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   setOperationAction(ISD::ADDC,      MVT::i32, Custom);
826   setOperationAction(ISD::ADDE,      MVT::i32, Custom);
827   setOperationAction(ISD::SUBC,      MVT::i32, Custom);
828   setOperationAction(ISD::SUBE,      MVT::i32, Custom);
829 
830   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
831     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
832 
833   // ARM does not have ROTL.
834   setOperationAction(ISD::ROTL, MVT::i32, Expand);
835   for (MVT VT : MVT::vector_valuetypes()) {
836     setOperationAction(ISD::ROTL, VT, Expand);
837     setOperationAction(ISD::ROTR, VT, Expand);
838   }
839   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
840   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
841   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
842     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
843 
844   // @llvm.readcyclecounter requires the Performance Monitors extension.
845   // Default to the 0 expansion on unsupported platforms.
846   // FIXME: Technically there are older ARM CPUs that have
847   // implementation-specific ways of obtaining this information.
848   if (Subtarget->hasPerfMon())
849     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
850 
851   // Only ARMv6 has BSWAP.
852   if (!Subtarget->hasV6Ops())
853     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
854 
855   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivide()
856                                         : Subtarget->hasDivideInARMMode();
857   if (!hasDivide) {
858     // These are expanded into libcalls if the cpu doesn't have HW divider.
859     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
860     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
861   }
862 
863   if (Subtarget->isTargetWindows() && !Subtarget->hasDivide()) {
864     setOperationAction(ISD::SDIV, MVT::i32, Custom);
865     setOperationAction(ISD::UDIV, MVT::i32, Custom);
866 
867     setOperationAction(ISD::SDIV, MVT::i64, Custom);
868     setOperationAction(ISD::UDIV, MVT::i64, Custom);
869   }
870 
871   setOperationAction(ISD::SREM,  MVT::i32, Expand);
872   setOperationAction(ISD::UREM,  MVT::i32, Expand);
873 
874   // Register based DivRem for AEABI (RTABI 4.2)
875   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
876       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
877       Subtarget->isTargetWindows()) {
878     setOperationAction(ISD::SREM, MVT::i64, Custom);
879     setOperationAction(ISD::UREM, MVT::i64, Custom);
880     HasStandaloneRem = false;
881 
882     if (Subtarget->isTargetWindows()) {
883       const struct {
884         const RTLIB::Libcall Op;
885         const char * const Name;
886         const CallingConv::ID CC;
887       } LibraryCalls[] = {
888         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
889         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
890         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
891         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
892 
893         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
894         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
895         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
896         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
897       };
898 
899       for (const auto &LC : LibraryCalls) {
900         setLibcallName(LC.Op, LC.Name);
901         setLibcallCallingConv(LC.Op, LC.CC);
902       }
903     } else {
904       const struct {
905         const RTLIB::Libcall Op;
906         const char * const Name;
907         const CallingConv::ID CC;
908       } LibraryCalls[] = {
909         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
910         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
911         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
912         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
913 
914         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
915         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
916         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
917         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
918       };
919 
920       for (const auto &LC : LibraryCalls) {
921         setLibcallName(LC.Op, LC.Name);
922         setLibcallCallingConv(LC.Op, LC.CC);
923       }
924     }
925 
926     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
927     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
928     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
929     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
930   } else {
931     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
932     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
933   }
934 
935   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
936     for (auto &VT : {MVT::f32, MVT::f64})
937       setOperationAction(ISD::FPOWI, VT, Custom);
938 
939   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
940   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
941   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
942   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
943 
944   setOperationAction(ISD::TRAP, MVT::Other, Legal);
945 
946   // Use the default implementation.
947   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
948   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
949   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
950   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
951   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
952   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
953 
954   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
955     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
956   else
957     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
958 
959   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
960   // the default expansion.
961   InsertFencesForAtomic = false;
962   if (Subtarget->hasAnyDataBarrier() &&
963       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
964     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
965     // to ldrex/strex loops already.
966     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
967     if (!Subtarget->isThumb() || !Subtarget->isMClass())
968       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
969 
970     // On v8, we have particularly efficient implementations of atomic fences
971     // if they can be combined with nearby atomic loads and stores.
972     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
973       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
974       InsertFencesForAtomic = true;
975     }
976   } else {
977     // If there's anything we can use as a barrier, go through custom lowering
978     // for ATOMIC_FENCE.
979     // If target has DMB in thumb, Fences can be inserted.
980     if (Subtarget->hasDataBarrier())
981       InsertFencesForAtomic = true;
982 
983     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
984                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
985 
986     // Set them all for expansion, which will force libcalls.
987     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
988     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
989     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
990     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
991     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
992     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
993     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
994     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
995     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
996     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
997     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
998     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
999     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1000     // Unordered/Monotonic case.
1001     if (!InsertFencesForAtomic) {
1002       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1003       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1004     }
1005   }
1006 
1007   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1008 
1009   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1010   if (!Subtarget->hasV6Ops()) {
1011     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1012     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1013   }
1014   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1015 
1016   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1017       !Subtarget->isThumb1Only()) {
1018     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1019     // iff target supports vfp2.
1020     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1021     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1022   }
1023 
1024   // We want to custom lower some of our intrinsics.
1025   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1026   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1027   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1028   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1029   if (Subtarget->useSjLjEH())
1030     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1031 
1032   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1033   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1034   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1035   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1036   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1037   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1038   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1039   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1040   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1041 
1042   // Thumb-1 cannot currently select ARMISD::SUBE.
1043   if (!Subtarget->isThumb1Only())
1044     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1045 
1046   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
1047   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1048   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1049   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1050   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1051 
1052   // We don't support sin/cos/fmod/copysign/pow
1053   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1054   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1055   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1056   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1057   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1058   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1059   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1060   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1061   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1062       !Subtarget->isThumb1Only()) {
1063     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1064     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1065   }
1066   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1067   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1068 
1069   if (!Subtarget->hasVFP4()) {
1070     setOperationAction(ISD::FMA, MVT::f64, Expand);
1071     setOperationAction(ISD::FMA, MVT::f32, Expand);
1072   }
1073 
1074   // Various VFP goodness
1075   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1076     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1077     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1078       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1079       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1080     }
1081 
1082     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1083     if (!Subtarget->hasFP16()) {
1084       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1085       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1086     }
1087   }
1088 
1089   // Combine sin / cos into one node or libcall if possible.
1090   if (Subtarget->hasSinCos()) {
1091     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1092     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1093     if (Subtarget->isTargetWatchABI()) {
1094       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
1095       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
1096     }
1097     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
1098       // For iOS, we don't want to the normal expansion of a libcall to
1099       // sincos. We want to issue a libcall to __sincos_stret.
1100       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1101       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1102     }
1103   }
1104 
1105   // FP-ARMv8 implements a lot of rounding-like FP operations.
1106   if (Subtarget->hasFPARMv8()) {
1107     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1108     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1109     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1110     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1111     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1112     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1113     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1114     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1115     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1116     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1117     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1118     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1119 
1120     if (!Subtarget->isFPOnlySP()) {
1121       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1122       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1123       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1124       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1125       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1126       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1127       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1128       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1129     }
1130   }
1131 
1132   if (Subtarget->hasNEON()) {
1133     // vmin and vmax aren't available in a scalar form, so we use
1134     // a NEON instruction with an undef lane instead.
1135     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1136     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1137     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1138     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1139     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1140     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1141   }
1142 
1143   // We have target-specific dag combine patterns for the following nodes:
1144   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1145   setTargetDAGCombine(ISD::ADD);
1146   setTargetDAGCombine(ISD::SUB);
1147   setTargetDAGCombine(ISD::MUL);
1148   setTargetDAGCombine(ISD::AND);
1149   setTargetDAGCombine(ISD::OR);
1150   setTargetDAGCombine(ISD::XOR);
1151 
1152   if (Subtarget->hasV6Ops())
1153     setTargetDAGCombine(ISD::SRL);
1154 
1155   setStackPointerRegisterToSaveRestore(ARM::SP);
1156 
1157   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1158       !Subtarget->hasVFP2())
1159     setSchedulingPreference(Sched::RegPressure);
1160   else
1161     setSchedulingPreference(Sched::Hybrid);
1162 
1163   //// temporary - rewrite interface to use type
1164   MaxStoresPerMemset = 8;
1165   MaxStoresPerMemsetOptSize = 4;
1166   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1167   MaxStoresPerMemcpyOptSize = 2;
1168   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1169   MaxStoresPerMemmoveOptSize = 2;
1170 
1171   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1172   // are at least 4 bytes aligned.
1173   setMinStackArgumentAlignment(4);
1174 
1175   // Prefer likely predicted branches to selects on out-of-order cores.
1176   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1177 
1178   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1179 }
1180 
1181 bool ARMTargetLowering::useSoftFloat() const {
1182   return Subtarget->useSoftFloat();
1183 }
1184 
1185 // FIXME: It might make sense to define the representative register class as the
1186 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1187 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1188 // SPR's representative would be DPR_VFP2. This should work well if register
1189 // pressure tracking were modified such that a register use would increment the
1190 // pressure of the register class's representative and all of it's super
1191 // classes' representatives transitively. We have not implemented this because
1192 // of the difficulty prior to coalescing of modeling operand register classes
1193 // due to the common occurrence of cross class copies and subregister insertions
1194 // and extractions.
1195 std::pair<const TargetRegisterClass *, uint8_t>
1196 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1197                                            MVT VT) const {
1198   const TargetRegisterClass *RRC = nullptr;
1199   uint8_t Cost = 1;
1200   switch (VT.SimpleTy) {
1201   default:
1202     return TargetLowering::findRepresentativeClass(TRI, VT);
1203   // Use DPR as representative register class for all floating point
1204   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1205   // the cost is 1 for both f32 and f64.
1206   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1207   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1208     RRC = &ARM::DPRRegClass;
1209     // When NEON is used for SP, only half of the register file is available
1210     // because operations that define both SP and DP results will be constrained
1211     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1212     // coalescing by double-counting the SP regs. See the FIXME above.
1213     if (Subtarget->useNEONForSinglePrecisionFP())
1214       Cost = 2;
1215     break;
1216   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1217   case MVT::v4f32: case MVT::v2f64:
1218     RRC = &ARM::DPRRegClass;
1219     Cost = 2;
1220     break;
1221   case MVT::v4i64:
1222     RRC = &ARM::DPRRegClass;
1223     Cost = 4;
1224     break;
1225   case MVT::v8i64:
1226     RRC = &ARM::DPRRegClass;
1227     Cost = 8;
1228     break;
1229   }
1230   return std::make_pair(RRC, Cost);
1231 }
1232 
1233 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1234   switch ((ARMISD::NodeType)Opcode) {
1235   case ARMISD::FIRST_NUMBER:  break;
1236   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1237   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1238   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1239   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1240   case ARMISD::CALL:          return "ARMISD::CALL";
1241   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1242   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1243   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1244   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1245   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1246   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1247   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1248   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1249   case ARMISD::CMP:           return "ARMISD::CMP";
1250   case ARMISD::CMN:           return "ARMISD::CMN";
1251   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1252   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1253   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1254   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1255   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1256 
1257   case ARMISD::CMOV:          return "ARMISD::CMOV";
1258 
1259   case ARMISD::SSAT:          return "ARMISD::SSAT";
1260 
1261   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1262   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1263   case ARMISD::RRX:           return "ARMISD::RRX";
1264 
1265   case ARMISD::ADDC:          return "ARMISD::ADDC";
1266   case ARMISD::ADDE:          return "ARMISD::ADDE";
1267   case ARMISD::SUBC:          return "ARMISD::SUBC";
1268   case ARMISD::SUBE:          return "ARMISD::SUBE";
1269 
1270   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1271   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1272 
1273   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1274   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1275   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1276 
1277   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1278 
1279   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1280 
1281   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1282 
1283   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1284 
1285   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1286 
1287   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1288   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1289 
1290   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1291   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1292   case ARMISD::VCGE:          return "ARMISD::VCGE";
1293   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1294   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1295   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1296   case ARMISD::VCGT:          return "ARMISD::VCGT";
1297   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1298   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1299   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1300   case ARMISD::VTST:          return "ARMISD::VTST";
1301 
1302   case ARMISD::VSHL:          return "ARMISD::VSHL";
1303   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1304   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1305   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1306   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1307   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1308   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1309   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1310   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1311   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1312   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1313   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1314   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1315   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1316   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1317   case ARMISD::VSLI:          return "ARMISD::VSLI";
1318   case ARMISD::VSRI:          return "ARMISD::VSRI";
1319   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1320   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1321   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1322   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1323   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1324   case ARMISD::VDUP:          return "ARMISD::VDUP";
1325   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1326   case ARMISD::VEXT:          return "ARMISD::VEXT";
1327   case ARMISD::VREV64:        return "ARMISD::VREV64";
1328   case ARMISD::VREV32:        return "ARMISD::VREV32";
1329   case ARMISD::VREV16:        return "ARMISD::VREV16";
1330   case ARMISD::VZIP:          return "ARMISD::VZIP";
1331   case ARMISD::VUZP:          return "ARMISD::VUZP";
1332   case ARMISD::VTRN:          return "ARMISD::VTRN";
1333   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1334   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1335   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1336   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1337   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1338   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1339   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1340   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1341   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1342   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1343   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1344   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1345   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1346   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1347   case ARMISD::BFI:           return "ARMISD::BFI";
1348   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1349   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1350   case ARMISD::VBSL:          return "ARMISD::VBSL";
1351   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1352   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1353   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1354   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1355   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1356   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1357   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1358   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1359   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1360   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1361   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1362   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1363   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1364   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1365   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1366   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1367   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1368   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1369   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1370   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1371   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1372   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1373   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1374   }
1375   return nullptr;
1376 }
1377 
1378 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1379                                           EVT VT) const {
1380   if (!VT.isVector())
1381     return getPointerTy(DL);
1382   return VT.changeVectorElementTypeToInteger();
1383 }
1384 
1385 /// getRegClassFor - Return the register class that should be used for the
1386 /// specified value type.
1387 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1388   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1389   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1390   // load / store 4 to 8 consecutive D registers.
1391   if (Subtarget->hasNEON()) {
1392     if (VT == MVT::v4i64)
1393       return &ARM::QQPRRegClass;
1394     if (VT == MVT::v8i64)
1395       return &ARM::QQQQPRRegClass;
1396   }
1397   return TargetLowering::getRegClassFor(VT);
1398 }
1399 
1400 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1401 // source/dest is aligned and the copy size is large enough. We therefore want
1402 // to align such objects passed to memory intrinsics.
1403 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1404                                                unsigned &PrefAlign) const {
1405   if (!isa<MemIntrinsic>(CI))
1406     return false;
1407   MinSize = 8;
1408   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1409   // cycle faster than 4-byte aligned LDM.
1410   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1411   return true;
1412 }
1413 
1414 // Create a fast isel object.
1415 FastISel *
1416 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1417                                   const TargetLibraryInfo *libInfo) const {
1418   return ARM::createFastISel(funcInfo, libInfo);
1419 }
1420 
1421 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1422   unsigned NumVals = N->getNumValues();
1423   if (!NumVals)
1424     return Sched::RegPressure;
1425 
1426   for (unsigned i = 0; i != NumVals; ++i) {
1427     EVT VT = N->getValueType(i);
1428     if (VT == MVT::Glue || VT == MVT::Other)
1429       continue;
1430     if (VT.isFloatingPoint() || VT.isVector())
1431       return Sched::ILP;
1432   }
1433 
1434   if (!N->isMachineOpcode())
1435     return Sched::RegPressure;
1436 
1437   // Load are scheduled for latency even if there instruction itinerary
1438   // is not available.
1439   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1440   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1441 
1442   if (MCID.getNumDefs() == 0)
1443     return Sched::RegPressure;
1444   if (!Itins->isEmpty() &&
1445       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1446     return Sched::ILP;
1447 
1448   return Sched::RegPressure;
1449 }
1450 
1451 //===----------------------------------------------------------------------===//
1452 // Lowering Code
1453 //===----------------------------------------------------------------------===//
1454 
1455 static bool isSRL16(const SDValue &Op) {
1456   if (Op.getOpcode() != ISD::SRL)
1457     return false;
1458   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1459     return Const->getZExtValue() == 16;
1460   return false;
1461 }
1462 
1463 static bool isSRA16(const SDValue &Op) {
1464   if (Op.getOpcode() != ISD::SRA)
1465     return false;
1466   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1467     return Const->getZExtValue() == 16;
1468   return false;
1469 }
1470 
1471 static bool isSHL16(const SDValue &Op) {
1472   if (Op.getOpcode() != ISD::SHL)
1473     return false;
1474   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1475     return Const->getZExtValue() == 16;
1476   return false;
1477 }
1478 
1479 // Check for a signed 16-bit value. We special case SRA because it makes it
1480 // more simple when also looking for SRAs that aren't sign extending a
1481 // smaller value. Without the check, we'd need to take extra care with
1482 // checking order for some operations.
1483 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1484   if (isSRA16(Op))
1485     return isSHL16(Op.getOperand(0));
1486   return DAG.ComputeNumSignBits(Op) == 17;
1487 }
1488 
1489 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1490 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1491   switch (CC) {
1492   default: llvm_unreachable("Unknown condition code!");
1493   case ISD::SETNE:  return ARMCC::NE;
1494   case ISD::SETEQ:  return ARMCC::EQ;
1495   case ISD::SETGT:  return ARMCC::GT;
1496   case ISD::SETGE:  return ARMCC::GE;
1497   case ISD::SETLT:  return ARMCC::LT;
1498   case ISD::SETLE:  return ARMCC::LE;
1499   case ISD::SETUGT: return ARMCC::HI;
1500   case ISD::SETUGE: return ARMCC::HS;
1501   case ISD::SETULT: return ARMCC::LO;
1502   case ISD::SETULE: return ARMCC::LS;
1503   }
1504 }
1505 
1506 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1507 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1508                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1509   CondCode2 = ARMCC::AL;
1510   InvalidOnQNaN = true;
1511   switch (CC) {
1512   default: llvm_unreachable("Unknown FP condition!");
1513   case ISD::SETEQ:
1514   case ISD::SETOEQ:
1515     CondCode = ARMCC::EQ;
1516     InvalidOnQNaN = false;
1517     break;
1518   case ISD::SETGT:
1519   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1520   case ISD::SETGE:
1521   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1522   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1523   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1524   case ISD::SETONE:
1525     CondCode = ARMCC::MI;
1526     CondCode2 = ARMCC::GT;
1527     InvalidOnQNaN = false;
1528     break;
1529   case ISD::SETO:   CondCode = ARMCC::VC; break;
1530   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1531   case ISD::SETUEQ:
1532     CondCode = ARMCC::EQ;
1533     CondCode2 = ARMCC::VS;
1534     InvalidOnQNaN = false;
1535     break;
1536   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1537   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1538   case ISD::SETLT:
1539   case ISD::SETULT: CondCode = ARMCC::LT; break;
1540   case ISD::SETLE:
1541   case ISD::SETULE: CondCode = ARMCC::LE; break;
1542   case ISD::SETNE:
1543   case ISD::SETUNE:
1544     CondCode = ARMCC::NE;
1545     InvalidOnQNaN = false;
1546     break;
1547   }
1548 }
1549 
1550 //===----------------------------------------------------------------------===//
1551 //                      Calling Convention Implementation
1552 //===----------------------------------------------------------------------===//
1553 
1554 #include "ARMGenCallingConv.inc"
1555 
1556 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1557 /// account presence of floating point hardware and calling convention
1558 /// limitations, such as support for variadic functions.
1559 CallingConv::ID
1560 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1561                                            bool isVarArg) const {
1562   switch (CC) {
1563   default:
1564     llvm_unreachable("Unsupported calling convention");
1565   case CallingConv::ARM_AAPCS:
1566   case CallingConv::ARM_APCS:
1567   case CallingConv::GHC:
1568     return CC;
1569   case CallingConv::PreserveMost:
1570     return CallingConv::PreserveMost;
1571   case CallingConv::ARM_AAPCS_VFP:
1572   case CallingConv::Swift:
1573     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1574   case CallingConv::C:
1575     if (!Subtarget->isAAPCS_ABI())
1576       return CallingConv::ARM_APCS;
1577     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1578              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1579              !isVarArg)
1580       return CallingConv::ARM_AAPCS_VFP;
1581     else
1582       return CallingConv::ARM_AAPCS;
1583   case CallingConv::Fast:
1584   case CallingConv::CXX_FAST_TLS:
1585     if (!Subtarget->isAAPCS_ABI()) {
1586       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1587         return CallingConv::Fast;
1588       return CallingConv::ARM_APCS;
1589     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1590       return CallingConv::ARM_AAPCS_VFP;
1591     else
1592       return CallingConv::ARM_AAPCS;
1593   }
1594 }
1595 
1596 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1597                                                  bool isVarArg) const {
1598   return CCAssignFnForNode(CC, false, isVarArg);
1599 }
1600 
1601 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1602                                                    bool isVarArg) const {
1603   return CCAssignFnForNode(CC, true, isVarArg);
1604 }
1605 
1606 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1607 /// CallingConvention.
1608 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1609                                                  bool Return,
1610                                                  bool isVarArg) const {
1611   switch (getEffectiveCallingConv(CC, isVarArg)) {
1612   default:
1613     llvm_unreachable("Unsupported calling convention");
1614   case CallingConv::ARM_APCS:
1615     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1616   case CallingConv::ARM_AAPCS:
1617     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1618   case CallingConv::ARM_AAPCS_VFP:
1619     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1620   case CallingConv::Fast:
1621     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1622   case CallingConv::GHC:
1623     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1624   case CallingConv::PreserveMost:
1625     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1626   }
1627 }
1628 
1629 /// LowerCallResult - Lower the result values of a call into the
1630 /// appropriate copies out of appropriate physical registers.
1631 SDValue ARMTargetLowering::LowerCallResult(
1632     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1633     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1634     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1635     SDValue ThisVal) const {
1636 
1637   // Assign locations to each value returned by this call.
1638   SmallVector<CCValAssign, 16> RVLocs;
1639   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1640                  *DAG.getContext());
1641   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1642 
1643   // Copy all of the result registers out of their specified physreg.
1644   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1645     CCValAssign VA = RVLocs[i];
1646 
1647     // Pass 'this' value directly from the argument to return value, to avoid
1648     // reg unit interference
1649     if (i == 0 && isThisReturn) {
1650       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1651              "unexpected return calling convention register assignment");
1652       InVals.push_back(ThisVal);
1653       continue;
1654     }
1655 
1656     SDValue Val;
1657     if (VA.needsCustom()) {
1658       // Handle f64 or half of a v2f64.
1659       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1660                                       InFlag);
1661       Chain = Lo.getValue(1);
1662       InFlag = Lo.getValue(2);
1663       VA = RVLocs[++i]; // skip ahead to next loc
1664       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1665                                       InFlag);
1666       Chain = Hi.getValue(1);
1667       InFlag = Hi.getValue(2);
1668       if (!Subtarget->isLittle())
1669         std::swap (Lo, Hi);
1670       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1671 
1672       if (VA.getLocVT() == MVT::v2f64) {
1673         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1674         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1675                           DAG.getConstant(0, dl, MVT::i32));
1676 
1677         VA = RVLocs[++i]; // skip ahead to next loc
1678         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1679         Chain = Lo.getValue(1);
1680         InFlag = Lo.getValue(2);
1681         VA = RVLocs[++i]; // skip ahead to next loc
1682         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1683         Chain = Hi.getValue(1);
1684         InFlag = Hi.getValue(2);
1685         if (!Subtarget->isLittle())
1686           std::swap (Lo, Hi);
1687         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1688         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1689                           DAG.getConstant(1, dl, MVT::i32));
1690       }
1691     } else {
1692       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1693                                InFlag);
1694       Chain = Val.getValue(1);
1695       InFlag = Val.getValue(2);
1696     }
1697 
1698     switch (VA.getLocInfo()) {
1699     default: llvm_unreachable("Unknown loc info!");
1700     case CCValAssign::Full: break;
1701     case CCValAssign::BCvt:
1702       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1703       break;
1704     }
1705 
1706     InVals.push_back(Val);
1707   }
1708 
1709   return Chain;
1710 }
1711 
1712 /// LowerMemOpCallTo - Store the argument to the stack.
1713 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1714                                             SDValue Arg, const SDLoc &dl,
1715                                             SelectionDAG &DAG,
1716                                             const CCValAssign &VA,
1717                                             ISD::ArgFlagsTy Flags) const {
1718   unsigned LocMemOffset = VA.getLocMemOffset();
1719   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1720   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1721                        StackPtr, PtrOff);
1722   return DAG.getStore(
1723       Chain, dl, Arg, PtrOff,
1724       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1725 }
1726 
1727 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1728                                          SDValue Chain, SDValue &Arg,
1729                                          RegsToPassVector &RegsToPass,
1730                                          CCValAssign &VA, CCValAssign &NextVA,
1731                                          SDValue &StackPtr,
1732                                          SmallVectorImpl<SDValue> &MemOpChains,
1733                                          ISD::ArgFlagsTy Flags) const {
1734 
1735   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1736                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1737   unsigned id = Subtarget->isLittle() ? 0 : 1;
1738   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1739 
1740   if (NextVA.isRegLoc())
1741     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1742   else {
1743     assert(NextVA.isMemLoc());
1744     if (!StackPtr.getNode())
1745       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1746                                     getPointerTy(DAG.getDataLayout()));
1747 
1748     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1749                                            dl, DAG, NextVA,
1750                                            Flags));
1751   }
1752 }
1753 
1754 /// LowerCall - Lowering a call into a callseq_start <-
1755 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1756 /// nodes.
1757 SDValue
1758 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1759                              SmallVectorImpl<SDValue> &InVals) const {
1760   SelectionDAG &DAG                     = CLI.DAG;
1761   SDLoc &dl                             = CLI.DL;
1762   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1763   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1764   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1765   SDValue Chain                         = CLI.Chain;
1766   SDValue Callee                        = CLI.Callee;
1767   bool &isTailCall                      = CLI.IsTailCall;
1768   CallingConv::ID CallConv              = CLI.CallConv;
1769   bool doesNotRet                       = CLI.DoesNotReturn;
1770   bool isVarArg                         = CLI.IsVarArg;
1771 
1772   MachineFunction &MF = DAG.getMachineFunction();
1773   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1774   bool isThisReturn   = false;
1775   bool isSibCall      = false;
1776   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1777 
1778   // Disable tail calls if they're not supported.
1779   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1780     isTailCall = false;
1781 
1782   if (isTailCall) {
1783     // Check if it's really possible to do a tail call.
1784     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1785                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1786                                                    Outs, OutVals, Ins, DAG);
1787     if (!isTailCall && CLI.CS && CLI.CS->isMustTailCall())
1788       report_fatal_error("failed to perform tail call elimination on a call "
1789                          "site marked musttail");
1790     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1791     // detected sibcalls.
1792     if (isTailCall) {
1793       ++NumTailCalls;
1794       isSibCall = true;
1795     }
1796   }
1797 
1798   // Analyze operands of the call, assigning locations to each operand.
1799   SmallVector<CCValAssign, 16> ArgLocs;
1800   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1801                  *DAG.getContext());
1802   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1803 
1804   // Get a count of how many bytes are to be pushed on the stack.
1805   unsigned NumBytes = CCInfo.getNextStackOffset();
1806 
1807   // For tail calls, memory operands are available in our caller's stack.
1808   if (isSibCall)
1809     NumBytes = 0;
1810 
1811   // Adjust the stack pointer for the new arguments...
1812   // These operations are automatically eliminated by the prolog/epilog pass
1813   if (!isSibCall)
1814     Chain = DAG.getCALLSEQ_START(Chain,
1815                                  DAG.getIntPtrConstant(NumBytes, dl, true), dl);
1816 
1817   SDValue StackPtr =
1818       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1819 
1820   RegsToPassVector RegsToPass;
1821   SmallVector<SDValue, 8> MemOpChains;
1822 
1823   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1824   // of tail call optimization, arguments are handled later.
1825   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1826        i != e;
1827        ++i, ++realArgIdx) {
1828     CCValAssign &VA = ArgLocs[i];
1829     SDValue Arg = OutVals[realArgIdx];
1830     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1831     bool isByVal = Flags.isByVal();
1832 
1833     // Promote the value if needed.
1834     switch (VA.getLocInfo()) {
1835     default: llvm_unreachable("Unknown loc info!");
1836     case CCValAssign::Full: break;
1837     case CCValAssign::SExt:
1838       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1839       break;
1840     case CCValAssign::ZExt:
1841       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1842       break;
1843     case CCValAssign::AExt:
1844       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1845       break;
1846     case CCValAssign::BCvt:
1847       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1848       break;
1849     }
1850 
1851     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1852     if (VA.needsCustom()) {
1853       if (VA.getLocVT() == MVT::v2f64) {
1854         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1855                                   DAG.getConstant(0, dl, MVT::i32));
1856         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1857                                   DAG.getConstant(1, dl, MVT::i32));
1858 
1859         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1860                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1861 
1862         VA = ArgLocs[++i]; // skip ahead to next loc
1863         if (VA.isRegLoc()) {
1864           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1865                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1866         } else {
1867           assert(VA.isMemLoc());
1868 
1869           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1870                                                  dl, DAG, VA, Flags));
1871         }
1872       } else {
1873         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1874                          StackPtr, MemOpChains, Flags);
1875       }
1876     } else if (VA.isRegLoc()) {
1877       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1878           Outs[0].VT == MVT::i32) {
1879         assert(VA.getLocVT() == MVT::i32 &&
1880                "unexpected calling convention register assignment");
1881         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1882                "unexpected use of 'returned'");
1883         isThisReturn = true;
1884       }
1885       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1886     } else if (isByVal) {
1887       assert(VA.isMemLoc());
1888       unsigned offset = 0;
1889 
1890       // True if this byval aggregate will be split between registers
1891       // and memory.
1892       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1893       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1894 
1895       if (CurByValIdx < ByValArgsCount) {
1896 
1897         unsigned RegBegin, RegEnd;
1898         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1899 
1900         EVT PtrVT =
1901             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1902         unsigned int i, j;
1903         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1904           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1905           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1906           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1907                                      MachinePointerInfo(),
1908                                      DAG.InferPtrAlignment(AddArg));
1909           MemOpChains.push_back(Load.getValue(1));
1910           RegsToPass.push_back(std::make_pair(j, Load));
1911         }
1912 
1913         // If parameter size outsides register area, "offset" value
1914         // helps us to calculate stack slot for remained part properly.
1915         offset = RegEnd - RegBegin;
1916 
1917         CCInfo.nextInRegsParam();
1918       }
1919 
1920       if (Flags.getByValSize() > 4*offset) {
1921         auto PtrVT = getPointerTy(DAG.getDataLayout());
1922         unsigned LocMemOffset = VA.getLocMemOffset();
1923         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1924         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1925         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1926         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1927         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1928                                            MVT::i32);
1929         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1930                                             MVT::i32);
1931 
1932         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1933         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1934         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1935                                           Ops));
1936       }
1937     } else if (!isSibCall) {
1938       assert(VA.isMemLoc());
1939 
1940       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1941                                              dl, DAG, VA, Flags));
1942     }
1943   }
1944 
1945   if (!MemOpChains.empty())
1946     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1947 
1948   // Build a sequence of copy-to-reg nodes chained together with token chain
1949   // and flag operands which copy the outgoing args into the appropriate regs.
1950   SDValue InFlag;
1951   // Tail call byval lowering might overwrite argument registers so in case of
1952   // tail call optimization the copies to registers are lowered later.
1953   if (!isTailCall)
1954     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1955       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1956                                RegsToPass[i].second, InFlag);
1957       InFlag = Chain.getValue(1);
1958     }
1959 
1960   // For tail calls lower the arguments to the 'real' stack slot.
1961   if (isTailCall) {
1962     // Force all the incoming stack arguments to be loaded from the stack
1963     // before any new outgoing arguments are stored to the stack, because the
1964     // outgoing stack slots may alias the incoming argument stack slots, and
1965     // the alias isn't otherwise explicit. This is slightly more conservative
1966     // than necessary, because it means that each store effectively depends
1967     // on every argument instead of just those arguments it would clobber.
1968 
1969     // Do not flag preceding copytoreg stuff together with the following stuff.
1970     InFlag = SDValue();
1971     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1972       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1973                                RegsToPass[i].second, InFlag);
1974       InFlag = Chain.getValue(1);
1975     }
1976     InFlag = SDValue();
1977   }
1978 
1979   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1980   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1981   // node so that legalize doesn't hack it.
1982   bool isDirect = false;
1983 
1984   const TargetMachine &TM = getTargetMachine();
1985   const Module *Mod = MF.getFunction()->getParent();
1986   const GlobalValue *GV = nullptr;
1987   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1988     GV = G->getGlobal();
1989   bool isStub =
1990       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1991 
1992   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1993   bool isLocalARMFunc = false;
1994   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1995   auto PtrVt = getPointerTy(DAG.getDataLayout());
1996 
1997   if (Subtarget->genLongCalls()) {
1998     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
1999            "long-calls codegen is not position independent!");
2000     // Handle a global address or an external symbol. If it's not one of
2001     // those, the target's already in a register, so we don't need to do
2002     // anything extra.
2003     if (isa<GlobalAddressSDNode>(Callee)) {
2004       // Create a constant pool entry for the callee address
2005       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2006       ARMConstantPoolValue *CPV =
2007         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2008 
2009       // Get the address of the callee into a register
2010       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2011       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2012       Callee = DAG.getLoad(
2013           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2014           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2015     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2016       const char *Sym = S->getSymbol();
2017 
2018       // Create a constant pool entry for the callee address
2019       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2020       ARMConstantPoolValue *CPV =
2021         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2022                                       ARMPCLabelIndex, 0);
2023       // Get the address of the callee into a register
2024       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2025       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2026       Callee = DAG.getLoad(
2027           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2028           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2029     }
2030   } else if (isa<GlobalAddressSDNode>(Callee)) {
2031     // If we're optimizing for minimum size and the function is called three or
2032     // more times in this block, we can improve codesize by calling indirectly
2033     // as BLXr has a 16-bit encoding.
2034     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2035     auto *BB = CLI.CS->getParent();
2036     bool PreferIndirect =
2037         Subtarget->isThumb() && MF.getFunction()->optForMinSize() &&
2038         count_if(GV->users(), [&BB](const User *U) {
2039           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2040         }) > 2;
2041 
2042     if (!PreferIndirect) {
2043       isDirect = true;
2044       bool isDef = GV->isStrongDefinitionForLinker();
2045 
2046       // ARM call to a local ARM function is predicable.
2047       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2048       // tBX takes a register source operand.
2049       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2050         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2051         Callee = DAG.getNode(
2052             ARMISD::WrapperPIC, dl, PtrVt,
2053             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2054         Callee = DAG.getLoad(
2055             PtrVt, dl, DAG.getEntryNode(), Callee,
2056             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2057             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2058                                      MachineMemOperand::MOInvariant);
2059       } else if (Subtarget->isTargetCOFF()) {
2060         assert(Subtarget->isTargetWindows() &&
2061                "Windows is the only supported COFF target");
2062         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2063                                    ? ARMII::MO_DLLIMPORT
2064                                    : ARMII::MO_NO_FLAG;
2065         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2066                                             TargetFlags);
2067         if (GV->hasDLLImportStorageClass())
2068           Callee =
2069               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2070                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2071                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2072       } else {
2073         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2074       }
2075     }
2076   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2077     isDirect = true;
2078     // tBX takes a register source operand.
2079     const char *Sym = S->getSymbol();
2080     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2081       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2082       ARMConstantPoolValue *CPV =
2083         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2084                                       ARMPCLabelIndex, 4);
2085       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2086       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2087       Callee = DAG.getLoad(
2088           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2089           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2090       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2091       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2092     } else {
2093       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2094     }
2095   }
2096 
2097   // FIXME: handle tail calls differently.
2098   unsigned CallOpc;
2099   if (Subtarget->isThumb()) {
2100     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2101       CallOpc = ARMISD::CALL_NOLINK;
2102     else
2103       CallOpc = ARMISD::CALL;
2104   } else {
2105     if (!isDirect && !Subtarget->hasV5TOps())
2106       CallOpc = ARMISD::CALL_NOLINK;
2107     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2108              // Emit regular call when code size is the priority
2109              !MF.getFunction()->optForMinSize())
2110       // "mov lr, pc; b _foo" to avoid confusing the RSP
2111       CallOpc = ARMISD::CALL_NOLINK;
2112     else
2113       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2114   }
2115 
2116   std::vector<SDValue> Ops;
2117   Ops.push_back(Chain);
2118   Ops.push_back(Callee);
2119 
2120   // Add argument registers to the end of the list so that they are known live
2121   // into the call.
2122   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2123     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2124                                   RegsToPass[i].second.getValueType()));
2125 
2126   // Add a register mask operand representing the call-preserved registers.
2127   if (!isTailCall) {
2128     const uint32_t *Mask;
2129     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2130     if (isThisReturn) {
2131       // For 'this' returns, use the R0-preserving mask if applicable
2132       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2133       if (!Mask) {
2134         // Set isThisReturn to false if the calling convention is not one that
2135         // allows 'returned' to be modeled in this way, so LowerCallResult does
2136         // not try to pass 'this' straight through
2137         isThisReturn = false;
2138         Mask = ARI->getCallPreservedMask(MF, CallConv);
2139       }
2140     } else
2141       Mask = ARI->getCallPreservedMask(MF, CallConv);
2142 
2143     assert(Mask && "Missing call preserved mask for calling convention");
2144     Ops.push_back(DAG.getRegisterMask(Mask));
2145   }
2146 
2147   if (InFlag.getNode())
2148     Ops.push_back(InFlag);
2149 
2150   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2151   if (isTailCall) {
2152     MF.getFrameInfo().setHasTailCall();
2153     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2154   }
2155 
2156   // Returns a chain and a flag for retval copy to use.
2157   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2158   InFlag = Chain.getValue(1);
2159 
2160   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2161                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2162   if (!Ins.empty())
2163     InFlag = Chain.getValue(1);
2164 
2165   // Handle result values, copying them out of physregs into vregs that we
2166   // return.
2167   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2168                          InVals, isThisReturn,
2169                          isThisReturn ? OutVals[0] : SDValue());
2170 }
2171 
2172 /// HandleByVal - Every parameter *after* a byval parameter is passed
2173 /// on the stack.  Remember the next parameter register to allocate,
2174 /// and then confiscate the rest of the parameter registers to insure
2175 /// this.
2176 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2177                                     unsigned Align) const {
2178   // Byval (as with any stack) slots are always at least 4 byte aligned.
2179   Align = std::max(Align, 4U);
2180 
2181   unsigned Reg = State->AllocateReg(GPRArgRegs);
2182   if (!Reg)
2183     return;
2184 
2185   unsigned AlignInRegs = Align / 4;
2186   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2187   for (unsigned i = 0; i < Waste; ++i)
2188     Reg = State->AllocateReg(GPRArgRegs);
2189 
2190   if (!Reg)
2191     return;
2192 
2193   unsigned Excess = 4 * (ARM::R4 - Reg);
2194 
2195   // Special case when NSAA != SP and parameter size greater than size of
2196   // all remained GPR regs. In that case we can't split parameter, we must
2197   // send it to stack. We also must set NCRN to R4, so waste all
2198   // remained registers.
2199   const unsigned NSAAOffset = State->getNextStackOffset();
2200   if (NSAAOffset != 0 && Size > Excess) {
2201     while (State->AllocateReg(GPRArgRegs))
2202       ;
2203     return;
2204   }
2205 
2206   // First register for byval parameter is the first register that wasn't
2207   // allocated before this method call, so it would be "reg".
2208   // If parameter is small enough to be saved in range [reg, r4), then
2209   // the end (first after last) register would be reg + param-size-in-regs,
2210   // else parameter would be splitted between registers and stack,
2211   // end register would be r4 in this case.
2212   unsigned ByValRegBegin = Reg;
2213   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2214   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2215   // Note, first register is allocated in the beginning of function already,
2216   // allocate remained amount of registers we need.
2217   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2218     State->AllocateReg(GPRArgRegs);
2219   // A byval parameter that is split between registers and memory needs its
2220   // size truncated here.
2221   // In the case where the entire structure fits in registers, we set the
2222   // size in memory to zero.
2223   Size = std::max<int>(Size - Excess, 0);
2224 }
2225 
2226 /// MatchingStackOffset - Return true if the given stack call argument is
2227 /// already available in the same position (relatively) of the caller's
2228 /// incoming argument stack.
2229 static
2230 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2231                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2232                          const TargetInstrInfo *TII) {
2233   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2234   int FI = std::numeric_limits<int>::max();
2235   if (Arg.getOpcode() == ISD::CopyFromReg) {
2236     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2237     if (!TargetRegisterInfo::isVirtualRegister(VR))
2238       return false;
2239     MachineInstr *Def = MRI->getVRegDef(VR);
2240     if (!Def)
2241       return false;
2242     if (!Flags.isByVal()) {
2243       if (!TII->isLoadFromStackSlot(*Def, FI))
2244         return false;
2245     } else {
2246       return false;
2247     }
2248   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2249     if (Flags.isByVal())
2250       // ByVal argument is passed in as a pointer but it's now being
2251       // dereferenced. e.g.
2252       // define @foo(%struct.X* %A) {
2253       //   tail call @bar(%struct.X* byval %A)
2254       // }
2255       return false;
2256     SDValue Ptr = Ld->getBasePtr();
2257     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2258     if (!FINode)
2259       return false;
2260     FI = FINode->getIndex();
2261   } else
2262     return false;
2263 
2264   assert(FI != std::numeric_limits<int>::max());
2265   if (!MFI.isFixedObjectIndex(FI))
2266     return false;
2267   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2268 }
2269 
2270 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2271 /// for tail call optimization. Targets which want to do tail call
2272 /// optimization should implement this function.
2273 bool
2274 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2275                                                      CallingConv::ID CalleeCC,
2276                                                      bool isVarArg,
2277                                                      bool isCalleeStructRet,
2278                                                      bool isCallerStructRet,
2279                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2280                                     const SmallVectorImpl<SDValue> &OutVals,
2281                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2282                                                      SelectionDAG& DAG) const {
2283   MachineFunction &MF = DAG.getMachineFunction();
2284   const Function *CallerF = MF.getFunction();
2285   CallingConv::ID CallerCC = CallerF->getCallingConv();
2286 
2287   assert(Subtarget->supportsTailCall());
2288 
2289   // Look for obvious safe cases to perform tail call optimization that do not
2290   // require ABI changes. This is what gcc calls sibcall.
2291 
2292   // Exception-handling functions need a special set of instructions to indicate
2293   // a return to the hardware. Tail-calling another function would probably
2294   // break this.
2295   if (CallerF->hasFnAttribute("interrupt"))
2296     return false;
2297 
2298   // Also avoid sibcall optimization if either caller or callee uses struct
2299   // return semantics.
2300   if (isCalleeStructRet || isCallerStructRet)
2301     return false;
2302 
2303   // Externally-defined functions with weak linkage should not be
2304   // tail-called on ARM when the OS does not support dynamic
2305   // pre-emption of symbols, as the AAELF spec requires normal calls
2306   // to undefined weak functions to be replaced with a NOP or jump to the
2307   // next instruction. The behaviour of branch instructions in this
2308   // situation (as used for tail calls) is implementation-defined, so we
2309   // cannot rely on the linker replacing the tail call with a return.
2310   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2311     const GlobalValue *GV = G->getGlobal();
2312     const Triple &TT = getTargetMachine().getTargetTriple();
2313     if (GV->hasExternalWeakLinkage() &&
2314         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2315       return false;
2316   }
2317 
2318   // Check that the call results are passed in the same way.
2319   LLVMContext &C = *DAG.getContext();
2320   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2321                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2322                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2323     return false;
2324   // The callee has to preserve all registers the caller needs to preserve.
2325   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2326   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2327   if (CalleeCC != CallerCC) {
2328     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2329     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2330       return false;
2331   }
2332 
2333   // If Caller's vararg or byval argument has been split between registers and
2334   // stack, do not perform tail call, since part of the argument is in caller's
2335   // local frame.
2336   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2337   if (AFI_Caller->getArgRegsSaveSize())
2338     return false;
2339 
2340   // If the callee takes no arguments then go on to check the results of the
2341   // call.
2342   if (!Outs.empty()) {
2343     // Check if stack adjustment is needed. For now, do not do this if any
2344     // argument is passed on the stack.
2345     SmallVector<CCValAssign, 16> ArgLocs;
2346     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2347     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2348     if (CCInfo.getNextStackOffset()) {
2349       // Check if the arguments are already laid out in the right way as
2350       // the caller's fixed stack objects.
2351       MachineFrameInfo &MFI = MF.getFrameInfo();
2352       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2353       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2354       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2355            i != e;
2356            ++i, ++realArgIdx) {
2357         CCValAssign &VA = ArgLocs[i];
2358         EVT RegVT = VA.getLocVT();
2359         SDValue Arg = OutVals[realArgIdx];
2360         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2361         if (VA.getLocInfo() == CCValAssign::Indirect)
2362           return false;
2363         if (VA.needsCustom()) {
2364           // f64 and vector types are split into multiple registers or
2365           // register/stack-slot combinations.  The types will not match
2366           // the registers; give up on memory f64 refs until we figure
2367           // out what to do about this.
2368           if (!VA.isRegLoc())
2369             return false;
2370           if (!ArgLocs[++i].isRegLoc())
2371             return false;
2372           if (RegVT == MVT::v2f64) {
2373             if (!ArgLocs[++i].isRegLoc())
2374               return false;
2375             if (!ArgLocs[++i].isRegLoc())
2376               return false;
2377           }
2378         } else if (!VA.isRegLoc()) {
2379           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2380                                    MFI, MRI, TII))
2381             return false;
2382         }
2383       }
2384     }
2385 
2386     const MachineRegisterInfo &MRI = MF.getRegInfo();
2387     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2388       return false;
2389   }
2390 
2391   return true;
2392 }
2393 
2394 bool
2395 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2396                                   MachineFunction &MF, bool isVarArg,
2397                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2398                                   LLVMContext &Context) const {
2399   SmallVector<CCValAssign, 16> RVLocs;
2400   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2401   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2402 }
2403 
2404 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2405                                     const SDLoc &DL, SelectionDAG &DAG) {
2406   const MachineFunction &MF = DAG.getMachineFunction();
2407   const Function *F = MF.getFunction();
2408 
2409   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2410 
2411   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2412   // version of the "preferred return address". These offsets affect the return
2413   // instruction if this is a return from PL1 without hypervisor extensions.
2414   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2415   //    SWI:     0      "subs pc, lr, #0"
2416   //    ABORT:   +4     "subs pc, lr, #4"
2417   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2418   // UNDEF varies depending on where the exception came from ARM or Thumb
2419   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2420 
2421   int64_t LROffset;
2422   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2423       IntKind == "ABORT")
2424     LROffset = 4;
2425   else if (IntKind == "SWI" || IntKind == "UNDEF")
2426     LROffset = 0;
2427   else
2428     report_fatal_error("Unsupported interrupt attribute. If present, value "
2429                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2430 
2431   RetOps.insert(RetOps.begin() + 1,
2432                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2433 
2434   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2435 }
2436 
2437 SDValue
2438 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2439                                bool isVarArg,
2440                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2441                                const SmallVectorImpl<SDValue> &OutVals,
2442                                const SDLoc &dl, SelectionDAG &DAG) const {
2443 
2444   // CCValAssign - represent the assignment of the return value to a location.
2445   SmallVector<CCValAssign, 16> RVLocs;
2446 
2447   // CCState - Info about the registers and stack slots.
2448   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2449                  *DAG.getContext());
2450 
2451   // Analyze outgoing return values.
2452   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2453 
2454   SDValue Flag;
2455   SmallVector<SDValue, 4> RetOps;
2456   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2457   bool isLittleEndian = Subtarget->isLittle();
2458 
2459   MachineFunction &MF = DAG.getMachineFunction();
2460   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2461   AFI->setReturnRegsCount(RVLocs.size());
2462 
2463   // Copy the result values into the output registers.
2464   for (unsigned i = 0, realRVLocIdx = 0;
2465        i != RVLocs.size();
2466        ++i, ++realRVLocIdx) {
2467     CCValAssign &VA = RVLocs[i];
2468     assert(VA.isRegLoc() && "Can only return in registers!");
2469 
2470     SDValue Arg = OutVals[realRVLocIdx];
2471 
2472     switch (VA.getLocInfo()) {
2473     default: llvm_unreachable("Unknown loc info!");
2474     case CCValAssign::Full: break;
2475     case CCValAssign::BCvt:
2476       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2477       break;
2478     }
2479 
2480     if (VA.needsCustom()) {
2481       if (VA.getLocVT() == MVT::v2f64) {
2482         // Extract the first half and return it in two registers.
2483         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2484                                    DAG.getConstant(0, dl, MVT::i32));
2485         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2486                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2487 
2488         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2489                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2490                                  Flag);
2491         Flag = Chain.getValue(1);
2492         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2493         VA = RVLocs[++i]; // skip ahead to next loc
2494         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2495                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2496                                  Flag);
2497         Flag = Chain.getValue(1);
2498         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2499         VA = RVLocs[++i]; // skip ahead to next loc
2500 
2501         // Extract the 2nd half and fall through to handle it as an f64 value.
2502         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2503                           DAG.getConstant(1, dl, MVT::i32));
2504       }
2505       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2506       // available.
2507       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2508                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2509       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2510                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2511                                Flag);
2512       Flag = Chain.getValue(1);
2513       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2514       VA = RVLocs[++i]; // skip ahead to next loc
2515       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2516                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2517                                Flag);
2518     } else
2519       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2520 
2521     // Guarantee that all emitted copies are
2522     // stuck together, avoiding something bad.
2523     Flag = Chain.getValue(1);
2524     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2525   }
2526   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2527   const MCPhysReg *I =
2528       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2529   if (I) {
2530     for (; *I; ++I) {
2531       if (ARM::GPRRegClass.contains(*I))
2532         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2533       else if (ARM::DPRRegClass.contains(*I))
2534         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2535       else
2536         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2537     }
2538   }
2539 
2540   // Update chain and glue.
2541   RetOps[0] = Chain;
2542   if (Flag.getNode())
2543     RetOps.push_back(Flag);
2544 
2545   // CPUs which aren't M-class use a special sequence to return from
2546   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2547   // though we use "subs pc, lr, #N").
2548   //
2549   // M-class CPUs actually use a normal return sequence with a special
2550   // (hardware-provided) value in LR, so the normal code path works.
2551   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2552       !Subtarget->isMClass()) {
2553     if (Subtarget->isThumb1Only())
2554       report_fatal_error("interrupt attribute is not supported in Thumb1");
2555     return LowerInterruptReturn(RetOps, dl, DAG);
2556   }
2557 
2558   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2559 }
2560 
2561 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2562   if (N->getNumValues() != 1)
2563     return false;
2564   if (!N->hasNUsesOfValue(1, 0))
2565     return false;
2566 
2567   SDValue TCChain = Chain;
2568   SDNode *Copy = *N->use_begin();
2569   if (Copy->getOpcode() == ISD::CopyToReg) {
2570     // If the copy has a glue operand, we conservatively assume it isn't safe to
2571     // perform a tail call.
2572     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2573       return false;
2574     TCChain = Copy->getOperand(0);
2575   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2576     SDNode *VMov = Copy;
2577     // f64 returned in a pair of GPRs.
2578     SmallPtrSet<SDNode*, 2> Copies;
2579     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2580          UI != UE; ++UI) {
2581       if (UI->getOpcode() != ISD::CopyToReg)
2582         return false;
2583       Copies.insert(*UI);
2584     }
2585     if (Copies.size() > 2)
2586       return false;
2587 
2588     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2589          UI != UE; ++UI) {
2590       SDValue UseChain = UI->getOperand(0);
2591       if (Copies.count(UseChain.getNode()))
2592         // Second CopyToReg
2593         Copy = *UI;
2594       else {
2595         // We are at the top of this chain.
2596         // If the copy has a glue operand, we conservatively assume it
2597         // isn't safe to perform a tail call.
2598         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2599           return false;
2600         // First CopyToReg
2601         TCChain = UseChain;
2602       }
2603     }
2604   } else if (Copy->getOpcode() == ISD::BITCAST) {
2605     // f32 returned in a single GPR.
2606     if (!Copy->hasOneUse())
2607       return false;
2608     Copy = *Copy->use_begin();
2609     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2610       return false;
2611     // If the copy has a glue operand, we conservatively assume it isn't safe to
2612     // perform a tail call.
2613     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2614       return false;
2615     TCChain = Copy->getOperand(0);
2616   } else {
2617     return false;
2618   }
2619 
2620   bool HasRet = false;
2621   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2622        UI != UE; ++UI) {
2623     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2624         UI->getOpcode() != ARMISD::INTRET_FLAG)
2625       return false;
2626     HasRet = true;
2627   }
2628 
2629   if (!HasRet)
2630     return false;
2631 
2632   Chain = TCChain;
2633   return true;
2634 }
2635 
2636 bool ARMTargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2637   if (!Subtarget->supportsTailCall())
2638     return false;
2639 
2640   auto Attr =
2641       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2642   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2643     return false;
2644 
2645   return true;
2646 }
2647 
2648 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2649 // and pass the lower and high parts through.
2650 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2651   SDLoc DL(Op);
2652   SDValue WriteValue = Op->getOperand(2);
2653 
2654   // This function is only supposed to be called for i64 type argument.
2655   assert(WriteValue.getValueType() == MVT::i64
2656           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2657 
2658   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2659                            DAG.getConstant(0, DL, MVT::i32));
2660   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2661                            DAG.getConstant(1, DL, MVT::i32));
2662   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2663   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2664 }
2665 
2666 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2667 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2668 // one of the above mentioned nodes. It has to be wrapped because otherwise
2669 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2670 // be used to form addressing mode. These wrapped nodes will be selected
2671 // into MOVi.
2672 static SDValue LowerConstantPool(SDValue Op, SelectionDAG &DAG) {
2673   EVT PtrVT = Op.getValueType();
2674   // FIXME there is no actual debug info here
2675   SDLoc dl(Op);
2676   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2677   SDValue Res;
2678   if (CP->isMachineConstantPoolEntry())
2679     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2680                                     CP->getAlignment());
2681   else
2682     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2683                                     CP->getAlignment());
2684   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2685 }
2686 
2687 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2688   return MachineJumpTableInfo::EK_Inline;
2689 }
2690 
2691 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2692                                              SelectionDAG &DAG) const {
2693   MachineFunction &MF = DAG.getMachineFunction();
2694   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2695   unsigned ARMPCLabelIndex = 0;
2696   SDLoc DL(Op);
2697   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2698   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2699   SDValue CPAddr;
2700   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2701   if (!IsPositionIndependent) {
2702     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2703   } else {
2704     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2705     ARMPCLabelIndex = AFI->createPICLabelUId();
2706     ARMConstantPoolValue *CPV =
2707       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2708                                       ARMCP::CPBlockAddress, PCAdj);
2709     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2710   }
2711   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2712   SDValue Result = DAG.getLoad(
2713       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2714       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2715   if (!IsPositionIndependent)
2716     return Result;
2717   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2718   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2719 }
2720 
2721 /// \brief Convert a TLS address reference into the correct sequence of loads
2722 /// and calls to compute the variable's address for Darwin, and return an
2723 /// SDValue containing the final node.
2724 
2725 /// Darwin only has one TLS scheme which must be capable of dealing with the
2726 /// fully general situation, in the worst case. This means:
2727 ///     + "extern __thread" declaration.
2728 ///     + Defined in a possibly unknown dynamic library.
2729 ///
2730 /// The general system is that each __thread variable has a [3 x i32] descriptor
2731 /// which contains information used by the runtime to calculate the address. The
2732 /// only part of this the compiler needs to know about is the first word, which
2733 /// contains a function pointer that must be called with the address of the
2734 /// entire descriptor in "r0".
2735 ///
2736 /// Since this descriptor may be in a different unit, in general access must
2737 /// proceed along the usual ARM rules. A common sequence to produce is:
2738 ///
2739 ///     movw rT1, :lower16:_var$non_lazy_ptr
2740 ///     movt rT1, :upper16:_var$non_lazy_ptr
2741 ///     ldr r0, [rT1]
2742 ///     ldr rT2, [r0]
2743 ///     blx rT2
2744 ///     [...address now in r0...]
2745 SDValue
2746 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2747                                                SelectionDAG &DAG) const {
2748   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2749   SDLoc DL(Op);
2750 
2751   // First step is to get the address of the actua global symbol. This is where
2752   // the TLS descriptor lives.
2753   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2754 
2755   // The first entry in the descriptor is a function pointer that we must call
2756   // to obtain the address of the variable.
2757   SDValue Chain = DAG.getEntryNode();
2758   SDValue FuncTLVGet = DAG.getLoad(
2759       MVT::i32, DL, Chain, DescAddr,
2760       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2761       /* Alignment = */ 4,
2762       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2763           MachineMemOperand::MOInvariant);
2764   Chain = FuncTLVGet.getValue(1);
2765 
2766   MachineFunction &F = DAG.getMachineFunction();
2767   MachineFrameInfo &MFI = F.getFrameInfo();
2768   MFI.setAdjustsStack(true);
2769 
2770   // TLS calls preserve all registers except those that absolutely must be
2771   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2772   // silly).
2773   auto TRI =
2774       getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2775   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2776   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2777 
2778   // Finally, we can make the call. This is just a degenerate version of a
2779   // normal AArch64 call node: r0 takes the address of the descriptor, and
2780   // returns the address of the variable in this thread.
2781   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2782   Chain =
2783       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2784                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2785                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2786   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2787 }
2788 
2789 SDValue
2790 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2791                                                 SelectionDAG &DAG) const {
2792   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2793 
2794   SDValue Chain = DAG.getEntryNode();
2795   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2796   SDLoc DL(Op);
2797 
2798   // Load the current TEB (thread environment block)
2799   SDValue Ops[] = {Chain,
2800                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2801                    DAG.getConstant(15, DL, MVT::i32),
2802                    DAG.getConstant(0, DL, MVT::i32),
2803                    DAG.getConstant(13, DL, MVT::i32),
2804                    DAG.getConstant(0, DL, MVT::i32),
2805                    DAG.getConstant(2, DL, MVT::i32)};
2806   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2807                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2808 
2809   SDValue TEB = CurrentTEB.getValue(0);
2810   Chain = CurrentTEB.getValue(1);
2811 
2812   // Load the ThreadLocalStoragePointer from the TEB
2813   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2814   SDValue TLSArray =
2815       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2816   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2817 
2818   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2819   // offset into the TLSArray.
2820 
2821   // Load the TLS index from the C runtime
2822   SDValue TLSIndex =
2823       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2824   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2825   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2826 
2827   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2828                               DAG.getConstant(2, DL, MVT::i32));
2829   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2830                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2831                             MachinePointerInfo());
2832 
2833   // Get the offset of the start of the .tls section (section base)
2834   const auto *GA = cast<GlobalAddressSDNode>(Op);
2835   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2836   SDValue Offset = DAG.getLoad(
2837       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2838                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2839       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2840 
2841   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2842 }
2843 
2844 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2845 SDValue
2846 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2847                                                  SelectionDAG &DAG) const {
2848   SDLoc dl(GA);
2849   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2850   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2851   MachineFunction &MF = DAG.getMachineFunction();
2852   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2853   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2854   ARMConstantPoolValue *CPV =
2855     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2856                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2857   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2858   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2859   Argument = DAG.getLoad(
2860       PtrVT, dl, DAG.getEntryNode(), Argument,
2861       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2862   SDValue Chain = Argument.getValue(1);
2863 
2864   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2865   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2866 
2867   // call __tls_get_addr.
2868   ArgListTy Args;
2869   ArgListEntry Entry;
2870   Entry.Node = Argument;
2871   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2872   Args.push_back(Entry);
2873 
2874   // FIXME: is there useful debug info available here?
2875   TargetLowering::CallLoweringInfo CLI(DAG);
2876   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2877       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2878       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2879 
2880   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2881   return CallResult.first;
2882 }
2883 
2884 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2885 // "local exec" model.
2886 SDValue
2887 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2888                                         SelectionDAG &DAG,
2889                                         TLSModel::Model model) const {
2890   const GlobalValue *GV = GA->getGlobal();
2891   SDLoc dl(GA);
2892   SDValue Offset;
2893   SDValue Chain = DAG.getEntryNode();
2894   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2895   // Get the Thread Pointer
2896   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2897 
2898   if (model == TLSModel::InitialExec) {
2899     MachineFunction &MF = DAG.getMachineFunction();
2900     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2901     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2902     // Initial exec model.
2903     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2904     ARMConstantPoolValue *CPV =
2905       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2906                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2907                                       true);
2908     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2909     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2910     Offset = DAG.getLoad(
2911         PtrVT, dl, Chain, Offset,
2912         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2913     Chain = Offset.getValue(1);
2914 
2915     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2916     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2917 
2918     Offset = DAG.getLoad(
2919         PtrVT, dl, Chain, Offset,
2920         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2921   } else {
2922     // local exec model
2923     assert(model == TLSModel::LocalExec);
2924     ARMConstantPoolValue *CPV =
2925       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2926     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2927     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2928     Offset = DAG.getLoad(
2929         PtrVT, dl, Chain, Offset,
2930         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2931   }
2932 
2933   // The address of the thread local variable is the add of the thread
2934   // pointer with the offset of the variable.
2935   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2936 }
2937 
2938 SDValue
2939 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2940   if (Subtarget->isTargetDarwin())
2941     return LowerGlobalTLSAddressDarwin(Op, DAG);
2942 
2943   if (Subtarget->isTargetWindows())
2944     return LowerGlobalTLSAddressWindows(Op, DAG);
2945 
2946   // TODO: implement the "local dynamic" model
2947   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2948   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2949   if (DAG.getTarget().Options.EmulatedTLS)
2950     return LowerToTLSEmulatedModel(GA, DAG);
2951 
2952   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2953 
2954   switch (model) {
2955     case TLSModel::GeneralDynamic:
2956     case TLSModel::LocalDynamic:
2957       return LowerToTLSGeneralDynamicModel(GA, DAG);
2958     case TLSModel::InitialExec:
2959     case TLSModel::LocalExec:
2960       return LowerToTLSExecModels(GA, DAG, model);
2961   }
2962   llvm_unreachable("bogus TLS model");
2963 }
2964 
2965 /// Return true if all users of V are within function F, looking through
2966 /// ConstantExprs.
2967 static bool allUsersAreInFunction(const Value *V, const Function *F) {
2968   SmallVector<const User*,4> Worklist;
2969   for (auto *U : V->users())
2970     Worklist.push_back(U);
2971   while (!Worklist.empty()) {
2972     auto *U = Worklist.pop_back_val();
2973     if (isa<ConstantExpr>(U)) {
2974       for (auto *UU : U->users())
2975         Worklist.push_back(UU);
2976       continue;
2977     }
2978 
2979     auto *I = dyn_cast<Instruction>(U);
2980     if (!I || I->getParent()->getParent() != F)
2981       return false;
2982   }
2983   return true;
2984 }
2985 
2986 /// Return true if all users of V are within some (any) function, looking through
2987 /// ConstantExprs. In other words, are there any global constant users?
2988 static bool allUsersAreInFunctions(const Value *V) {
2989   SmallVector<const User*,4> Worklist;
2990   for (auto *U : V->users())
2991     Worklist.push_back(U);
2992   while (!Worklist.empty()) {
2993     auto *U = Worklist.pop_back_val();
2994     if (isa<ConstantExpr>(U)) {
2995       for (auto *UU : U->users())
2996         Worklist.push_back(UU);
2997       continue;
2998     }
2999 
3000     if (!isa<Instruction>(U))
3001       return false;
3002   }
3003   return true;
3004 }
3005 
3006 // Return true if T is an integer, float or an array/vector of either.
3007 static bool isSimpleType(Type *T) {
3008   if (T->isIntegerTy() || T->isFloatingPointTy())
3009     return true;
3010   Type *SubT = nullptr;
3011   if (T->isArrayTy())
3012     SubT = T->getArrayElementType();
3013   else if (T->isVectorTy())
3014     SubT = T->getVectorElementType();
3015   else
3016     return false;
3017   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3018 }
3019 
3020 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3021                                      EVT PtrVT, const SDLoc &dl) {
3022   // If we're creating a pool entry for a constant global with unnamed address,
3023   // and the global is small enough, we can emit it inline into the constant pool
3024   // to save ourselves an indirection.
3025   //
3026   // This is a win if the constant is only used in one function (so it doesn't
3027   // need to be duplicated) or duplicating the constant wouldn't increase code
3028   // size (implying the constant is no larger than 4 bytes).
3029   const Function *F = DAG.getMachineFunction().getFunction();
3030 
3031   // We rely on this decision to inline being idemopotent and unrelated to the
3032   // use-site. We know that if we inline a variable at one use site, we'll
3033   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3034   // doesn't know about this optimization, so bail out if it's enabled else
3035   // we could decide to inline here (and thus never emit the GV) but require
3036   // the GV from fast-isel generated code.
3037   if (!EnableConstpoolPromotion ||
3038       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3039       return SDValue();
3040 
3041   auto *GVar = dyn_cast<GlobalVariable>(GV);
3042   if (!GVar || !GVar->hasInitializer() ||
3043       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3044       !GVar->hasLocalLinkage())
3045     return SDValue();
3046 
3047   // Ensure that we don't try and inline any type that contains pointers. If
3048   // we inline a value that contains relocations, we move the relocations from
3049   // .data to .text which is not ideal.
3050   auto *Init = GVar->getInitializer();
3051   if (!isSimpleType(Init->getType()))
3052     return SDValue();
3053 
3054   // The constant islands pass can only really deal with alignment requests
3055   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3056   // any type wanting greater alignment requirements than 4 bytes. We also
3057   // can only promote constants that are multiples of 4 bytes in size or
3058   // are paddable to a multiple of 4. Currently we only try and pad constants
3059   // that are strings for simplicity.
3060   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3061   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3062   unsigned Align = GVar->getAlignment();
3063   unsigned RequiredPadding = 4 - (Size % 4);
3064   bool PaddingPossible =
3065     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3066   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3067       Size == 0)
3068     return SDValue();
3069 
3070   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3071   MachineFunction &MF = DAG.getMachineFunction();
3072   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3073 
3074   // We can't bloat the constant pool too much, else the ConstantIslands pass
3075   // may fail to converge. If we haven't promoted this global yet (it may have
3076   // multiple uses), and promoting it would increase the constant pool size (Sz
3077   // > 4), ensure we have space to do so up to MaxTotal.
3078   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3079     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3080         ConstpoolPromotionMaxTotal)
3081       return SDValue();
3082 
3083   // This is only valid if all users are in a single function OR it has users
3084   // in multiple functions but it no larger than a pointer. We also check if
3085   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3086   // address taken.
3087   if (!allUsersAreInFunction(GVar, F) &&
3088       !(Size <= 4 && allUsersAreInFunctions(GVar)))
3089     return SDValue();
3090 
3091   // We're going to inline this global. Pad it out if needed.
3092   if (RequiredPadding != 4) {
3093     StringRef S = CDAInit->getAsString();
3094 
3095     SmallVector<uint8_t,16> V(S.size());
3096     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3097     while (RequiredPadding--)
3098       V.push_back(0);
3099     Init = ConstantDataArray::get(*DAG.getContext(), V);
3100   }
3101 
3102   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3103   SDValue CPAddr =
3104     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3105   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3106     AFI->markGlobalAsPromotedToConstantPool(GVar);
3107     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3108                                       PaddedSize - 4);
3109   }
3110   ++NumConstpoolPromoted;
3111   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3112 }
3113 
3114 static bool isReadOnly(const GlobalValue *GV) {
3115   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3116     GV = GA->getBaseObject();
3117   return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3118          isa<Function>(GV);
3119 }
3120 
3121 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3122                                                  SelectionDAG &DAG) const {
3123   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3124   SDLoc dl(Op);
3125   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3126   const TargetMachine &TM = getTargetMachine();
3127   bool IsRO = isReadOnly(GV);
3128 
3129   // promoteToConstantPool only if not generating XO text section
3130   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3131     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3132       return V;
3133 
3134   if (isPositionIndependent()) {
3135     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3136 
3137     MachineFunction &MF = DAG.getMachineFunction();
3138     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3139     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3140     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3141     SDLoc dl(Op);
3142     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3143     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
3144         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
3145         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
3146         /*AddCurrentAddress=*/UseGOT_PREL);
3147     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3148     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3149     SDValue Result = DAG.getLoad(
3150         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3151         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3152     SDValue Chain = Result.getValue(1);
3153     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3154     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3155     if (UseGOT_PREL)
3156       Result =
3157           DAG.getLoad(PtrVT, dl, Chain, Result,
3158                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3159     return Result;
3160   } else if (Subtarget->isROPI() && IsRO) {
3161     // PC-relative.
3162     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3163     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3164     return Result;
3165   } else if (Subtarget->isRWPI() && !IsRO) {
3166     // SB-relative.
3167     SDValue RelAddr;
3168     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3169       ++NumMovwMovt;
3170       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3171       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3172     } else { // use literal pool for address constant
3173       ARMConstantPoolValue *CPV =
3174         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3175       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3176       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3177       RelAddr = DAG.getLoad(
3178           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3179           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3180     }
3181     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3182     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3183     return Result;
3184   }
3185 
3186   // If we have T2 ops, we can materialize the address directly via movt/movw
3187   // pair. This is always cheaper.
3188   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3189     ++NumMovwMovt;
3190     // FIXME: Once remat is capable of dealing with instructions with register
3191     // operands, expand this into two nodes.
3192     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3193                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3194   } else {
3195     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3196     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3197     return DAG.getLoad(
3198         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3199         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3200   }
3201 }
3202 
3203 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3204                                                     SelectionDAG &DAG) const {
3205   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3206          "ROPI/RWPI not currently supported for Darwin");
3207   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3208   SDLoc dl(Op);
3209   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3210 
3211   if (Subtarget->useMovt(DAG.getMachineFunction()))
3212     ++NumMovwMovt;
3213 
3214   // FIXME: Once remat is capable of dealing with instructions with register
3215   // operands, expand this into multiple nodes
3216   unsigned Wrapper =
3217       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3218 
3219   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3220   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3221 
3222   if (Subtarget->isGVIndirectSymbol(GV))
3223     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3224                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3225   return Result;
3226 }
3227 
3228 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3229                                                      SelectionDAG &DAG) const {
3230   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3231   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3232          "Windows on ARM expects to use movw/movt");
3233   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3234          "ROPI/RWPI not currently supported for Windows");
3235 
3236   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3237   const ARMII::TOF TargetFlags =
3238     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3239   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3240   SDValue Result;
3241   SDLoc DL(Op);
3242 
3243   ++NumMovwMovt;
3244 
3245   // FIXME: Once remat is capable of dealing with instructions with register
3246   // operands, expand this into two nodes.
3247   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3248                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3249                                                   TargetFlags));
3250   if (GV->hasDLLImportStorageClass())
3251     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3252                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3253   return Result;
3254 }
3255 
3256 SDValue
3257 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3258   SDLoc dl(Op);
3259   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3260   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3261                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3262                      Op.getOperand(1), Val);
3263 }
3264 
3265 SDValue
3266 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3267   SDLoc dl(Op);
3268   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3269                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3270 }
3271 
3272 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3273                                                       SelectionDAG &DAG) const {
3274   SDLoc dl(Op);
3275   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3276                      Op.getOperand(0));
3277 }
3278 
3279 SDValue
3280 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3281                                           const ARMSubtarget *Subtarget) const {
3282   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3283   SDLoc dl(Op);
3284   switch (IntNo) {
3285   default: return SDValue();    // Don't custom lower most intrinsics.
3286   case Intrinsic::thread_pointer: {
3287     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3288     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3289   }
3290   case Intrinsic::eh_sjlj_lsda: {
3291     MachineFunction &MF = DAG.getMachineFunction();
3292     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3293     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3294     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3295     SDValue CPAddr;
3296     bool IsPositionIndependent = isPositionIndependent();
3297     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3298     ARMConstantPoolValue *CPV =
3299       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
3300                                       ARMCP::CPLSDA, PCAdj);
3301     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3302     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3303     SDValue Result = DAG.getLoad(
3304         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3305         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3306 
3307     if (IsPositionIndependent) {
3308       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3309       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3310     }
3311     return Result;
3312   }
3313   case Intrinsic::arm_neon_vmulls:
3314   case Intrinsic::arm_neon_vmullu: {
3315     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3316       ? ARMISD::VMULLs : ARMISD::VMULLu;
3317     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3318                        Op.getOperand(1), Op.getOperand(2));
3319   }
3320   case Intrinsic::arm_neon_vminnm:
3321   case Intrinsic::arm_neon_vmaxnm: {
3322     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3323       ? ISD::FMINNUM : ISD::FMAXNUM;
3324     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3325                        Op.getOperand(1), Op.getOperand(2));
3326   }
3327   case Intrinsic::arm_neon_vminu:
3328   case Intrinsic::arm_neon_vmaxu: {
3329     if (Op.getValueType().isFloatingPoint())
3330       return SDValue();
3331     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3332       ? ISD::UMIN : ISD::UMAX;
3333     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3334                          Op.getOperand(1), Op.getOperand(2));
3335   }
3336   case Intrinsic::arm_neon_vmins:
3337   case Intrinsic::arm_neon_vmaxs: {
3338     // v{min,max}s is overloaded between signed integers and floats.
3339     if (!Op.getValueType().isFloatingPoint()) {
3340       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3341         ? ISD::SMIN : ISD::SMAX;
3342       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3343                          Op.getOperand(1), Op.getOperand(2));
3344     }
3345     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3346       ? ISD::FMINNAN : ISD::FMAXNAN;
3347     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3348                        Op.getOperand(1), Op.getOperand(2));
3349   }
3350   }
3351 }
3352 
3353 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3354                                  const ARMSubtarget *Subtarget) {
3355   // FIXME: handle "fence singlethread" more efficiently.
3356   SDLoc dl(Op);
3357   if (!Subtarget->hasDataBarrier()) {
3358     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3359     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3360     // here.
3361     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3362            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3363     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3364                        DAG.getConstant(0, dl, MVT::i32));
3365   }
3366 
3367   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3368   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3369   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3370   if (Subtarget->isMClass()) {
3371     // Only a full system barrier exists in the M-class architectures.
3372     Domain = ARM_MB::SY;
3373   } else if (Subtarget->preferISHSTBarriers() &&
3374              Ord == AtomicOrdering::Release) {
3375     // Swift happens to implement ISHST barriers in a way that's compatible with
3376     // Release semantics but weaker than ISH so we'd be fools not to use
3377     // it. Beware: other processors probably don't!
3378     Domain = ARM_MB::ISHST;
3379   }
3380 
3381   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3382                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3383                      DAG.getConstant(Domain, dl, MVT::i32));
3384 }
3385 
3386 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3387                              const ARMSubtarget *Subtarget) {
3388   // ARM pre v5TE and Thumb1 does not have preload instructions.
3389   if (!(Subtarget->isThumb2() ||
3390         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3391     // Just preserve the chain.
3392     return Op.getOperand(0);
3393 
3394   SDLoc dl(Op);
3395   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3396   if (!isRead &&
3397       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3398     // ARMv7 with MP extension has PLDW.
3399     return Op.getOperand(0);
3400 
3401   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3402   if (Subtarget->isThumb()) {
3403     // Invert the bits.
3404     isRead = ~isRead & 1;
3405     isData = ~isData & 1;
3406   }
3407 
3408   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3409                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3410                      DAG.getConstant(isData, dl, MVT::i32));
3411 }
3412 
3413 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3414   MachineFunction &MF = DAG.getMachineFunction();
3415   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3416 
3417   // vastart just stores the address of the VarArgsFrameIndex slot into the
3418   // memory location argument.
3419   SDLoc dl(Op);
3420   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3421   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3422   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3423   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3424                       MachinePointerInfo(SV));
3425 }
3426 
3427 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3428                                                 CCValAssign &NextVA,
3429                                                 SDValue &Root,
3430                                                 SelectionDAG &DAG,
3431                                                 const SDLoc &dl) const {
3432   MachineFunction &MF = DAG.getMachineFunction();
3433   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3434 
3435   const TargetRegisterClass *RC;
3436   if (AFI->isThumb1OnlyFunction())
3437     RC = &ARM::tGPRRegClass;
3438   else
3439     RC = &ARM::GPRRegClass;
3440 
3441   // Transform the arguments stored in physical registers into virtual ones.
3442   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3443   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3444 
3445   SDValue ArgValue2;
3446   if (NextVA.isMemLoc()) {
3447     MachineFrameInfo &MFI = MF.getFrameInfo();
3448     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3449 
3450     // Create load node to retrieve arguments from the stack.
3451     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3452     ArgValue2 = DAG.getLoad(
3453         MVT::i32, dl, Root, FIN,
3454         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3455   } else {
3456     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3457     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3458   }
3459   if (!Subtarget->isLittle())
3460     std::swap (ArgValue, ArgValue2);
3461   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3462 }
3463 
3464 // The remaining GPRs hold either the beginning of variable-argument
3465 // data, or the beginning of an aggregate passed by value (usually
3466 // byval).  Either way, we allocate stack slots adjacent to the data
3467 // provided by our caller, and store the unallocated registers there.
3468 // If this is a variadic function, the va_list pointer will begin with
3469 // these values; otherwise, this reassembles a (byval) structure that
3470 // was split between registers and memory.
3471 // Return: The frame index registers were stored into.
3472 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3473                                       const SDLoc &dl, SDValue &Chain,
3474                                       const Value *OrigArg,
3475                                       unsigned InRegsParamRecordIdx,
3476                                       int ArgOffset, unsigned ArgSize) const {
3477   // Currently, two use-cases possible:
3478   // Case #1. Non-var-args function, and we meet first byval parameter.
3479   //          Setup first unallocated register as first byval register;
3480   //          eat all remained registers
3481   //          (these two actions are performed by HandleByVal method).
3482   //          Then, here, we initialize stack frame with
3483   //          "store-reg" instructions.
3484   // Case #2. Var-args function, that doesn't contain byval parameters.
3485   //          The same: eat all remained unallocated registers,
3486   //          initialize stack frame.
3487 
3488   MachineFunction &MF = DAG.getMachineFunction();
3489   MachineFrameInfo &MFI = MF.getFrameInfo();
3490   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3491   unsigned RBegin, REnd;
3492   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3493     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3494   } else {
3495     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3496     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3497     REnd = ARM::R4;
3498   }
3499 
3500   if (REnd != RBegin)
3501     ArgOffset = -4 * (ARM::R4 - RBegin);
3502 
3503   auto PtrVT = getPointerTy(DAG.getDataLayout());
3504   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3505   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3506 
3507   SmallVector<SDValue, 4> MemOps;
3508   const TargetRegisterClass *RC =
3509       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3510 
3511   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3512     unsigned VReg = MF.addLiveIn(Reg, RC);
3513     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3514     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3515                                  MachinePointerInfo(OrigArg, 4 * i));
3516     MemOps.push_back(Store);
3517     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3518   }
3519 
3520   if (!MemOps.empty())
3521     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3522   return FrameIndex;
3523 }
3524 
3525 // Setup stack frame, the va_list pointer will start from.
3526 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3527                                              const SDLoc &dl, SDValue &Chain,
3528                                              unsigned ArgOffset,
3529                                              unsigned TotalArgRegsSaveSize,
3530                                              bool ForceMutable) const {
3531   MachineFunction &MF = DAG.getMachineFunction();
3532   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3533 
3534   // Try to store any remaining integer argument regs
3535   // to their spots on the stack so that they may be loaded by dereferencing
3536   // the result of va_next.
3537   // If there is no regs to be stored, just point address after last
3538   // argument passed via stack.
3539   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3540                                   CCInfo.getInRegsParamsCount(),
3541                                   CCInfo.getNextStackOffset(), 4);
3542   AFI->setVarArgsFrameIndex(FrameIndex);
3543 }
3544 
3545 SDValue ARMTargetLowering::LowerFormalArguments(
3546     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3547     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3548     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3549   MachineFunction &MF = DAG.getMachineFunction();
3550   MachineFrameInfo &MFI = MF.getFrameInfo();
3551 
3552   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3553 
3554   // Assign locations to all of the incoming arguments.
3555   SmallVector<CCValAssign, 16> ArgLocs;
3556   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3557                  *DAG.getContext());
3558   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3559 
3560   SmallVector<SDValue, 16> ArgValues;
3561   SDValue ArgValue;
3562   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3563   unsigned CurArgIdx = 0;
3564 
3565   // Initially ArgRegsSaveSize is zero.
3566   // Then we increase this value each time we meet byval parameter.
3567   // We also increase this value in case of varargs function.
3568   AFI->setArgRegsSaveSize(0);
3569 
3570   // Calculate the amount of stack space that we need to allocate to store
3571   // byval and variadic arguments that are passed in registers.
3572   // We need to know this before we allocate the first byval or variadic
3573   // argument, as they will be allocated a stack slot below the CFA (Canonical
3574   // Frame Address, the stack pointer at entry to the function).
3575   unsigned ArgRegBegin = ARM::R4;
3576   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3577     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3578       break;
3579 
3580     CCValAssign &VA = ArgLocs[i];
3581     unsigned Index = VA.getValNo();
3582     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3583     if (!Flags.isByVal())
3584       continue;
3585 
3586     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3587     unsigned RBegin, REnd;
3588     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3589     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3590 
3591     CCInfo.nextInRegsParam();
3592   }
3593   CCInfo.rewindByValRegsInfo();
3594 
3595   int lastInsIndex = -1;
3596   if (isVarArg && MFI.hasVAStart()) {
3597     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3598     if (RegIdx != array_lengthof(GPRArgRegs))
3599       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3600   }
3601 
3602   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3603   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3604   auto PtrVT = getPointerTy(DAG.getDataLayout());
3605 
3606   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3607     CCValAssign &VA = ArgLocs[i];
3608     if (Ins[VA.getValNo()].isOrigArg()) {
3609       std::advance(CurOrigArg,
3610                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3611       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3612     }
3613     // Arguments stored in registers.
3614     if (VA.isRegLoc()) {
3615       EVT RegVT = VA.getLocVT();
3616 
3617       if (VA.needsCustom()) {
3618         // f64 and vector types are split up into multiple registers or
3619         // combinations of registers and stack slots.
3620         if (VA.getLocVT() == MVT::v2f64) {
3621           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3622                                                    Chain, DAG, dl);
3623           VA = ArgLocs[++i]; // skip ahead to next loc
3624           SDValue ArgValue2;
3625           if (VA.isMemLoc()) {
3626             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3627             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3628             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3629                                     MachinePointerInfo::getFixedStack(
3630                                         DAG.getMachineFunction(), FI));
3631           } else {
3632             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3633                                              Chain, DAG, dl);
3634           }
3635           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3636           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3637                                  ArgValue, ArgValue1,
3638                                  DAG.getIntPtrConstant(0, dl));
3639           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3640                                  ArgValue, ArgValue2,
3641                                  DAG.getIntPtrConstant(1, dl));
3642         } else
3643           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3644 
3645       } else {
3646         const TargetRegisterClass *RC;
3647 
3648         if (RegVT == MVT::f32)
3649           RC = &ARM::SPRRegClass;
3650         else if (RegVT == MVT::f64)
3651           RC = &ARM::DPRRegClass;
3652         else if (RegVT == MVT::v2f64)
3653           RC = &ARM::QPRRegClass;
3654         else if (RegVT == MVT::i32)
3655           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3656                                            : &ARM::GPRRegClass;
3657         else
3658           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3659 
3660         // Transform the arguments in physical registers into virtual ones.
3661         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3662         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3663       }
3664 
3665       // If this is an 8 or 16-bit value, it is really passed promoted
3666       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3667       // truncate to the right size.
3668       switch (VA.getLocInfo()) {
3669       default: llvm_unreachable("Unknown loc info!");
3670       case CCValAssign::Full: break;
3671       case CCValAssign::BCvt:
3672         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3673         break;
3674       case CCValAssign::SExt:
3675         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3676                                DAG.getValueType(VA.getValVT()));
3677         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3678         break;
3679       case CCValAssign::ZExt:
3680         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3681                                DAG.getValueType(VA.getValVT()));
3682         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3683         break;
3684       }
3685 
3686       InVals.push_back(ArgValue);
3687 
3688     } else { // VA.isRegLoc()
3689       // sanity check
3690       assert(VA.isMemLoc());
3691       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3692 
3693       int index = VA.getValNo();
3694 
3695       // Some Ins[] entries become multiple ArgLoc[] entries.
3696       // Process them only once.
3697       if (index != lastInsIndex)
3698         {
3699           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3700           // FIXME: For now, all byval parameter objects are marked mutable.
3701           // This can be changed with more analysis.
3702           // In case of tail call optimization mark all arguments mutable.
3703           // Since they could be overwritten by lowering of arguments in case of
3704           // a tail call.
3705           if (Flags.isByVal()) {
3706             assert(Ins[index].isOrigArg() &&
3707                    "Byval arguments cannot be implicit");
3708             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3709 
3710             int FrameIndex = StoreByValRegs(
3711                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3712                 VA.getLocMemOffset(), Flags.getByValSize());
3713             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3714             CCInfo.nextInRegsParam();
3715           } else {
3716             unsigned FIOffset = VA.getLocMemOffset();
3717             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3718                                            FIOffset, true);
3719 
3720             // Create load nodes to retrieve arguments from the stack.
3721             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3722             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3723                                          MachinePointerInfo::getFixedStack(
3724                                              DAG.getMachineFunction(), FI)));
3725           }
3726           lastInsIndex = index;
3727         }
3728     }
3729   }
3730 
3731   // varargs
3732   if (isVarArg && MFI.hasVAStart())
3733     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3734                          CCInfo.getNextStackOffset(),
3735                          TotalArgRegsSaveSize);
3736 
3737   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3738 
3739   return Chain;
3740 }
3741 
3742 /// isFloatingPointZero - Return true if this is +0.0.
3743 static bool isFloatingPointZero(SDValue Op) {
3744   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3745     return CFP->getValueAPF().isPosZero();
3746   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3747     // Maybe this has already been legalized into the constant pool?
3748     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3749       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3750       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3751         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3752           return CFP->getValueAPF().isPosZero();
3753     }
3754   } else if (Op->getOpcode() == ISD::BITCAST &&
3755              Op->getValueType(0) == MVT::f64) {
3756     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3757     // created by LowerConstantFP().
3758     SDValue BitcastOp = Op->getOperand(0);
3759     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3760         isNullConstant(BitcastOp->getOperand(0)))
3761       return true;
3762   }
3763   return false;
3764 }
3765 
3766 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3767 /// the given operands.
3768 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3769                                      SDValue &ARMcc, SelectionDAG &DAG,
3770                                      const SDLoc &dl) const {
3771   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3772     unsigned C = RHSC->getZExtValue();
3773     if (!isLegalICmpImmediate(C)) {
3774       // Constant does not fit, try adjusting it by one?
3775       switch (CC) {
3776       default: break;
3777       case ISD::SETLT:
3778       case ISD::SETGE:
3779         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3780           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3781           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3782         }
3783         break;
3784       case ISD::SETULT:
3785       case ISD::SETUGE:
3786         if (C != 0 && isLegalICmpImmediate(C-1)) {
3787           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3788           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3789         }
3790         break;
3791       case ISD::SETLE:
3792       case ISD::SETGT:
3793         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3794           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3795           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3796         }
3797         break;
3798       case ISD::SETULE:
3799       case ISD::SETUGT:
3800         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3801           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3802           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3803         }
3804         break;
3805       }
3806     }
3807   }
3808 
3809   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3810   ARMISD::NodeType CompareType;
3811   switch (CondCode) {
3812   default:
3813     CompareType = ARMISD::CMP;
3814     break;
3815   case ARMCC::EQ:
3816   case ARMCC::NE:
3817     // Uses only Z Flag
3818     CompareType = ARMISD::CMPZ;
3819     break;
3820   }
3821   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3822   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3823 }
3824 
3825 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3826 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3827                                      SelectionDAG &DAG, const SDLoc &dl,
3828                                      bool InvalidOnQNaN) const {
3829   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3830   SDValue Cmp;
3831   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3832   if (!isFloatingPointZero(RHS))
3833     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3834   else
3835     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3836   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3837 }
3838 
3839 /// duplicateCmp - Glue values can have only one use, so this function
3840 /// duplicates a comparison node.
3841 SDValue
3842 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3843   unsigned Opc = Cmp.getOpcode();
3844   SDLoc DL(Cmp);
3845   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3846     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3847 
3848   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3849   Cmp = Cmp.getOperand(0);
3850   Opc = Cmp.getOpcode();
3851   if (Opc == ARMISD::CMPFP)
3852     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3853                       Cmp.getOperand(1), Cmp.getOperand(2));
3854   else {
3855     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3856     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3857                       Cmp.getOperand(1));
3858   }
3859   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3860 }
3861 
3862 std::pair<SDValue, SDValue>
3863 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3864                                  SDValue &ARMcc) const {
3865   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3866 
3867   SDValue Value, OverflowCmp;
3868   SDValue LHS = Op.getOperand(0);
3869   SDValue RHS = Op.getOperand(1);
3870   SDLoc dl(Op);
3871 
3872   // FIXME: We are currently always generating CMPs because we don't support
3873   // generating CMN through the backend. This is not as good as the natural
3874   // CMP case because it causes a register dependency and cannot be folded
3875   // later.
3876 
3877   switch (Op.getOpcode()) {
3878   default:
3879     llvm_unreachable("Unknown overflow instruction!");
3880   case ISD::SADDO:
3881     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3882     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3883     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3884     break;
3885   case ISD::UADDO:
3886     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3887     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3888     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3889     break;
3890   case ISD::SSUBO:
3891     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3892     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3893     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3894     break;
3895   case ISD::USUBO:
3896     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3897     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3898     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3899     break;
3900   } // switch (...)
3901 
3902   return std::make_pair(Value, OverflowCmp);
3903 }
3904 
3905 SDValue
3906 ARMTargetLowering::LowerXALUO(SDValue Op, SelectionDAG &DAG) const {
3907   // Let legalize expand this if it isn't a legal type yet.
3908   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3909     return SDValue();
3910 
3911   SDValue Value, OverflowCmp;
3912   SDValue ARMcc;
3913   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3914   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3915   SDLoc dl(Op);
3916   // We use 0 and 1 as false and true values.
3917   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3918   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3919   EVT VT = Op.getValueType();
3920 
3921   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3922                                  ARMcc, CCR, OverflowCmp);
3923 
3924   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3925   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3926 }
3927 
3928 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
3929   SDValue Cond = Op.getOperand(0);
3930   SDValue SelectTrue = Op.getOperand(1);
3931   SDValue SelectFalse = Op.getOperand(2);
3932   SDLoc dl(Op);
3933   unsigned Opc = Cond.getOpcode();
3934 
3935   if (Cond.getResNo() == 1 &&
3936       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
3937        Opc == ISD::USUBO)) {
3938     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
3939       return SDValue();
3940 
3941     SDValue Value, OverflowCmp;
3942     SDValue ARMcc;
3943     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
3944     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3945     EVT VT = Op.getValueType();
3946 
3947     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
3948                    OverflowCmp, DAG);
3949   }
3950 
3951   // Convert:
3952   //
3953   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
3954   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
3955   //
3956   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
3957     const ConstantSDNode *CMOVTrue =
3958       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
3959     const ConstantSDNode *CMOVFalse =
3960       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
3961 
3962     if (CMOVTrue && CMOVFalse) {
3963       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
3964       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
3965 
3966       SDValue True;
3967       SDValue False;
3968       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
3969         True = SelectTrue;
3970         False = SelectFalse;
3971       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
3972         True = SelectFalse;
3973         False = SelectTrue;
3974       }
3975 
3976       if (True.getNode() && False.getNode()) {
3977         EVT VT = Op.getValueType();
3978         SDValue ARMcc = Cond.getOperand(2);
3979         SDValue CCR = Cond.getOperand(3);
3980         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
3981         assert(True.getValueType() == VT);
3982         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
3983       }
3984     }
3985   }
3986 
3987   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
3988   // undefined bits before doing a full-word comparison with zero.
3989   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
3990                      DAG.getConstant(1, dl, Cond.getValueType()));
3991 
3992   return DAG.getSelectCC(dl, Cond,
3993                          DAG.getConstant(0, dl, Cond.getValueType()),
3994                          SelectTrue, SelectFalse, ISD::SETNE);
3995 }
3996 
3997 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
3998                                  bool &swpCmpOps, bool &swpVselOps) {
3999   // Start by selecting the GE condition code for opcodes that return true for
4000   // 'equality'
4001   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4002       CC == ISD::SETULE)
4003     CondCode = ARMCC::GE;
4004 
4005   // and GT for opcodes that return false for 'equality'.
4006   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4007            CC == ISD::SETULT)
4008     CondCode = ARMCC::GT;
4009 
4010   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4011   // to swap the compare operands.
4012   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4013       CC == ISD::SETULT)
4014     swpCmpOps = true;
4015 
4016   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4017   // If we have an unordered opcode, we need to swap the operands to the VSEL
4018   // instruction (effectively negating the condition).
4019   //
4020   // This also has the effect of swapping which one of 'less' or 'greater'
4021   // returns true, so we also swap the compare operands. It also switches
4022   // whether we return true for 'equality', so we compensate by picking the
4023   // opposite condition code to our original choice.
4024   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4025       CC == ISD::SETUGT) {
4026     swpCmpOps = !swpCmpOps;
4027     swpVselOps = !swpVselOps;
4028     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4029   }
4030 
4031   // 'ordered' is 'anything but unordered', so use the VS condition code and
4032   // swap the VSEL operands.
4033   if (CC == ISD::SETO) {
4034     CondCode = ARMCC::VS;
4035     swpVselOps = true;
4036   }
4037 
4038   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4039   // code and swap the VSEL operands.
4040   if (CC == ISD::SETUNE) {
4041     CondCode = ARMCC::EQ;
4042     swpVselOps = true;
4043   }
4044 }
4045 
4046 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4047                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4048                                    SDValue Cmp, SelectionDAG &DAG) const {
4049   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4050     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4051                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4052     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4053                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4054 
4055     SDValue TrueLow = TrueVal.getValue(0);
4056     SDValue TrueHigh = TrueVal.getValue(1);
4057     SDValue FalseLow = FalseVal.getValue(0);
4058     SDValue FalseHigh = FalseVal.getValue(1);
4059 
4060     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4061                               ARMcc, CCR, Cmp);
4062     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4063                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4064 
4065     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4066   } else {
4067     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4068                        Cmp);
4069   }
4070 }
4071 
4072 static bool isGTorGE(ISD::CondCode CC) {
4073   return CC == ISD::SETGT || CC == ISD::SETGE;
4074 }
4075 
4076 static bool isLTorLE(ISD::CondCode CC) {
4077   return CC == ISD::SETLT || CC == ISD::SETLE;
4078 }
4079 
4080 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4081 // All of these conditions (and their <= and >= counterparts) will do:
4082 //          x < k ? k : x
4083 //          x > k ? x : k
4084 //          k < x ? x : k
4085 //          k > x ? k : x
4086 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4087                             const SDValue TrueVal, const SDValue FalseVal,
4088                             const ISD::CondCode CC, const SDValue K) {
4089   return (isGTorGE(CC) &&
4090           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4091          (isLTorLE(CC) &&
4092           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4093 }
4094 
4095 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4096 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4097                             const SDValue TrueVal, const SDValue FalseVal,
4098                             const ISD::CondCode CC, const SDValue K) {
4099   return (isGTorGE(CC) &&
4100           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4101          (isLTorLE(CC) &&
4102           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4103 }
4104 
4105 // Check if two chained conditionals could be converted into SSAT.
4106 //
4107 // SSAT can replace a set of two conditional selectors that bound a number to an
4108 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4109 //
4110 //     x < -k ? -k : (x > k ? k : x)
4111 //     x < -k ? -k : (x < k ? x : k)
4112 //     x > -k ? (x > k ? k : x) : -k
4113 //     x < k ? (x < -k ? -k : x) : k
4114 //     etc.
4115 //
4116 // It returns true if the conversion can be done, false otherwise.
4117 // Additionally, the variable is returned in parameter V and the constant in K.
4118 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4119                                     uint64_t &K) {
4120   SDValue LHS1 = Op.getOperand(0);
4121   SDValue RHS1 = Op.getOperand(1);
4122   SDValue TrueVal1 = Op.getOperand(2);
4123   SDValue FalseVal1 = Op.getOperand(3);
4124   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4125 
4126   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4127   if (Op2.getOpcode() != ISD::SELECT_CC)
4128     return false;
4129 
4130   SDValue LHS2 = Op2.getOperand(0);
4131   SDValue RHS2 = Op2.getOperand(1);
4132   SDValue TrueVal2 = Op2.getOperand(2);
4133   SDValue FalseVal2 = Op2.getOperand(3);
4134   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4135 
4136   // Find out which are the constants and which are the variables
4137   // in each conditional
4138   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4139                                                         ? &RHS1
4140                                                         : nullptr;
4141   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4142                                                         ? &RHS2
4143                                                         : nullptr;
4144   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4145   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4146   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4147   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4148 
4149   // We must detect cases where the original operations worked with 16- or
4150   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4151   // must work with sign-extended values but the select operations return
4152   // the original non-extended value.
4153   SDValue V2TmpReg = V2Tmp;
4154   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4155     V2TmpReg = V2Tmp->getOperand(0);
4156 
4157   // Check that the registers and the constants have the correct values
4158   // in both conditionals
4159   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4160       V2TmpReg != V2)
4161     return false;
4162 
4163   // Figure out which conditional is saturating the lower/upper bound.
4164   const SDValue *LowerCheckOp =
4165       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4166           ? &Op
4167           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4168                 ? &Op2
4169                 : nullptr;
4170   const SDValue *UpperCheckOp =
4171       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4172           ? &Op
4173           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4174                 ? &Op2
4175                 : nullptr;
4176 
4177   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4178     return false;
4179 
4180   // Check that the constant in the lower-bound check is
4181   // the opposite of the constant in the upper-bound check
4182   // in 1's complement.
4183   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4184   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4185   int64_t PosVal = std::max(Val1, Val2);
4186 
4187   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4188        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4189       Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) {
4190 
4191     V = V2;
4192     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4193     return true;
4194   }
4195 
4196   return false;
4197 }
4198 
4199 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4200   EVT VT = Op.getValueType();
4201   SDLoc dl(Op);
4202 
4203   // Try to convert two saturating conditional selects into a single SSAT
4204   SDValue SatValue;
4205   uint64_t SatConstant;
4206   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4207       isSaturatingConditional(Op, SatValue, SatConstant))
4208     return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4209                        DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4210 
4211   SDValue LHS = Op.getOperand(0);
4212   SDValue RHS = Op.getOperand(1);
4213   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4214   SDValue TrueVal = Op.getOperand(2);
4215   SDValue FalseVal = Op.getOperand(3);
4216 
4217   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4218     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4219                                                     dl);
4220 
4221     // If softenSetCCOperands only returned one value, we should compare it to
4222     // zero.
4223     if (!RHS.getNode()) {
4224       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4225       CC = ISD::SETNE;
4226     }
4227   }
4228 
4229   if (LHS.getValueType() == MVT::i32) {
4230     // Try to generate VSEL on ARMv8.
4231     // The VSEL instruction can't use all the usual ARM condition
4232     // codes: it only has two bits to select the condition code, so it's
4233     // constrained to use only GE, GT, VS and EQ.
4234     //
4235     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4236     // swap the operands of the previous compare instruction (effectively
4237     // inverting the compare condition, swapping 'less' and 'greater') and
4238     // sometimes need to swap the operands to the VSEL (which inverts the
4239     // condition in the sense of firing whenever the previous condition didn't)
4240     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4241                                     TrueVal.getValueType() == MVT::f64)) {
4242       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4243       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4244           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4245         CC = ISD::getSetCCInverse(CC, true);
4246         std::swap(TrueVal, FalseVal);
4247       }
4248     }
4249 
4250     SDValue ARMcc;
4251     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4252     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4253     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4254   }
4255 
4256   ARMCC::CondCodes CondCode, CondCode2;
4257   bool InvalidOnQNaN;
4258   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4259 
4260   // Try to generate VMAXNM/VMINNM on ARMv8.
4261   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4262                                   TrueVal.getValueType() == MVT::f64)) {
4263     bool swpCmpOps = false;
4264     bool swpVselOps = false;
4265     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4266 
4267     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4268         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4269       if (swpCmpOps)
4270         std::swap(LHS, RHS);
4271       if (swpVselOps)
4272         std::swap(TrueVal, FalseVal);
4273     }
4274   }
4275 
4276   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4277   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4278   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4279   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4280   if (CondCode2 != ARMCC::AL) {
4281     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4282     // FIXME: Needs another CMP because flag can have but one use.
4283     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4284     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4285   }
4286   return Result;
4287 }
4288 
4289 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4290 /// to morph to an integer compare sequence.
4291 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4292                            const ARMSubtarget *Subtarget) {
4293   SDNode *N = Op.getNode();
4294   if (!N->hasOneUse())
4295     // Otherwise it requires moving the value from fp to integer registers.
4296     return false;
4297   if (!N->getNumValues())
4298     return false;
4299   EVT VT = Op.getValueType();
4300   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4301     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4302     // vmrs are very slow, e.g. cortex-a8.
4303     return false;
4304 
4305   if (isFloatingPointZero(Op)) {
4306     SeenZero = true;
4307     return true;
4308   }
4309   return ISD::isNormalLoad(N);
4310 }
4311 
4312 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4313   if (isFloatingPointZero(Op))
4314     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4315 
4316   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4317     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4318                        Ld->getPointerInfo(), Ld->getAlignment(),
4319                        Ld->getMemOperand()->getFlags());
4320 
4321   llvm_unreachable("Unknown VFP cmp argument!");
4322 }
4323 
4324 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4325                            SDValue &RetVal1, SDValue &RetVal2) {
4326   SDLoc dl(Op);
4327 
4328   if (isFloatingPointZero(Op)) {
4329     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4330     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4331     return;
4332   }
4333 
4334   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4335     SDValue Ptr = Ld->getBasePtr();
4336     RetVal1 =
4337         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4338                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4339 
4340     EVT PtrType = Ptr.getValueType();
4341     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4342     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4343                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4344     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4345                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4346                           Ld->getMemOperand()->getFlags());
4347     return;
4348   }
4349 
4350   llvm_unreachable("Unknown VFP cmp argument!");
4351 }
4352 
4353 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4354 /// f32 and even f64 comparisons to integer ones.
4355 SDValue
4356 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4357   SDValue Chain = Op.getOperand(0);
4358   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4359   SDValue LHS = Op.getOperand(2);
4360   SDValue RHS = Op.getOperand(3);
4361   SDValue Dest = Op.getOperand(4);
4362   SDLoc dl(Op);
4363 
4364   bool LHSSeenZero = false;
4365   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4366   bool RHSSeenZero = false;
4367   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4368   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4369     // If unsafe fp math optimization is enabled and there are no other uses of
4370     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4371     // to an integer comparison.
4372     if (CC == ISD::SETOEQ)
4373       CC = ISD::SETEQ;
4374     else if (CC == ISD::SETUNE)
4375       CC = ISD::SETNE;
4376 
4377     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4378     SDValue ARMcc;
4379     if (LHS.getValueType() == MVT::f32) {
4380       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4381                         bitcastf32Toi32(LHS, DAG), Mask);
4382       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4383                         bitcastf32Toi32(RHS, DAG), Mask);
4384       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4385       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4386       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4387                          Chain, Dest, ARMcc, CCR, Cmp);
4388     }
4389 
4390     SDValue LHS1, LHS2;
4391     SDValue RHS1, RHS2;
4392     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4393     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4394     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4395     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4396     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4397     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4398     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4399     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4400     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4401   }
4402 
4403   return SDValue();
4404 }
4405 
4406 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4407   SDValue Chain = Op.getOperand(0);
4408   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4409   SDValue LHS = Op.getOperand(2);
4410   SDValue RHS = Op.getOperand(3);
4411   SDValue Dest = Op.getOperand(4);
4412   SDLoc dl(Op);
4413 
4414   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4415     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4416                                                     dl);
4417 
4418     // If softenSetCCOperands only returned one value, we should compare it to
4419     // zero.
4420     if (!RHS.getNode()) {
4421       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4422       CC = ISD::SETNE;
4423     }
4424   }
4425 
4426   if (LHS.getValueType() == MVT::i32) {
4427     SDValue ARMcc;
4428     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4429     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4430     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4431                        Chain, Dest, ARMcc, CCR, Cmp);
4432   }
4433 
4434   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4435 
4436   if (getTargetMachine().Options.UnsafeFPMath &&
4437       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4438        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4439     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4440       return Result;
4441   }
4442 
4443   ARMCC::CondCodes CondCode, CondCode2;
4444   bool InvalidOnQNaN;
4445   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4446 
4447   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4448   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4449   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4450   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4451   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4452   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4453   if (CondCode2 != ARMCC::AL) {
4454     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4455     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4456     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4457   }
4458   return Res;
4459 }
4460 
4461 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4462   SDValue Chain = Op.getOperand(0);
4463   SDValue Table = Op.getOperand(1);
4464   SDValue Index = Op.getOperand(2);
4465   SDLoc dl(Op);
4466 
4467   EVT PTy = getPointerTy(DAG.getDataLayout());
4468   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4469   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4470   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4471   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4472   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4473   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4474     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4475     // which does another jump to the destination. This also makes it easier
4476     // to translate it to TBB / TBH later (Thumb2 only).
4477     // FIXME: This might not work if the function is extremely large.
4478     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4479                        Addr, Op.getOperand(2), JTI);
4480   }
4481   if (isPositionIndependent() || Subtarget->isROPI()) {
4482     Addr =
4483         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4484                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4485     Chain = Addr.getValue(1);
4486     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4487     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4488   } else {
4489     Addr =
4490         DAG.getLoad(PTy, dl, Chain, Addr,
4491                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4492     Chain = Addr.getValue(1);
4493     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4494   }
4495 }
4496 
4497 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4498   EVT VT = Op.getValueType();
4499   SDLoc dl(Op);
4500 
4501   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4502     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4503       return Op;
4504     return DAG.UnrollVectorOp(Op.getNode());
4505   }
4506 
4507   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4508          "Invalid type for custom lowering!");
4509   if (VT != MVT::v4i16)
4510     return DAG.UnrollVectorOp(Op.getNode());
4511 
4512   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4513   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4514 }
4515 
4516 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4517   EVT VT = Op.getValueType();
4518   if (VT.isVector())
4519     return LowerVectorFP_TO_INT(Op, DAG);
4520   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4521     RTLIB::Libcall LC;
4522     if (Op.getOpcode() == ISD::FP_TO_SINT)
4523       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4524                               Op.getValueType());
4525     else
4526       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4527                               Op.getValueType());
4528     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4529                        /*isSigned*/ false, SDLoc(Op)).first;
4530   }
4531 
4532   return Op;
4533 }
4534 
4535 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4536   EVT VT = Op.getValueType();
4537   SDLoc dl(Op);
4538 
4539   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4540     if (VT.getVectorElementType() == MVT::f32)
4541       return Op;
4542     return DAG.UnrollVectorOp(Op.getNode());
4543   }
4544 
4545   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4546          "Invalid type for custom lowering!");
4547   if (VT != MVT::v4f32)
4548     return DAG.UnrollVectorOp(Op.getNode());
4549 
4550   unsigned CastOpc;
4551   unsigned Opc;
4552   switch (Op.getOpcode()) {
4553   default: llvm_unreachable("Invalid opcode!");
4554   case ISD::SINT_TO_FP:
4555     CastOpc = ISD::SIGN_EXTEND;
4556     Opc = ISD::SINT_TO_FP;
4557     break;
4558   case ISD::UINT_TO_FP:
4559     CastOpc = ISD::ZERO_EXTEND;
4560     Opc = ISD::UINT_TO_FP;
4561     break;
4562   }
4563 
4564   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4565   return DAG.getNode(Opc, dl, VT, Op);
4566 }
4567 
4568 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4569   EVT VT = Op.getValueType();
4570   if (VT.isVector())
4571     return LowerVectorINT_TO_FP(Op, DAG);
4572   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4573     RTLIB::Libcall LC;
4574     if (Op.getOpcode() == ISD::SINT_TO_FP)
4575       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4576                               Op.getValueType());
4577     else
4578       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4579                               Op.getValueType());
4580     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4581                        /*isSigned*/ false, SDLoc(Op)).first;
4582   }
4583 
4584   return Op;
4585 }
4586 
4587 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4588   // Implement fcopysign with a fabs and a conditional fneg.
4589   SDValue Tmp0 = Op.getOperand(0);
4590   SDValue Tmp1 = Op.getOperand(1);
4591   SDLoc dl(Op);
4592   EVT VT = Op.getValueType();
4593   EVT SrcVT = Tmp1.getValueType();
4594   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4595     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4596   bool UseNEON = !InGPR && Subtarget->hasNEON();
4597 
4598   if (UseNEON) {
4599     // Use VBSL to copy the sign bit.
4600     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4601     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4602                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4603     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4604     if (VT == MVT::f64)
4605       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4606                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4607                          DAG.getConstant(32, dl, MVT::i32));
4608     else /*if (VT == MVT::f32)*/
4609       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4610     if (SrcVT == MVT::f32) {
4611       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4612       if (VT == MVT::f64)
4613         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4614                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4615                            DAG.getConstant(32, dl, MVT::i32));
4616     } else if (VT == MVT::f32)
4617       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4618                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4619                          DAG.getConstant(32, dl, MVT::i32));
4620     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4621     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4622 
4623     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4624                                             dl, MVT::i32);
4625     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4626     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4627                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4628 
4629     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4630                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4631                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4632     if (VT == MVT::f32) {
4633       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4634       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4635                         DAG.getConstant(0, dl, MVT::i32));
4636     } else {
4637       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4638     }
4639 
4640     return Res;
4641   }
4642 
4643   // Bitcast operand 1 to i32.
4644   if (SrcVT == MVT::f64)
4645     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4646                        Tmp1).getValue(1);
4647   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4648 
4649   // Or in the signbit with integer operations.
4650   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4651   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4652   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4653   if (VT == MVT::f32) {
4654     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4655                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4656     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4657                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4658   }
4659 
4660   // f64: Or the high part with signbit and then combine two parts.
4661   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4662                      Tmp0);
4663   SDValue Lo = Tmp0.getValue(0);
4664   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4665   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4666   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4667 }
4668 
4669 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4670   MachineFunction &MF = DAG.getMachineFunction();
4671   MachineFrameInfo &MFI = MF.getFrameInfo();
4672   MFI.setReturnAddressIsTaken(true);
4673 
4674   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4675     return SDValue();
4676 
4677   EVT VT = Op.getValueType();
4678   SDLoc dl(Op);
4679   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4680   if (Depth) {
4681     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4682     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4683     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4684                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4685                        MachinePointerInfo());
4686   }
4687 
4688   // Return LR, which contains the return address. Mark it an implicit live-in.
4689   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4690   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4691 }
4692 
4693 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4694   const ARMBaseRegisterInfo &ARI =
4695     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4696   MachineFunction &MF = DAG.getMachineFunction();
4697   MachineFrameInfo &MFI = MF.getFrameInfo();
4698   MFI.setFrameAddressIsTaken(true);
4699 
4700   EVT VT = Op.getValueType();
4701   SDLoc dl(Op);  // FIXME probably not meaningful
4702   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4703   unsigned FrameReg = ARI.getFrameRegister(MF);
4704   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4705   while (Depth--)
4706     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4707                             MachinePointerInfo());
4708   return FrameAddr;
4709 }
4710 
4711 // FIXME? Maybe this could be a TableGen attribute on some registers and
4712 // this table could be generated automatically from RegInfo.
4713 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4714                                               SelectionDAG &DAG) const {
4715   unsigned Reg = StringSwitch<unsigned>(RegName)
4716                        .Case("sp", ARM::SP)
4717                        .Default(0);
4718   if (Reg)
4719     return Reg;
4720   report_fatal_error(Twine("Invalid register name \""
4721                               + StringRef(RegName)  + "\"."));
4722 }
4723 
4724 // Result is 64 bit value so split into two 32 bit values and return as a
4725 // pair of values.
4726 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4727                                 SelectionDAG &DAG) {
4728   SDLoc DL(N);
4729 
4730   // This function is only supposed to be called for i64 type destination.
4731   assert(N->getValueType(0) == MVT::i64
4732           && "ExpandREAD_REGISTER called for non-i64 type result.");
4733 
4734   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4735                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4736                              N->getOperand(0),
4737                              N->getOperand(1));
4738 
4739   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4740                     Read.getValue(1)));
4741   Results.push_back(Read.getOperand(0));
4742 }
4743 
4744 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4745 /// When \p DstVT, the destination type of \p BC, is on the vector
4746 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4747 /// it might be possible to combine them, such that everything stays on the
4748 /// vector register bank.
4749 /// \p return The node that would replace \p BT, if the combine
4750 /// is possible.
4751 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4752                                                 SelectionDAG &DAG) {
4753   SDValue Op = BC->getOperand(0);
4754   EVT DstVT = BC->getValueType(0);
4755 
4756   // The only vector instruction that can produce a scalar (remember,
4757   // since the bitcast was about to be turned into VMOVDRR, the source
4758   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4759   // Moreover, we can do this combine only if there is one use.
4760   // Finally, if the destination type is not a vector, there is not
4761   // much point on forcing everything on the vector bank.
4762   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4763       !Op.hasOneUse())
4764     return SDValue();
4765 
4766   // If the index is not constant, we will introduce an additional
4767   // multiply that will stick.
4768   // Give up in that case.
4769   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4770   if (!Index)
4771     return SDValue();
4772   unsigned DstNumElt = DstVT.getVectorNumElements();
4773 
4774   // Compute the new index.
4775   const APInt &APIntIndex = Index->getAPIntValue();
4776   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4777   NewIndex *= APIntIndex;
4778   // Check if the new constant index fits into i32.
4779   if (NewIndex.getBitWidth() > 32)
4780     return SDValue();
4781 
4782   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4783   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4784   SDLoc dl(Op);
4785   SDValue ExtractSrc = Op.getOperand(0);
4786   EVT VecVT = EVT::getVectorVT(
4787       *DAG.getContext(), DstVT.getScalarType(),
4788       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4789   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4790   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4791                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4792 }
4793 
4794 /// ExpandBITCAST - If the target supports VFP, this function is called to
4795 /// expand a bit convert where either the source or destination type is i64 to
4796 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4797 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4798 /// vectors), since the legalizer won't know what to do with that.
4799 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4800   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4801   SDLoc dl(N);
4802   SDValue Op = N->getOperand(0);
4803 
4804   // This function is only supposed to be called for i64 types, either as the
4805   // source or destination of the bit convert.
4806   EVT SrcVT = Op.getValueType();
4807   EVT DstVT = N->getValueType(0);
4808   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4809          "ExpandBITCAST called for non-i64 type");
4810 
4811   // Turn i64->f64 into VMOVDRR.
4812   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4813     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4814     // if we can combine the bitcast with its source.
4815     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4816       return Val;
4817 
4818     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4819                              DAG.getConstant(0, dl, MVT::i32));
4820     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4821                              DAG.getConstant(1, dl, MVT::i32));
4822     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4823                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4824   }
4825 
4826   // Turn f64->i64 into VMOVRRD.
4827   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4828     SDValue Cvt;
4829     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4830         SrcVT.getVectorNumElements() > 1)
4831       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4832                         DAG.getVTList(MVT::i32, MVT::i32),
4833                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4834     else
4835       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4836                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4837     // Merge the pieces into a single i64 value.
4838     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4839   }
4840 
4841   return SDValue();
4842 }
4843 
4844 /// getZeroVector - Returns a vector of specified type with all zero elements.
4845 /// Zero vectors are used to represent vector negation and in those cases
4846 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4847 /// not support i64 elements, so sometimes the zero vectors will need to be
4848 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4849 /// zero vector.
4850 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4851   assert(VT.isVector() && "Expected a vector type");
4852   // The canonical modified immediate encoding of a zero vector is....0!
4853   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4854   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4855   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4856   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4857 }
4858 
4859 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4860 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4861 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4862                                                 SelectionDAG &DAG) const {
4863   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4864   EVT VT = Op.getValueType();
4865   unsigned VTBits = VT.getSizeInBits();
4866   SDLoc dl(Op);
4867   SDValue ShOpLo = Op.getOperand(0);
4868   SDValue ShOpHi = Op.getOperand(1);
4869   SDValue ShAmt  = Op.getOperand(2);
4870   SDValue ARMcc;
4871   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4872   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4873 
4874   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4875 
4876   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4877                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4878   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4879   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4880                                    DAG.getConstant(VTBits, dl, MVT::i32));
4881   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4882   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4883   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4884   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4885                             ISD::SETGE, ARMcc, DAG, dl);
4886   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
4887                            ARMcc, CCR, CmpLo);
4888 
4889 
4890   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
4891   SDValue HiBigShift = Opc == ISD::SRA
4892                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
4893                                          DAG.getConstant(VTBits - 1, dl, VT))
4894                            : DAG.getConstant(0, dl, VT);
4895   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4896                             ISD::SETGE, ARMcc, DAG, dl);
4897   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
4898                            ARMcc, CCR, CmpHi);
4899 
4900   SDValue Ops[2] = { Lo, Hi };
4901   return DAG.getMergeValues(Ops, dl);
4902 }
4903 
4904 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
4905 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4906 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
4907                                                SelectionDAG &DAG) const {
4908   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4909   EVT VT = Op.getValueType();
4910   unsigned VTBits = VT.getSizeInBits();
4911   SDLoc dl(Op);
4912   SDValue ShOpLo = Op.getOperand(0);
4913   SDValue ShOpHi = Op.getOperand(1);
4914   SDValue ShAmt  = Op.getOperand(2);
4915   SDValue ARMcc;
4916   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4917 
4918   assert(Op.getOpcode() == ISD::SHL_PARTS);
4919   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4920                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4921   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
4922   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
4923   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4924 
4925   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4926                                    DAG.getConstant(VTBits, dl, MVT::i32));
4927   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
4928   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4929                             ISD::SETGE, ARMcc, DAG, dl);
4930   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
4931                            ARMcc, CCR, CmpHi);
4932 
4933   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4934                           ISD::SETGE, ARMcc, DAG, dl);
4935   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
4936   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
4937                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
4938 
4939   SDValue Ops[2] = { Lo, Hi };
4940   return DAG.getMergeValues(Ops, dl);
4941 }
4942 
4943 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
4944                                             SelectionDAG &DAG) const {
4945   // The rounding mode is in bits 23:22 of the FPSCR.
4946   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
4947   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
4948   // so that the shift + and get folded into a bitfield extract.
4949   SDLoc dl(Op);
4950   SDValue Ops[] = { DAG.getEntryNode(),
4951                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
4952 
4953   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
4954   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
4955                                   DAG.getConstant(1U << 22, dl, MVT::i32));
4956   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
4957                               DAG.getConstant(22, dl, MVT::i32));
4958   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
4959                      DAG.getConstant(3, dl, MVT::i32));
4960 }
4961 
4962 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
4963                          const ARMSubtarget *ST) {
4964   SDLoc dl(N);
4965   EVT VT = N->getValueType(0);
4966   if (VT.isVector()) {
4967     assert(ST->hasNEON());
4968 
4969     // Compute the least significant set bit: LSB = X & -X
4970     SDValue X = N->getOperand(0);
4971     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
4972     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
4973 
4974     EVT ElemTy = VT.getVectorElementType();
4975 
4976     if (ElemTy == MVT::i8) {
4977       // Compute with: cttz(x) = ctpop(lsb - 1)
4978       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4979                                 DAG.getTargetConstant(1, dl, ElemTy));
4980       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
4981       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
4982     }
4983 
4984     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
4985         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
4986       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
4987       unsigned NumBits = ElemTy.getSizeInBits();
4988       SDValue WidthMinus1 =
4989           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
4990                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
4991       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
4992       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
4993     }
4994 
4995     // Compute with: cttz(x) = ctpop(lsb - 1)
4996 
4997     // Since we can only compute the number of bits in a byte with vcnt.8, we
4998     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
4999     // and i64.
5000 
5001     // Compute LSB - 1.
5002     SDValue Bits;
5003     if (ElemTy == MVT::i64) {
5004       // Load constant 0xffff'ffff'ffff'ffff to register.
5005       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5006                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5007       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5008     } else {
5009       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5010                                 DAG.getTargetConstant(1, dl, ElemTy));
5011       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5012     }
5013 
5014     // Count #bits with vcnt.8.
5015     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5016     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5017     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5018 
5019     // Gather the #bits with vpaddl (pairwise add.)
5020     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5021     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5022         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5023         Cnt8);
5024     if (ElemTy == MVT::i16)
5025       return Cnt16;
5026 
5027     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5028     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5029         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5030         Cnt16);
5031     if (ElemTy == MVT::i32)
5032       return Cnt32;
5033 
5034     assert(ElemTy == MVT::i64);
5035     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5036         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5037         Cnt32);
5038     return Cnt64;
5039   }
5040 
5041   if (!ST->hasV6T2Ops())
5042     return SDValue();
5043 
5044   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5045   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5046 }
5047 
5048 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5049 /// for each 16-bit element from operand, repeated.  The basic idea is to
5050 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5051 ///
5052 /// Trace for v4i16:
5053 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
5054 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5055 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5056 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5057 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
5058 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
5059 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5060 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
5061 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5062   EVT VT = N->getValueType(0);
5063   SDLoc DL(N);
5064 
5065   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5066   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5067   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5068   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5069   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5070   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5071 }
5072 
5073 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5074 /// bit-count for each 16-bit element from the operand.  We need slightly
5075 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5076 /// 64/128-bit registers.
5077 ///
5078 /// Trace for v4i16:
5079 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
5080 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5081 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
5082 /// v4i16:Extracted = [k0    k1    k2    k3    ]
5083 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5084   EVT VT = N->getValueType(0);
5085   SDLoc DL(N);
5086 
5087   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5088   if (VT.is64BitVector()) {
5089     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5090     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5091                        DAG.getIntPtrConstant(0, DL));
5092   } else {
5093     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5094                                     BitCounts, DAG.getIntPtrConstant(0, DL));
5095     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5096   }
5097 }
5098 
5099 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5100 /// bit-count for each 32-bit element from the operand.  The idea here is
5101 /// to split the vector into 16-bit elements, leverage the 16-bit count
5102 /// routine, and then combine the results.
5103 ///
5104 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5105 /// input    = [v0    v1    ] (vi: 32-bit elements)
5106 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5107 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5108 /// vrev: N0 = [k1 k0 k3 k2 ]
5109 ///            [k0 k1 k2 k3 ]
5110 ///       N1 =+[k1 k0 k3 k2 ]
5111 ///            [k0 k2 k1 k3 ]
5112 ///       N2 =+[k1 k3 k0 k2 ]
5113 ///            [k0    k2    k1    k3    ]
5114 /// Extended =+[k1    k3    k0    k2    ]
5115 ///            [k0    k2    ]
5116 /// Extracted=+[k1    k3    ]
5117 ///
5118 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5119   EVT VT = N->getValueType(0);
5120   SDLoc DL(N);
5121 
5122   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5123 
5124   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5125   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5126   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5127   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5128   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5129 
5130   if (VT.is64BitVector()) {
5131     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5132     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5133                        DAG.getIntPtrConstant(0, DL));
5134   } else {
5135     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5136                                     DAG.getIntPtrConstant(0, DL));
5137     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5138   }
5139 }
5140 
5141 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5142                           const ARMSubtarget *ST) {
5143   EVT VT = N->getValueType(0);
5144 
5145   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5146   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5147           VT == MVT::v4i16 || VT == MVT::v8i16) &&
5148          "Unexpected type for custom ctpop lowering");
5149 
5150   if (VT.getVectorElementType() == MVT::i32)
5151     return lowerCTPOP32BitElements(N, DAG);
5152   else
5153     return lowerCTPOP16BitElements(N, DAG);
5154 }
5155 
5156 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5157                           const ARMSubtarget *ST) {
5158   EVT VT = N->getValueType(0);
5159   SDLoc dl(N);
5160 
5161   if (!VT.isVector())
5162     return SDValue();
5163 
5164   // Lower vector shifts on NEON to use VSHL.
5165   assert(ST->hasNEON() && "unexpected vector shift");
5166 
5167   // Left shifts translate directly to the vshiftu intrinsic.
5168   if (N->getOpcode() == ISD::SHL)
5169     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5170                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5171                                        MVT::i32),
5172                        N->getOperand(0), N->getOperand(1));
5173 
5174   assert((N->getOpcode() == ISD::SRA ||
5175           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5176 
5177   // NEON uses the same intrinsics for both left and right shifts.  For
5178   // right shifts, the shift amounts are negative, so negate the vector of
5179   // shift amounts.
5180   EVT ShiftVT = N->getOperand(1).getValueType();
5181   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5182                                      getZeroVector(ShiftVT, DAG, dl),
5183                                      N->getOperand(1));
5184   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5185                              Intrinsic::arm_neon_vshifts :
5186                              Intrinsic::arm_neon_vshiftu);
5187   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5188                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5189                      N->getOperand(0), NegatedCount);
5190 }
5191 
5192 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5193                                 const ARMSubtarget *ST) {
5194   EVT VT = N->getValueType(0);
5195   SDLoc dl(N);
5196 
5197   // We can get here for a node like i32 = ISD::SHL i32, i64
5198   if (VT != MVT::i64)
5199     return SDValue();
5200 
5201   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5202          "Unknown shift to lower!");
5203 
5204   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5205   if (!isOneConstant(N->getOperand(1)))
5206     return SDValue();
5207 
5208   // If we are in thumb mode, we don't have RRX.
5209   if (ST->isThumb1Only()) return SDValue();
5210 
5211   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5212   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5213                            DAG.getConstant(0, dl, MVT::i32));
5214   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5215                            DAG.getConstant(1, dl, MVT::i32));
5216 
5217   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5218   // captures the result into a carry flag.
5219   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5220   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5221 
5222   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5223   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5224 
5225   // Merge the pieces into a single i64 value.
5226  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5227 }
5228 
5229 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5230   SDValue TmpOp0, TmpOp1;
5231   bool Invert = false;
5232   bool Swap = false;
5233   unsigned Opc = 0;
5234 
5235   SDValue Op0 = Op.getOperand(0);
5236   SDValue Op1 = Op.getOperand(1);
5237   SDValue CC = Op.getOperand(2);
5238   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5239   EVT VT = Op.getValueType();
5240   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5241   SDLoc dl(Op);
5242 
5243   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5244       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5245     // Special-case integer 64-bit equality comparisons. They aren't legal,
5246     // but they can be lowered with a few vector instructions.
5247     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5248     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5249     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5250     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5251     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5252                               DAG.getCondCode(ISD::SETEQ));
5253     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5254     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5255     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5256     if (SetCCOpcode == ISD::SETNE)
5257       Merged = DAG.getNOT(dl, Merged, CmpVT);
5258     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5259     return Merged;
5260   }
5261 
5262   if (CmpVT.getVectorElementType() == MVT::i64)
5263     // 64-bit comparisons are not legal in general.
5264     return SDValue();
5265 
5266   if (Op1.getValueType().isFloatingPoint()) {
5267     switch (SetCCOpcode) {
5268     default: llvm_unreachable("Illegal FP comparison");
5269     case ISD::SETUNE:
5270     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5271     case ISD::SETOEQ:
5272     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5273     case ISD::SETOLT:
5274     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5275     case ISD::SETOGT:
5276     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5277     case ISD::SETOLE:
5278     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5279     case ISD::SETOGE:
5280     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5281     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5282     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5283     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5284     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5285     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5286     case ISD::SETONE:
5287       // Expand this to (OLT | OGT).
5288       TmpOp0 = Op0;
5289       TmpOp1 = Op1;
5290       Opc = ISD::OR;
5291       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5292       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5293       break;
5294     case ISD::SETUO:
5295       Invert = true;
5296       LLVM_FALLTHROUGH;
5297     case ISD::SETO:
5298       // Expand this to (OLT | OGE).
5299       TmpOp0 = Op0;
5300       TmpOp1 = Op1;
5301       Opc = ISD::OR;
5302       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5303       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5304       break;
5305     }
5306   } else {
5307     // Integer comparisons.
5308     switch (SetCCOpcode) {
5309     default: llvm_unreachable("Illegal integer comparison");
5310     case ISD::SETNE:  Invert = true;
5311     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5312     case ISD::SETLT:  Swap = true;
5313     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5314     case ISD::SETLE:  Swap = true;
5315     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5316     case ISD::SETULT: Swap = true;
5317     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5318     case ISD::SETULE: Swap = true;
5319     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5320     }
5321 
5322     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5323     if (Opc == ARMISD::VCEQ) {
5324 
5325       SDValue AndOp;
5326       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5327         AndOp = Op0;
5328       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5329         AndOp = Op1;
5330 
5331       // Ignore bitconvert.
5332       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5333         AndOp = AndOp.getOperand(0);
5334 
5335       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5336         Opc = ARMISD::VTST;
5337         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5338         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5339         Invert = !Invert;
5340       }
5341     }
5342   }
5343 
5344   if (Swap)
5345     std::swap(Op0, Op1);
5346 
5347   // If one of the operands is a constant vector zero, attempt to fold the
5348   // comparison to a specialized compare-against-zero form.
5349   SDValue SingleOp;
5350   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5351     SingleOp = Op0;
5352   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5353     if (Opc == ARMISD::VCGE)
5354       Opc = ARMISD::VCLEZ;
5355     else if (Opc == ARMISD::VCGT)
5356       Opc = ARMISD::VCLTZ;
5357     SingleOp = Op1;
5358   }
5359 
5360   SDValue Result;
5361   if (SingleOp.getNode()) {
5362     switch (Opc) {
5363     case ARMISD::VCEQ:
5364       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5365     case ARMISD::VCGE:
5366       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5367     case ARMISD::VCLEZ:
5368       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5369     case ARMISD::VCGT:
5370       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5371     case ARMISD::VCLTZ:
5372       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5373     default:
5374       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5375     }
5376   } else {
5377      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5378   }
5379 
5380   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5381 
5382   if (Invert)
5383     Result = DAG.getNOT(dl, Result, VT);
5384 
5385   return Result;
5386 }
5387 
5388 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5389   SDValue LHS = Op.getOperand(0);
5390   SDValue RHS = Op.getOperand(1);
5391   SDValue Carry = Op.getOperand(2);
5392   SDValue Cond = Op.getOperand(3);
5393   SDLoc DL(Op);
5394 
5395   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5396 
5397   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5398   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5399   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5400 
5401   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5402   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5403   SDValue ARMcc = DAG.getConstant(
5404       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5405   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5406   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5407                                    Cmp.getValue(1), SDValue());
5408   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5409                      CCR, Chain.getValue(1));
5410 }
5411 
5412 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5413 /// valid vector constant for a NEON instruction with a "modified immediate"
5414 /// operand (e.g., VMOV).  If so, return the encoded value.
5415 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5416                                  unsigned SplatBitSize, SelectionDAG &DAG,
5417                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5418                                  NEONModImmType type) {
5419   unsigned OpCmode, Imm;
5420 
5421   // SplatBitSize is set to the smallest size that splats the vector, so a
5422   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5423   // immediate instructions others than VMOV do not support the 8-bit encoding
5424   // of a zero vector, and the default encoding of zero is supposed to be the
5425   // 32-bit version.
5426   if (SplatBits == 0)
5427     SplatBitSize = 32;
5428 
5429   switch (SplatBitSize) {
5430   case 8:
5431     if (type != VMOVModImm)
5432       return SDValue();
5433     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5434     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5435     OpCmode = 0xe;
5436     Imm = SplatBits;
5437     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5438     break;
5439 
5440   case 16:
5441     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5442     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5443     if ((SplatBits & ~0xff) == 0) {
5444       // Value = 0x00nn: Op=x, Cmode=100x.
5445       OpCmode = 0x8;
5446       Imm = SplatBits;
5447       break;
5448     }
5449     if ((SplatBits & ~0xff00) == 0) {
5450       // Value = 0xnn00: Op=x, Cmode=101x.
5451       OpCmode = 0xa;
5452       Imm = SplatBits >> 8;
5453       break;
5454     }
5455     return SDValue();
5456 
5457   case 32:
5458     // NEON's 32-bit VMOV supports splat values where:
5459     // * only one byte is nonzero, or
5460     // * the least significant byte is 0xff and the second byte is nonzero, or
5461     // * the least significant 2 bytes are 0xff and the third is nonzero.
5462     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5463     if ((SplatBits & ~0xff) == 0) {
5464       // Value = 0x000000nn: Op=x, Cmode=000x.
5465       OpCmode = 0;
5466       Imm = SplatBits;
5467       break;
5468     }
5469     if ((SplatBits & ~0xff00) == 0) {
5470       // Value = 0x0000nn00: Op=x, Cmode=001x.
5471       OpCmode = 0x2;
5472       Imm = SplatBits >> 8;
5473       break;
5474     }
5475     if ((SplatBits & ~0xff0000) == 0) {
5476       // Value = 0x00nn0000: Op=x, Cmode=010x.
5477       OpCmode = 0x4;
5478       Imm = SplatBits >> 16;
5479       break;
5480     }
5481     if ((SplatBits & ~0xff000000) == 0) {
5482       // Value = 0xnn000000: Op=x, Cmode=011x.
5483       OpCmode = 0x6;
5484       Imm = SplatBits >> 24;
5485       break;
5486     }
5487 
5488     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5489     if (type == OtherModImm) return SDValue();
5490 
5491     if ((SplatBits & ~0xffff) == 0 &&
5492         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5493       // Value = 0x0000nnff: Op=x, Cmode=1100.
5494       OpCmode = 0xc;
5495       Imm = SplatBits >> 8;
5496       break;
5497     }
5498 
5499     if ((SplatBits & ~0xffffff) == 0 &&
5500         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5501       // Value = 0x00nnffff: Op=x, Cmode=1101.
5502       OpCmode = 0xd;
5503       Imm = SplatBits >> 16;
5504       break;
5505     }
5506 
5507     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5508     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5509     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5510     // and fall through here to test for a valid 64-bit splat.  But, then the
5511     // caller would also need to check and handle the change in size.
5512     return SDValue();
5513 
5514   case 64: {
5515     if (type != VMOVModImm)
5516       return SDValue();
5517     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5518     uint64_t BitMask = 0xff;
5519     uint64_t Val = 0;
5520     unsigned ImmMask = 1;
5521     Imm = 0;
5522     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5523       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5524         Val |= BitMask;
5525         Imm |= ImmMask;
5526       } else if ((SplatBits & BitMask) != 0) {
5527         return SDValue();
5528       }
5529       BitMask <<= 8;
5530       ImmMask <<= 1;
5531     }
5532 
5533     if (DAG.getDataLayout().isBigEndian())
5534       // swap higher and lower 32 bit word
5535       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5536 
5537     // Op=1, Cmode=1110.
5538     OpCmode = 0x1e;
5539     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5540     break;
5541   }
5542 
5543   default:
5544     llvm_unreachable("unexpected size for isNEONModifiedImm");
5545   }
5546 
5547   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5548   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5549 }
5550 
5551 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5552                                            const ARMSubtarget *ST) const {
5553   bool IsDouble = Op.getValueType() == MVT::f64;
5554   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5555   const APFloat &FPVal = CFP->getValueAPF();
5556 
5557   // Prevent floating-point constants from using literal loads
5558   // when execute-only is enabled.
5559   if (ST->genExecuteOnly()) {
5560     APInt INTVal = FPVal.bitcastToAPInt();
5561     SDLoc DL(CFP);
5562     if (IsDouble) {
5563       SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5564       SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5565       if (!ST->isLittle())
5566         std::swap(Lo, Hi);
5567       return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5568     } else {
5569       return DAG.getConstant(INTVal, DL, MVT::i32);
5570     }
5571   }
5572 
5573   if (!ST->hasVFP3())
5574     return SDValue();
5575 
5576   // Use the default (constant pool) lowering for double constants when we have
5577   // an SP-only FPU
5578   if (IsDouble && Subtarget->isFPOnlySP())
5579     return SDValue();
5580 
5581   // Try splatting with a VMOV.f32...
5582   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5583 
5584   if (ImmVal != -1) {
5585     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5586       // We have code in place to select a valid ConstantFP already, no need to
5587       // do any mangling.
5588       return Op;
5589     }
5590 
5591     // It's a float and we are trying to use NEON operations where
5592     // possible. Lower it to a splat followed by an extract.
5593     SDLoc DL(Op);
5594     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5595     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5596                                       NewVal);
5597     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5598                        DAG.getConstant(0, DL, MVT::i32));
5599   }
5600 
5601   // The rest of our options are NEON only, make sure that's allowed before
5602   // proceeding..
5603   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5604     return SDValue();
5605 
5606   EVT VMovVT;
5607   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5608 
5609   // It wouldn't really be worth bothering for doubles except for one very
5610   // important value, which does happen to match: 0.0. So make sure we don't do
5611   // anything stupid.
5612   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5613     return SDValue();
5614 
5615   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5616   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5617                                      VMovVT, false, VMOVModImm);
5618   if (NewVal != SDValue()) {
5619     SDLoc DL(Op);
5620     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5621                                       NewVal);
5622     if (IsDouble)
5623       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5624 
5625     // It's a float: cast and extract a vector element.
5626     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5627                                        VecConstant);
5628     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5629                        DAG.getConstant(0, DL, MVT::i32));
5630   }
5631 
5632   // Finally, try a VMVN.i32
5633   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5634                              false, VMVNModImm);
5635   if (NewVal != SDValue()) {
5636     SDLoc DL(Op);
5637     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5638 
5639     if (IsDouble)
5640       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5641 
5642     // It's a float: cast and extract a vector element.
5643     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5644                                        VecConstant);
5645     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5646                        DAG.getConstant(0, DL, MVT::i32));
5647   }
5648 
5649   return SDValue();
5650 }
5651 
5652 // check if an VEXT instruction can handle the shuffle mask when the
5653 // vector sources of the shuffle are the same.
5654 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5655   unsigned NumElts = VT.getVectorNumElements();
5656 
5657   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5658   if (M[0] < 0)
5659     return false;
5660 
5661   Imm = M[0];
5662 
5663   // If this is a VEXT shuffle, the immediate value is the index of the first
5664   // element.  The other shuffle indices must be the successive elements after
5665   // the first one.
5666   unsigned ExpectedElt = Imm;
5667   for (unsigned i = 1; i < NumElts; ++i) {
5668     // Increment the expected index.  If it wraps around, just follow it
5669     // back to index zero and keep going.
5670     ++ExpectedElt;
5671     if (ExpectedElt == NumElts)
5672       ExpectedElt = 0;
5673 
5674     if (M[i] < 0) continue; // ignore UNDEF indices
5675     if (ExpectedElt != static_cast<unsigned>(M[i]))
5676       return false;
5677   }
5678 
5679   return true;
5680 }
5681 
5682 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5683                        bool &ReverseVEXT, unsigned &Imm) {
5684   unsigned NumElts = VT.getVectorNumElements();
5685   ReverseVEXT = false;
5686 
5687   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5688   if (M[0] < 0)
5689     return false;
5690 
5691   Imm = M[0];
5692 
5693   // If this is a VEXT shuffle, the immediate value is the index of the first
5694   // element.  The other shuffle indices must be the successive elements after
5695   // the first one.
5696   unsigned ExpectedElt = Imm;
5697   for (unsigned i = 1; i < NumElts; ++i) {
5698     // Increment the expected index.  If it wraps around, it may still be
5699     // a VEXT but the source vectors must be swapped.
5700     ExpectedElt += 1;
5701     if (ExpectedElt == NumElts * 2) {
5702       ExpectedElt = 0;
5703       ReverseVEXT = true;
5704     }
5705 
5706     if (M[i] < 0) continue; // ignore UNDEF indices
5707     if (ExpectedElt != static_cast<unsigned>(M[i]))
5708       return false;
5709   }
5710 
5711   // Adjust the index value if the source operands will be swapped.
5712   if (ReverseVEXT)
5713     Imm -= NumElts;
5714 
5715   return true;
5716 }
5717 
5718 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5719 /// instruction with the specified blocksize.  (The order of the elements
5720 /// within each block of the vector is reversed.)
5721 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5722   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5723          "Only possible block sizes for VREV are: 16, 32, 64");
5724 
5725   unsigned EltSz = VT.getScalarSizeInBits();
5726   if (EltSz == 64)
5727     return false;
5728 
5729   unsigned NumElts = VT.getVectorNumElements();
5730   unsigned BlockElts = M[0] + 1;
5731   // If the first shuffle index is UNDEF, be optimistic.
5732   if (M[0] < 0)
5733     BlockElts = BlockSize / EltSz;
5734 
5735   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5736     return false;
5737 
5738   for (unsigned i = 0; i < NumElts; ++i) {
5739     if (M[i] < 0) continue; // ignore UNDEF indices
5740     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5741       return false;
5742   }
5743 
5744   return true;
5745 }
5746 
5747 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5748   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5749   // range, then 0 is placed into the resulting vector. So pretty much any mask
5750   // of 8 elements can work here.
5751   return VT == MVT::v8i8 && M.size() == 8;
5752 }
5753 
5754 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5755 // checking that pairs of elements in the shuffle mask represent the same index
5756 // in each vector, incrementing the expected index by 2 at each step.
5757 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5758 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5759 //  v2={e,f,g,h}
5760 // WhichResult gives the offset for each element in the mask based on which
5761 // of the two results it belongs to.
5762 //
5763 // The transpose can be represented either as:
5764 // result1 = shufflevector v1, v2, result1_shuffle_mask
5765 // result2 = shufflevector v1, v2, result2_shuffle_mask
5766 // where v1/v2 and the shuffle masks have the same number of elements
5767 // (here WhichResult (see below) indicates which result is being checked)
5768 //
5769 // or as:
5770 // results = shufflevector v1, v2, shuffle_mask
5771 // where both results are returned in one vector and the shuffle mask has twice
5772 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5773 // want to check the low half and high half of the shuffle mask as if it were
5774 // the other case
5775 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5776   unsigned EltSz = VT.getScalarSizeInBits();
5777   if (EltSz == 64)
5778     return false;
5779 
5780   unsigned NumElts = VT.getVectorNumElements();
5781   if (M.size() != NumElts && M.size() != NumElts*2)
5782     return false;
5783 
5784   // If the mask is twice as long as the input vector then we need to check the
5785   // upper and lower parts of the mask with a matching value for WhichResult
5786   // FIXME: A mask with only even values will be rejected in case the first
5787   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5788   // M[0] is used to determine WhichResult
5789   for (unsigned i = 0; i < M.size(); i += NumElts) {
5790     if (M.size() == NumElts * 2)
5791       WhichResult = i / NumElts;
5792     else
5793       WhichResult = M[i] == 0 ? 0 : 1;
5794     for (unsigned j = 0; j < NumElts; j += 2) {
5795       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5796           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5797         return false;
5798     }
5799   }
5800 
5801   if (M.size() == NumElts*2)
5802     WhichResult = 0;
5803 
5804   return true;
5805 }
5806 
5807 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5808 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5809 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5810 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5811   unsigned EltSz = VT.getScalarSizeInBits();
5812   if (EltSz == 64)
5813     return false;
5814 
5815   unsigned NumElts = VT.getVectorNumElements();
5816   if (M.size() != NumElts && M.size() != NumElts*2)
5817     return false;
5818 
5819   for (unsigned i = 0; i < M.size(); i += NumElts) {
5820     if (M.size() == NumElts * 2)
5821       WhichResult = i / NumElts;
5822     else
5823       WhichResult = M[i] == 0 ? 0 : 1;
5824     for (unsigned j = 0; j < NumElts; j += 2) {
5825       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5826           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5827         return false;
5828     }
5829   }
5830 
5831   if (M.size() == NumElts*2)
5832     WhichResult = 0;
5833 
5834   return true;
5835 }
5836 
5837 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5838 // that the mask elements are either all even and in steps of size 2 or all odd
5839 // and in steps of size 2.
5840 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5841 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5842 //  v2={e,f,g,h}
5843 // Requires similar checks to that of isVTRNMask with
5844 // respect the how results are returned.
5845 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5846   unsigned EltSz = VT.getScalarSizeInBits();
5847   if (EltSz == 64)
5848     return false;
5849 
5850   unsigned NumElts = VT.getVectorNumElements();
5851   if (M.size() != NumElts && M.size() != NumElts*2)
5852     return false;
5853 
5854   for (unsigned i = 0; i < M.size(); i += NumElts) {
5855     WhichResult = M[i] == 0 ? 0 : 1;
5856     for (unsigned j = 0; j < NumElts; ++j) {
5857       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5858         return false;
5859     }
5860   }
5861 
5862   if (M.size() == NumElts*2)
5863     WhichResult = 0;
5864 
5865   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5866   if (VT.is64BitVector() && EltSz == 32)
5867     return false;
5868 
5869   return true;
5870 }
5871 
5872 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5873 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5874 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5875 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5876   unsigned EltSz = VT.getScalarSizeInBits();
5877   if (EltSz == 64)
5878     return false;
5879 
5880   unsigned NumElts = VT.getVectorNumElements();
5881   if (M.size() != NumElts && M.size() != NumElts*2)
5882     return false;
5883 
5884   unsigned Half = NumElts / 2;
5885   for (unsigned i = 0; i < M.size(); i += NumElts) {
5886     WhichResult = M[i] == 0 ? 0 : 1;
5887     for (unsigned j = 0; j < NumElts; j += Half) {
5888       unsigned Idx = WhichResult;
5889       for (unsigned k = 0; k < Half; ++k) {
5890         int MIdx = M[i + j + k];
5891         if (MIdx >= 0 && (unsigned) MIdx != Idx)
5892           return false;
5893         Idx += 2;
5894       }
5895     }
5896   }
5897 
5898   if (M.size() == NumElts*2)
5899     WhichResult = 0;
5900 
5901   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5902   if (VT.is64BitVector() && EltSz == 32)
5903     return false;
5904 
5905   return true;
5906 }
5907 
5908 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
5909 // that pairs of elements of the shufflemask represent the same index in each
5910 // vector incrementing sequentially through the vectors.
5911 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
5912 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
5913 //  v2={e,f,g,h}
5914 // Requires similar checks to that of isVTRNMask with respect the how results
5915 // are returned.
5916 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5917   unsigned EltSz = VT.getScalarSizeInBits();
5918   if (EltSz == 64)
5919     return false;
5920 
5921   unsigned NumElts = VT.getVectorNumElements();
5922   if (M.size() != NumElts && M.size() != NumElts*2)
5923     return false;
5924 
5925   for (unsigned i = 0; i < M.size(); i += NumElts) {
5926     WhichResult = M[i] == 0 ? 0 : 1;
5927     unsigned Idx = WhichResult * NumElts / 2;
5928     for (unsigned j = 0; j < NumElts; j += 2) {
5929       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5930           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
5931         return false;
5932       Idx += 1;
5933     }
5934   }
5935 
5936   if (M.size() == NumElts*2)
5937     WhichResult = 0;
5938 
5939   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5940   if (VT.is64BitVector() && EltSz == 32)
5941     return false;
5942 
5943   return true;
5944 }
5945 
5946 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
5947 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5948 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
5949 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5950   unsigned EltSz = VT.getScalarSizeInBits();
5951   if (EltSz == 64)
5952     return false;
5953 
5954   unsigned NumElts = VT.getVectorNumElements();
5955   if (M.size() != NumElts && M.size() != NumElts*2)
5956     return false;
5957 
5958   for (unsigned i = 0; i < M.size(); i += NumElts) {
5959     WhichResult = M[i] == 0 ? 0 : 1;
5960     unsigned Idx = WhichResult * NumElts / 2;
5961     for (unsigned j = 0; j < NumElts; j += 2) {
5962       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
5963           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
5964         return false;
5965       Idx += 1;
5966     }
5967   }
5968 
5969   if (M.size() == NumElts*2)
5970     WhichResult = 0;
5971 
5972   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5973   if (VT.is64BitVector() && EltSz == 32)
5974     return false;
5975 
5976   return true;
5977 }
5978 
5979 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
5980 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
5981 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
5982                                            unsigned &WhichResult,
5983                                            bool &isV_UNDEF) {
5984   isV_UNDEF = false;
5985   if (isVTRNMask(ShuffleMask, VT, WhichResult))
5986     return ARMISD::VTRN;
5987   if (isVUZPMask(ShuffleMask, VT, WhichResult))
5988     return ARMISD::VUZP;
5989   if (isVZIPMask(ShuffleMask, VT, WhichResult))
5990     return ARMISD::VZIP;
5991 
5992   isV_UNDEF = true;
5993   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
5994     return ARMISD::VTRN;
5995   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5996     return ARMISD::VUZP;
5997   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
5998     return ARMISD::VZIP;
5999 
6000   return 0;
6001 }
6002 
6003 /// \return true if this is a reverse operation on an vector.
6004 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6005   unsigned NumElts = VT.getVectorNumElements();
6006   // Make sure the mask has the right size.
6007   if (NumElts != M.size())
6008       return false;
6009 
6010   // Look for <15, ..., 3, -1, 1, 0>.
6011   for (unsigned i = 0; i != NumElts; ++i)
6012     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6013       return false;
6014 
6015   return true;
6016 }
6017 
6018 // If N is an integer constant that can be moved into a register in one
6019 // instruction, return an SDValue of such a constant (will become a MOV
6020 // instruction).  Otherwise return null.
6021 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6022                                      const ARMSubtarget *ST, const SDLoc &dl) {
6023   uint64_t Val;
6024   if (!isa<ConstantSDNode>(N))
6025     return SDValue();
6026   Val = cast<ConstantSDNode>(N)->getZExtValue();
6027 
6028   if (ST->isThumb1Only()) {
6029     if (Val <= 255 || ~Val <= 255)
6030       return DAG.getConstant(Val, dl, MVT::i32);
6031   } else {
6032     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6033       return DAG.getConstant(Val, dl, MVT::i32);
6034   }
6035   return SDValue();
6036 }
6037 
6038 // If this is a case we can't handle, return null and let the default
6039 // expansion code take care of it.
6040 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6041                                              const ARMSubtarget *ST) const {
6042   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6043   SDLoc dl(Op);
6044   EVT VT = Op.getValueType();
6045 
6046   APInt SplatBits, SplatUndef;
6047   unsigned SplatBitSize;
6048   bool HasAnyUndefs;
6049   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6050     if (SplatUndef.isAllOnesValue())
6051       return DAG.getUNDEF(VT);
6052 
6053     if (SplatBitSize <= 64) {
6054       // Check if an immediate VMOV works.
6055       EVT VmovVT;
6056       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6057                                       SplatUndef.getZExtValue(), SplatBitSize,
6058                                       DAG, dl, VmovVT, VT.is128BitVector(),
6059                                       VMOVModImm);
6060       if (Val.getNode()) {
6061         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6062         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6063       }
6064 
6065       // Try an immediate VMVN.
6066       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6067       Val = isNEONModifiedImm(NegatedImm,
6068                                       SplatUndef.getZExtValue(), SplatBitSize,
6069                                       DAG, dl, VmovVT, VT.is128BitVector(),
6070                                       VMVNModImm);
6071       if (Val.getNode()) {
6072         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6073         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6074       }
6075 
6076       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6077       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6078         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6079         if (ImmVal != -1) {
6080           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6081           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6082         }
6083       }
6084     }
6085   }
6086 
6087   // Scan through the operands to see if only one value is used.
6088   //
6089   // As an optimisation, even if more than one value is used it may be more
6090   // profitable to splat with one value then change some lanes.
6091   //
6092   // Heuristically we decide to do this if the vector has a "dominant" value,
6093   // defined as splatted to more than half of the lanes.
6094   unsigned NumElts = VT.getVectorNumElements();
6095   bool isOnlyLowElement = true;
6096   bool usesOnlyOneValue = true;
6097   bool hasDominantValue = false;
6098   bool isConstant = true;
6099 
6100   // Map of the number of times a particular SDValue appears in the
6101   // element list.
6102   DenseMap<SDValue, unsigned> ValueCounts;
6103   SDValue Value;
6104   for (unsigned i = 0; i < NumElts; ++i) {
6105     SDValue V = Op.getOperand(i);
6106     if (V.isUndef())
6107       continue;
6108     if (i > 0)
6109       isOnlyLowElement = false;
6110     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6111       isConstant = false;
6112 
6113     ValueCounts.insert(std::make_pair(V, 0));
6114     unsigned &Count = ValueCounts[V];
6115 
6116     // Is this value dominant? (takes up more than half of the lanes)
6117     if (++Count > (NumElts / 2)) {
6118       hasDominantValue = true;
6119       Value = V;
6120     }
6121   }
6122   if (ValueCounts.size() != 1)
6123     usesOnlyOneValue = false;
6124   if (!Value.getNode() && !ValueCounts.empty())
6125     Value = ValueCounts.begin()->first;
6126 
6127   if (ValueCounts.empty())
6128     return DAG.getUNDEF(VT);
6129 
6130   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6131   // Keep going if we are hitting this case.
6132   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6133     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6134 
6135   unsigned EltSize = VT.getScalarSizeInBits();
6136 
6137   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6138   // i32 and try again.
6139   if (hasDominantValue && EltSize <= 32) {
6140     if (!isConstant) {
6141       SDValue N;
6142 
6143       // If we are VDUPing a value that comes directly from a vector, that will
6144       // cause an unnecessary move to and from a GPR, where instead we could
6145       // just use VDUPLANE. We can only do this if the lane being extracted
6146       // is at a constant index, as the VDUP from lane instructions only have
6147       // constant-index forms.
6148       ConstantSDNode *constIndex;
6149       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6150           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6151         // We need to create a new undef vector to use for the VDUPLANE if the
6152         // size of the vector from which we get the value is different than the
6153         // size of the vector that we need to create. We will insert the element
6154         // such that the register coalescer will remove unnecessary copies.
6155         if (VT != Value->getOperand(0).getValueType()) {
6156           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6157                              VT.getVectorNumElements();
6158           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6159                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6160                         Value, DAG.getConstant(index, dl, MVT::i32)),
6161                            DAG.getConstant(index, dl, MVT::i32));
6162         } else
6163           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6164                         Value->getOperand(0), Value->getOperand(1));
6165       } else
6166         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6167 
6168       if (!usesOnlyOneValue) {
6169         // The dominant value was splatted as 'N', but we now have to insert
6170         // all differing elements.
6171         for (unsigned I = 0; I < NumElts; ++I) {
6172           if (Op.getOperand(I) == Value)
6173             continue;
6174           SmallVector<SDValue, 3> Ops;
6175           Ops.push_back(N);
6176           Ops.push_back(Op.getOperand(I));
6177           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6178           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6179         }
6180       }
6181       return N;
6182     }
6183     if (VT.getVectorElementType().isFloatingPoint()) {
6184       SmallVector<SDValue, 8> Ops;
6185       for (unsigned i = 0; i < NumElts; ++i)
6186         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6187                                   Op.getOperand(i)));
6188       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6189       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6190       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6191       if (Val.getNode())
6192         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6193     }
6194     if (usesOnlyOneValue) {
6195       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6196       if (isConstant && Val.getNode())
6197         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6198     }
6199   }
6200 
6201   // If all elements are constants and the case above didn't get hit, fall back
6202   // to the default expansion, which will generate a load from the constant
6203   // pool.
6204   if (isConstant)
6205     return SDValue();
6206 
6207   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6208   if (NumElts >= 4) {
6209     SDValue shuffle = ReconstructShuffle(Op, DAG);
6210     if (shuffle != SDValue())
6211       return shuffle;
6212   }
6213 
6214   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6215     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6216     // into two 64-bit vectors; we might discover a better way to lower it.
6217     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6218     EVT ExtVT = VT.getVectorElementType();
6219     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6220     SDValue Lower =
6221         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6222     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6223       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6224     SDValue Upper = DAG.getBuildVector(
6225         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6226     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6227       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6228     if (Lower && Upper)
6229       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6230   }
6231 
6232   // Vectors with 32- or 64-bit elements can be built by directly assigning
6233   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6234   // will be legalized.
6235   if (EltSize >= 32) {
6236     // Do the expansion with floating-point types, since that is what the VFP
6237     // registers are defined to use, and since i64 is not legal.
6238     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6239     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6240     SmallVector<SDValue, 8> Ops;
6241     for (unsigned i = 0; i < NumElts; ++i)
6242       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6243     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6244     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6245   }
6246 
6247   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6248   // know the default expansion would otherwise fall back on something even
6249   // worse. For a vector with one or two non-undef values, that's
6250   // scalar_to_vector for the elements followed by a shuffle (provided the
6251   // shuffle is valid for the target) and materialization element by element
6252   // on the stack followed by a load for everything else.
6253   if (!isConstant && !usesOnlyOneValue) {
6254     SDValue Vec = DAG.getUNDEF(VT);
6255     for (unsigned i = 0 ; i < NumElts; ++i) {
6256       SDValue V = Op.getOperand(i);
6257       if (V.isUndef())
6258         continue;
6259       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6260       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6261     }
6262     return Vec;
6263   }
6264 
6265   return SDValue();
6266 }
6267 
6268 // Gather data to see if the operation can be modelled as a
6269 // shuffle in combination with VEXTs.
6270 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6271                                               SelectionDAG &DAG) const {
6272   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6273   SDLoc dl(Op);
6274   EVT VT = Op.getValueType();
6275   unsigned NumElts = VT.getVectorNumElements();
6276 
6277   struct ShuffleSourceInfo {
6278     SDValue Vec;
6279     unsigned MinElt = std::numeric_limits<unsigned>::max();
6280     unsigned MaxElt = 0;
6281 
6282     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6283     // be compatible with the shuffle we intend to construct. As a result
6284     // ShuffleVec will be some sliding window into the original Vec.
6285     SDValue ShuffleVec;
6286 
6287     // Code should guarantee that element i in Vec starts at element "WindowBase
6288     // + i * WindowScale in ShuffleVec".
6289     int WindowBase = 0;
6290     int WindowScale = 1;
6291 
6292     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6293 
6294     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6295   };
6296 
6297   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6298   // node.
6299   SmallVector<ShuffleSourceInfo, 2> Sources;
6300   for (unsigned i = 0; i < NumElts; ++i) {
6301     SDValue V = Op.getOperand(i);
6302     if (V.isUndef())
6303       continue;
6304     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6305       // A shuffle can only come from building a vector from various
6306       // elements of other vectors.
6307       return SDValue();
6308     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6309       // Furthermore, shuffles require a constant mask, whereas extractelts
6310       // accept variable indices.
6311       return SDValue();
6312     }
6313 
6314     // Add this element source to the list if it's not already there.
6315     SDValue SourceVec = V.getOperand(0);
6316     auto Source = llvm::find(Sources, SourceVec);
6317     if (Source == Sources.end())
6318       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6319 
6320     // Update the minimum and maximum lane number seen.
6321     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6322     Source->MinElt = std::min(Source->MinElt, EltNo);
6323     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6324   }
6325 
6326   // Currently only do something sane when at most two source vectors
6327   // are involved.
6328   if (Sources.size() > 2)
6329     return SDValue();
6330 
6331   // Find out the smallest element size among result and two sources, and use
6332   // it as element size to build the shuffle_vector.
6333   EVT SmallestEltTy = VT.getVectorElementType();
6334   for (auto &Source : Sources) {
6335     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6336     if (SrcEltTy.bitsLT(SmallestEltTy))
6337       SmallestEltTy = SrcEltTy;
6338   }
6339   unsigned ResMultiplier =
6340       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6341   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6342   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6343 
6344   // If the source vector is too wide or too narrow, we may nevertheless be able
6345   // to construct a compatible shuffle either by concatenating it with UNDEF or
6346   // extracting a suitable range of elements.
6347   for (auto &Src : Sources) {
6348     EVT SrcVT = Src.ShuffleVec.getValueType();
6349 
6350     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6351       continue;
6352 
6353     // This stage of the search produces a source with the same element type as
6354     // the original, but with a total width matching the BUILD_VECTOR output.
6355     EVT EltVT = SrcVT.getVectorElementType();
6356     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6357     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6358 
6359     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6360       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6361         return SDValue();
6362       // We can pad out the smaller vector for free, so if it's part of a
6363       // shuffle...
6364       Src.ShuffleVec =
6365           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6366                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6367       continue;
6368     }
6369 
6370     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6371       return SDValue();
6372 
6373     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6374       // Span too large for a VEXT to cope
6375       return SDValue();
6376     }
6377 
6378     if (Src.MinElt >= NumSrcElts) {
6379       // The extraction can just take the second half
6380       Src.ShuffleVec =
6381           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6382                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6383       Src.WindowBase = -NumSrcElts;
6384     } else if (Src.MaxElt < NumSrcElts) {
6385       // The extraction can just take the first half
6386       Src.ShuffleVec =
6387           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6388                       DAG.getConstant(0, dl, MVT::i32));
6389     } else {
6390       // An actual VEXT is needed
6391       SDValue VEXTSrc1 =
6392           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6393                       DAG.getConstant(0, dl, MVT::i32));
6394       SDValue VEXTSrc2 =
6395           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6396                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6397 
6398       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6399                                    VEXTSrc2,
6400                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6401       Src.WindowBase = -Src.MinElt;
6402     }
6403   }
6404 
6405   // Another possible incompatibility occurs from the vector element types. We
6406   // can fix this by bitcasting the source vectors to the same type we intend
6407   // for the shuffle.
6408   for (auto &Src : Sources) {
6409     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6410     if (SrcEltTy == SmallestEltTy)
6411       continue;
6412     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6413     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6414     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6415     Src.WindowBase *= Src.WindowScale;
6416   }
6417 
6418   // Final sanity check before we try to actually produce a shuffle.
6419   DEBUG(
6420     for (auto Src : Sources)
6421       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6422   );
6423 
6424   // The stars all align, our next step is to produce the mask for the shuffle.
6425   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6426   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6427   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6428     SDValue Entry = Op.getOperand(i);
6429     if (Entry.isUndef())
6430       continue;
6431 
6432     auto Src = llvm::find(Sources, Entry.getOperand(0));
6433     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6434 
6435     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6436     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6437     // segment.
6438     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6439     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6440                                VT.getScalarSizeInBits());
6441     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6442 
6443     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6444     // starting at the appropriate offset.
6445     int *LaneMask = &Mask[i * ResMultiplier];
6446 
6447     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6448     ExtractBase += NumElts * (Src - Sources.begin());
6449     for (int j = 0; j < LanesDefined; ++j)
6450       LaneMask[j] = ExtractBase + j;
6451   }
6452 
6453   // Final check before we try to produce nonsense...
6454   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6455     return SDValue();
6456 
6457   // We can't handle more than two sources. This should have already
6458   // been checked before this point.
6459   assert(Sources.size() <= 2 && "Too many sources!");
6460 
6461   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6462   for (unsigned i = 0; i < Sources.size(); ++i)
6463     ShuffleOps[i] = Sources[i].ShuffleVec;
6464 
6465   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6466                                          ShuffleOps[1], Mask);
6467   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6468 }
6469 
6470 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6471 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6472 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6473 /// are assumed to be legal.
6474 bool
6475 ARMTargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
6476                                       EVT VT) const {
6477   if (VT.getVectorNumElements() == 4 &&
6478       (VT.is128BitVector() || VT.is64BitVector())) {
6479     unsigned PFIndexes[4];
6480     for (unsigned i = 0; i != 4; ++i) {
6481       if (M[i] < 0)
6482         PFIndexes[i] = 8;
6483       else
6484         PFIndexes[i] = M[i];
6485     }
6486 
6487     // Compute the index in the perfect shuffle table.
6488     unsigned PFTableIndex =
6489       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6490     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6491     unsigned Cost = (PFEntry >> 30);
6492 
6493     if (Cost <= 4)
6494       return true;
6495   }
6496 
6497   bool ReverseVEXT, isV_UNDEF;
6498   unsigned Imm, WhichResult;
6499 
6500   unsigned EltSize = VT.getScalarSizeInBits();
6501   return (EltSize >= 32 ||
6502           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6503           isVREVMask(M, VT, 64) ||
6504           isVREVMask(M, VT, 32) ||
6505           isVREVMask(M, VT, 16) ||
6506           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6507           isVTBLMask(M, VT) ||
6508           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6509           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6510 }
6511 
6512 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6513 /// the specified operations to build the shuffle.
6514 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6515                                       SDValue RHS, SelectionDAG &DAG,
6516                                       const SDLoc &dl) {
6517   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6518   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6519   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6520 
6521   enum {
6522     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6523     OP_VREV,
6524     OP_VDUP0,
6525     OP_VDUP1,
6526     OP_VDUP2,
6527     OP_VDUP3,
6528     OP_VEXT1,
6529     OP_VEXT2,
6530     OP_VEXT3,
6531     OP_VUZPL, // VUZP, left result
6532     OP_VUZPR, // VUZP, right result
6533     OP_VZIPL, // VZIP, left result
6534     OP_VZIPR, // VZIP, right result
6535     OP_VTRNL, // VTRN, left result
6536     OP_VTRNR  // VTRN, right result
6537   };
6538 
6539   if (OpNum == OP_COPY) {
6540     if (LHSID == (1*9+2)*9+3) return LHS;
6541     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6542     return RHS;
6543   }
6544 
6545   SDValue OpLHS, OpRHS;
6546   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6547   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6548   EVT VT = OpLHS.getValueType();
6549 
6550   switch (OpNum) {
6551   default: llvm_unreachable("Unknown shuffle opcode!");
6552   case OP_VREV:
6553     // VREV divides the vector in half and swaps within the half.
6554     if (VT.getVectorElementType() == MVT::i32 ||
6555         VT.getVectorElementType() == MVT::f32)
6556       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6557     // vrev <4 x i16> -> VREV32
6558     if (VT.getVectorElementType() == MVT::i16)
6559       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6560     // vrev <4 x i8> -> VREV16
6561     assert(VT.getVectorElementType() == MVT::i8);
6562     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6563   case OP_VDUP0:
6564   case OP_VDUP1:
6565   case OP_VDUP2:
6566   case OP_VDUP3:
6567     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6568                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6569   case OP_VEXT1:
6570   case OP_VEXT2:
6571   case OP_VEXT3:
6572     return DAG.getNode(ARMISD::VEXT, dl, VT,
6573                        OpLHS, OpRHS,
6574                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6575   case OP_VUZPL:
6576   case OP_VUZPR:
6577     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6578                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6579   case OP_VZIPL:
6580   case OP_VZIPR:
6581     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6582                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6583   case OP_VTRNL:
6584   case OP_VTRNR:
6585     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6586                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6587   }
6588 }
6589 
6590 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6591                                        ArrayRef<int> ShuffleMask,
6592                                        SelectionDAG &DAG) {
6593   // Check to see if we can use the VTBL instruction.
6594   SDValue V1 = Op.getOperand(0);
6595   SDValue V2 = Op.getOperand(1);
6596   SDLoc DL(Op);
6597 
6598   SmallVector<SDValue, 8> VTBLMask;
6599   for (ArrayRef<int>::iterator
6600          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6601     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6602 
6603   if (V2.getNode()->isUndef())
6604     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6605                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6606 
6607   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6608                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6609 }
6610 
6611 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6612                                                       SelectionDAG &DAG) {
6613   SDLoc DL(Op);
6614   SDValue OpLHS = Op.getOperand(0);
6615   EVT VT = OpLHS.getValueType();
6616 
6617   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6618          "Expect an v8i16/v16i8 type");
6619   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6620   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6621   // extract the first 8 bytes into the top double word and the last 8 bytes
6622   // into the bottom double word. The v8i16 case is similar.
6623   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6624   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6625                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6626 }
6627 
6628 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6629   SDValue V1 = Op.getOperand(0);
6630   SDValue V2 = Op.getOperand(1);
6631   SDLoc dl(Op);
6632   EVT VT = Op.getValueType();
6633   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6634 
6635   // Convert shuffles that are directly supported on NEON to target-specific
6636   // DAG nodes, instead of keeping them as shuffles and matching them again
6637   // during code selection.  This is more efficient and avoids the possibility
6638   // of inconsistencies between legalization and selection.
6639   // FIXME: floating-point vectors should be canonicalized to integer vectors
6640   // of the same time so that they get CSEd properly.
6641   ArrayRef<int> ShuffleMask = SVN->getMask();
6642 
6643   unsigned EltSize = VT.getScalarSizeInBits();
6644   if (EltSize <= 32) {
6645     if (SVN->isSplat()) {
6646       int Lane = SVN->getSplatIndex();
6647       // If this is undef splat, generate it via "just" vdup, if possible.
6648       if (Lane == -1) Lane = 0;
6649 
6650       // Test if V1 is a SCALAR_TO_VECTOR.
6651       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6652         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6653       }
6654       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6655       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6656       // reaches it).
6657       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6658           !isa<ConstantSDNode>(V1.getOperand(0))) {
6659         bool IsScalarToVector = true;
6660         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6661           if (!V1.getOperand(i).isUndef()) {
6662             IsScalarToVector = false;
6663             break;
6664           }
6665         if (IsScalarToVector)
6666           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6667       }
6668       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6669                          DAG.getConstant(Lane, dl, MVT::i32));
6670     }
6671 
6672     bool ReverseVEXT;
6673     unsigned Imm;
6674     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6675       if (ReverseVEXT)
6676         std::swap(V1, V2);
6677       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6678                          DAG.getConstant(Imm, dl, MVT::i32));
6679     }
6680 
6681     if (isVREVMask(ShuffleMask, VT, 64))
6682       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6683     if (isVREVMask(ShuffleMask, VT, 32))
6684       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6685     if (isVREVMask(ShuffleMask, VT, 16))
6686       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6687 
6688     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6689       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6690                          DAG.getConstant(Imm, dl, MVT::i32));
6691     }
6692 
6693     // Check for Neon shuffles that modify both input vectors in place.
6694     // If both results are used, i.e., if there are two shuffles with the same
6695     // source operands and with masks corresponding to both results of one of
6696     // these operations, DAG memoization will ensure that a single node is
6697     // used for both shuffles.
6698     unsigned WhichResult;
6699     bool isV_UNDEF;
6700     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6701             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6702       if (isV_UNDEF)
6703         V2 = V1;
6704       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6705           .getValue(WhichResult);
6706     }
6707 
6708     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6709     // shuffles that produce a result larger than their operands with:
6710     //   shuffle(concat(v1, undef), concat(v2, undef))
6711     // ->
6712     //   shuffle(concat(v1, v2), undef)
6713     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6714     //
6715     // This is useful in the general case, but there are special cases where
6716     // native shuffles produce larger results: the two-result ops.
6717     //
6718     // Look through the concat when lowering them:
6719     //   shuffle(concat(v1, v2), undef)
6720     // ->
6721     //   concat(VZIP(v1, v2):0, :1)
6722     //
6723     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6724       SDValue SubV1 = V1->getOperand(0);
6725       SDValue SubV2 = V1->getOperand(1);
6726       EVT SubVT = SubV1.getValueType();
6727 
6728       // We expect these to have been canonicalized to -1.
6729       assert(llvm::all_of(ShuffleMask, [&](int i) {
6730         return i < (int)VT.getVectorNumElements();
6731       }) && "Unexpected shuffle index into UNDEF operand!");
6732 
6733       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6734               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6735         if (isV_UNDEF)
6736           SubV2 = SubV1;
6737         assert((WhichResult == 0) &&
6738                "In-place shuffle of concat can only have one result!");
6739         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6740                                   SubV1, SubV2);
6741         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6742                            Res.getValue(1));
6743       }
6744     }
6745   }
6746 
6747   // If the shuffle is not directly supported and it has 4 elements, use
6748   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6749   unsigned NumElts = VT.getVectorNumElements();
6750   if (NumElts == 4) {
6751     unsigned PFIndexes[4];
6752     for (unsigned i = 0; i != 4; ++i) {
6753       if (ShuffleMask[i] < 0)
6754         PFIndexes[i] = 8;
6755       else
6756         PFIndexes[i] = ShuffleMask[i];
6757     }
6758 
6759     // Compute the index in the perfect shuffle table.
6760     unsigned PFTableIndex =
6761       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6762     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6763     unsigned Cost = (PFEntry >> 30);
6764 
6765     if (Cost <= 4)
6766       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6767   }
6768 
6769   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6770   if (EltSize >= 32) {
6771     // Do the expansion with floating-point types, since that is what the VFP
6772     // registers are defined to use, and since i64 is not legal.
6773     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6774     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6775     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6776     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6777     SmallVector<SDValue, 8> Ops;
6778     for (unsigned i = 0; i < NumElts; ++i) {
6779       if (ShuffleMask[i] < 0)
6780         Ops.push_back(DAG.getUNDEF(EltVT));
6781       else
6782         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6783                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6784                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6785                                                   dl, MVT::i32)));
6786     }
6787     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6788     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6789   }
6790 
6791   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6792     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6793 
6794   if (VT == MVT::v8i8)
6795     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6796       return NewOp;
6797 
6798   return SDValue();
6799 }
6800 
6801 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6802   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6803   SDValue Lane = Op.getOperand(2);
6804   if (!isa<ConstantSDNode>(Lane))
6805     return SDValue();
6806 
6807   return Op;
6808 }
6809 
6810 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6811   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6812   SDValue Lane = Op.getOperand(1);
6813   if (!isa<ConstantSDNode>(Lane))
6814     return SDValue();
6815 
6816   SDValue Vec = Op.getOperand(0);
6817   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
6818     SDLoc dl(Op);
6819     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6820   }
6821 
6822   return Op;
6823 }
6824 
6825 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6826   // The only time a CONCAT_VECTORS operation can have legal types is when
6827   // two 64-bit vectors are concatenated to a 128-bit vector.
6828   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6829          "unexpected CONCAT_VECTORS");
6830   SDLoc dl(Op);
6831   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6832   SDValue Op0 = Op.getOperand(0);
6833   SDValue Op1 = Op.getOperand(1);
6834   if (!Op0.isUndef())
6835     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6836                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6837                       DAG.getIntPtrConstant(0, dl));
6838   if (!Op1.isUndef())
6839     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6840                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6841                       DAG.getIntPtrConstant(1, dl));
6842   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6843 }
6844 
6845 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6846 /// element has been zero/sign-extended, depending on the isSigned parameter,
6847 /// from an integer type half its size.
6848 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6849                                    bool isSigned) {
6850   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6851   EVT VT = N->getValueType(0);
6852   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6853     SDNode *BVN = N->getOperand(0).getNode();
6854     if (BVN->getValueType(0) != MVT::v4i32 ||
6855         BVN->getOpcode() != ISD::BUILD_VECTOR)
6856       return false;
6857     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6858     unsigned HiElt = 1 - LoElt;
6859     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6860     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6861     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6862     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6863     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6864       return false;
6865     if (isSigned) {
6866       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6867           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6868         return true;
6869     } else {
6870       if (Hi0->isNullValue() && Hi1->isNullValue())
6871         return true;
6872     }
6873     return false;
6874   }
6875 
6876   if (N->getOpcode() != ISD::BUILD_VECTOR)
6877     return false;
6878 
6879   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6880     SDNode *Elt = N->getOperand(i).getNode();
6881     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6882       unsigned EltSize = VT.getScalarSizeInBits();
6883       unsigned HalfSize = EltSize / 2;
6884       if (isSigned) {
6885         if (!isIntN(HalfSize, C->getSExtValue()))
6886           return false;
6887       } else {
6888         if (!isUIntN(HalfSize, C->getZExtValue()))
6889           return false;
6890       }
6891       continue;
6892     }
6893     return false;
6894   }
6895 
6896   return true;
6897 }
6898 
6899 /// isSignExtended - Check if a node is a vector value that is sign-extended
6900 /// or a constant BUILD_VECTOR with sign-extended elements.
6901 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
6902   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
6903     return true;
6904   if (isExtendedBUILD_VECTOR(N, DAG, true))
6905     return true;
6906   return false;
6907 }
6908 
6909 /// isZeroExtended - Check if a node is a vector value that is zero-extended
6910 /// or a constant BUILD_VECTOR with zero-extended elements.
6911 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
6912   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
6913     return true;
6914   if (isExtendedBUILD_VECTOR(N, DAG, false))
6915     return true;
6916   return false;
6917 }
6918 
6919 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
6920   if (OrigVT.getSizeInBits() >= 64)
6921     return OrigVT;
6922 
6923   assert(OrigVT.isSimple() && "Expecting a simple value type");
6924 
6925   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
6926   switch (OrigSimpleTy) {
6927   default: llvm_unreachable("Unexpected Vector Type");
6928   case MVT::v2i8:
6929   case MVT::v2i16:
6930      return MVT::v2i32;
6931   case MVT::v4i8:
6932     return  MVT::v4i16;
6933   }
6934 }
6935 
6936 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
6937 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
6938 /// We insert the required extension here to get the vector to fill a D register.
6939 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
6940                                             const EVT &OrigTy,
6941                                             const EVT &ExtTy,
6942                                             unsigned ExtOpcode) {
6943   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
6944   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
6945   // 64-bits we need to insert a new extension so that it will be 64-bits.
6946   assert(ExtTy.is128BitVector() && "Unexpected extension size");
6947   if (OrigTy.getSizeInBits() >= 64)
6948     return N;
6949 
6950   // Must extend size to at least 64 bits to be used as an operand for VMULL.
6951   EVT NewVT = getExtensionTo64Bits(OrigTy);
6952 
6953   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
6954 }
6955 
6956 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
6957 /// does not do any sign/zero extension. If the original vector is less
6958 /// than 64 bits, an appropriate extension will be added after the load to
6959 /// reach a total size of 64 bits. We have to add the extension separately
6960 /// because ARM does not have a sign/zero extending load for vectors.
6961 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
6962   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
6963 
6964   // The load already has the right type.
6965   if (ExtendedTy == LD->getMemoryVT())
6966     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
6967                        LD->getBasePtr(), LD->getPointerInfo(),
6968                        LD->getAlignment(), LD->getMemOperand()->getFlags());
6969 
6970   // We need to create a zextload/sextload. We cannot just create a load
6971   // followed by a zext/zext node because LowerMUL is also run during normal
6972   // operation legalization where we can't create illegal types.
6973   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
6974                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
6975                         LD->getMemoryVT(), LD->getAlignment(),
6976                         LD->getMemOperand()->getFlags());
6977 }
6978 
6979 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
6980 /// extending load, or BUILD_VECTOR with extended elements, return the
6981 /// unextended value. The unextended vector should be 64 bits so that it can
6982 /// be used as an operand to a VMULL instruction. If the original vector size
6983 /// before extension is less than 64 bits we add a an extension to resize
6984 /// the vector to 64 bits.
6985 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
6986   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
6987     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
6988                                         N->getOperand(0)->getValueType(0),
6989                                         N->getValueType(0),
6990                                         N->getOpcode());
6991 
6992   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6993     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
6994            "Expected extending load");
6995 
6996     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
6997     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
6998     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6999     SDValue extLoad =
7000         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7001     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7002 
7003     return newLoad;
7004   }
7005 
7006   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7007   // have been legalized as a BITCAST from v4i32.
7008   if (N->getOpcode() == ISD::BITCAST) {
7009     SDNode *BVN = N->getOperand(0).getNode();
7010     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7011            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7012     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7013     return DAG.getBuildVector(
7014         MVT::v2i32, SDLoc(N),
7015         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7016   }
7017   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7018   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7019   EVT VT = N->getValueType(0);
7020   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7021   unsigned NumElts = VT.getVectorNumElements();
7022   MVT TruncVT = MVT::getIntegerVT(EltSize);
7023   SmallVector<SDValue, 8> Ops;
7024   SDLoc dl(N);
7025   for (unsigned i = 0; i != NumElts; ++i) {
7026     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7027     const APInt &CInt = C->getAPIntValue();
7028     // Element types smaller than 32 bits are not legal, so use i32 elements.
7029     // The values are implicitly truncated so sext vs. zext doesn't matter.
7030     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7031   }
7032   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7033 }
7034 
7035 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7036   unsigned Opcode = N->getOpcode();
7037   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7038     SDNode *N0 = N->getOperand(0).getNode();
7039     SDNode *N1 = N->getOperand(1).getNode();
7040     return N0->hasOneUse() && N1->hasOneUse() &&
7041       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7042   }
7043   return false;
7044 }
7045 
7046 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7047   unsigned Opcode = N->getOpcode();
7048   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7049     SDNode *N0 = N->getOperand(0).getNode();
7050     SDNode *N1 = N->getOperand(1).getNode();
7051     return N0->hasOneUse() && N1->hasOneUse() &&
7052       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7053   }
7054   return false;
7055 }
7056 
7057 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7058   // Multiplications are only custom-lowered for 128-bit vectors so that
7059   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7060   EVT VT = Op.getValueType();
7061   assert(VT.is128BitVector() && VT.isInteger() &&
7062          "unexpected type for custom-lowering ISD::MUL");
7063   SDNode *N0 = Op.getOperand(0).getNode();
7064   SDNode *N1 = Op.getOperand(1).getNode();
7065   unsigned NewOpc = 0;
7066   bool isMLA = false;
7067   bool isN0SExt = isSignExtended(N0, DAG);
7068   bool isN1SExt = isSignExtended(N1, DAG);
7069   if (isN0SExt && isN1SExt)
7070     NewOpc = ARMISD::VMULLs;
7071   else {
7072     bool isN0ZExt = isZeroExtended(N0, DAG);
7073     bool isN1ZExt = isZeroExtended(N1, DAG);
7074     if (isN0ZExt && isN1ZExt)
7075       NewOpc = ARMISD::VMULLu;
7076     else if (isN1SExt || isN1ZExt) {
7077       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7078       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7079       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7080         NewOpc = ARMISD::VMULLs;
7081         isMLA = true;
7082       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7083         NewOpc = ARMISD::VMULLu;
7084         isMLA = true;
7085       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7086         std::swap(N0, N1);
7087         NewOpc = ARMISD::VMULLu;
7088         isMLA = true;
7089       }
7090     }
7091 
7092     if (!NewOpc) {
7093       if (VT == MVT::v2i64)
7094         // Fall through to expand this.  It is not legal.
7095         return SDValue();
7096       else
7097         // Other vector multiplications are legal.
7098         return Op;
7099     }
7100   }
7101 
7102   // Legalize to a VMULL instruction.
7103   SDLoc DL(Op);
7104   SDValue Op0;
7105   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7106   if (!isMLA) {
7107     Op0 = SkipExtensionForVMULL(N0, DAG);
7108     assert(Op0.getValueType().is64BitVector() &&
7109            Op1.getValueType().is64BitVector() &&
7110            "unexpected types for extended operands to VMULL");
7111     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7112   }
7113 
7114   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7115   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7116   //   vmull q0, d4, d6
7117   //   vmlal q0, d5, d6
7118   // is faster than
7119   //   vaddl q0, d4, d5
7120   //   vmovl q1, d6
7121   //   vmul  q0, q0, q1
7122   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7123   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7124   EVT Op1VT = Op1.getValueType();
7125   return DAG.getNode(N0->getOpcode(), DL, VT,
7126                      DAG.getNode(NewOpc, DL, VT,
7127                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7128                      DAG.getNode(NewOpc, DL, VT,
7129                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7130 }
7131 
7132 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7133                               SelectionDAG &DAG) {
7134   // TODO: Should this propagate fast-math-flags?
7135 
7136   // Convert to float
7137   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7138   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7139   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7140   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7141   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7142   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7143   // Get reciprocal estimate.
7144   // float4 recip = vrecpeq_f32(yf);
7145   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7146                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7147                    Y);
7148   // Because char has a smaller range than uchar, we can actually get away
7149   // without any newton steps.  This requires that we use a weird bias
7150   // of 0xb000, however (again, this has been exhaustively tested).
7151   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7152   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7153   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7154   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7155   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7156   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7157   // Convert back to short.
7158   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7159   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7160   return X;
7161 }
7162 
7163 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7164                                SelectionDAG &DAG) {
7165   // TODO: Should this propagate fast-math-flags?
7166 
7167   SDValue N2;
7168   // Convert to float.
7169   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7170   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7171   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7172   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7173   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7174   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7175 
7176   // Use reciprocal estimate and one refinement step.
7177   // float4 recip = vrecpeq_f32(yf);
7178   // recip *= vrecpsq_f32(yf, recip);
7179   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7180                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7181                    N1);
7182   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7183                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7184                    N1, N2);
7185   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7186   // Because short has a smaller range than ushort, we can actually get away
7187   // with only a single newton step.  This requires that we use a weird bias
7188   // of 89, however (again, this has been exhaustively tested).
7189   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7190   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7191   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7192   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7193   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7194   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7195   // Convert back to integer and return.
7196   // return vmovn_s32(vcvt_s32_f32(result));
7197   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7198   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7199   return N0;
7200 }
7201 
7202 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7203   EVT VT = Op.getValueType();
7204   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7205          "unexpected type for custom-lowering ISD::SDIV");
7206 
7207   SDLoc dl(Op);
7208   SDValue N0 = Op.getOperand(0);
7209   SDValue N1 = Op.getOperand(1);
7210   SDValue N2, N3;
7211 
7212   if (VT == MVT::v8i8) {
7213     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7214     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7215 
7216     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7217                      DAG.getIntPtrConstant(4, dl));
7218     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7219                      DAG.getIntPtrConstant(4, dl));
7220     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7221                      DAG.getIntPtrConstant(0, dl));
7222     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7223                      DAG.getIntPtrConstant(0, dl));
7224 
7225     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7226     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7227 
7228     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7229     N0 = LowerCONCAT_VECTORS(N0, DAG);
7230 
7231     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7232     return N0;
7233   }
7234   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7235 }
7236 
7237 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7238   // TODO: Should this propagate fast-math-flags?
7239   EVT VT = Op.getValueType();
7240   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7241          "unexpected type for custom-lowering ISD::UDIV");
7242 
7243   SDLoc dl(Op);
7244   SDValue N0 = Op.getOperand(0);
7245   SDValue N1 = Op.getOperand(1);
7246   SDValue N2, N3;
7247 
7248   if (VT == MVT::v8i8) {
7249     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7250     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7251 
7252     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7253                      DAG.getIntPtrConstant(4, dl));
7254     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7255                      DAG.getIntPtrConstant(4, dl));
7256     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7257                      DAG.getIntPtrConstant(0, dl));
7258     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7259                      DAG.getIntPtrConstant(0, dl));
7260 
7261     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7262     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7263 
7264     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7265     N0 = LowerCONCAT_VECTORS(N0, DAG);
7266 
7267     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7268                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7269                                      MVT::i32),
7270                      N0);
7271     return N0;
7272   }
7273 
7274   // v4i16 sdiv ... Convert to float.
7275   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7276   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7277   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7278   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7279   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7280   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7281 
7282   // Use reciprocal estimate and two refinement steps.
7283   // float4 recip = vrecpeq_f32(yf);
7284   // recip *= vrecpsq_f32(yf, recip);
7285   // recip *= vrecpsq_f32(yf, recip);
7286   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7287                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7288                    BN1);
7289   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7290                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7291                    BN1, N2);
7292   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7293   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7294                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7295                    BN1, N2);
7296   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7297   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7298   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7299   // and that it will never cause us to return an answer too large).
7300   // float4 result = as_float4(as_int4(xf*recip) + 2);
7301   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7302   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7303   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7304   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7305   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7306   // Convert back to integer and return.
7307   // return vmovn_u32(vcvt_s32_f32(result));
7308   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7309   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7310   return N0;
7311 }
7312 
7313 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7314   EVT VT = Op.getNode()->getValueType(0);
7315   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7316 
7317   unsigned Opc;
7318   bool ExtraOp = false;
7319   switch (Op.getOpcode()) {
7320   default: llvm_unreachable("Invalid code");
7321   case ISD::ADDC: Opc = ARMISD::ADDC; break;
7322   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7323   case ISD::SUBC: Opc = ARMISD::SUBC; break;
7324   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7325   }
7326 
7327   if (!ExtraOp)
7328     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7329                        Op.getOperand(1));
7330   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7331                      Op.getOperand(1), Op.getOperand(2));
7332 }
7333 
7334 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7335   assert(Subtarget->isTargetDarwin());
7336 
7337   // For iOS, we want to call an alternative entry point: __sincos_stret,
7338   // return values are passed via sret.
7339   SDLoc dl(Op);
7340   SDValue Arg = Op.getOperand(0);
7341   EVT ArgVT = Arg.getValueType();
7342   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7343   auto PtrVT = getPointerTy(DAG.getDataLayout());
7344 
7345   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7346   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7347 
7348   // Pair of floats / doubles used to pass the result.
7349   Type *RetTy = StructType::get(ArgTy, ArgTy, nullptr);
7350   auto &DL = DAG.getDataLayout();
7351 
7352   ArgListTy Args;
7353   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7354   SDValue SRet;
7355   if (ShouldUseSRet) {
7356     // Create stack object for sret.
7357     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7358     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7359     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7360     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7361 
7362     ArgListEntry Entry;
7363     Entry.Node = SRet;
7364     Entry.Ty = RetTy->getPointerTo();
7365     Entry.IsSExt = false;
7366     Entry.IsZExt = false;
7367     Entry.IsSRet = true;
7368     Args.push_back(Entry);
7369     RetTy = Type::getVoidTy(*DAG.getContext());
7370   }
7371 
7372   ArgListEntry Entry;
7373   Entry.Node = Arg;
7374   Entry.Ty = ArgTy;
7375   Entry.IsSExt = false;
7376   Entry.IsZExt = false;
7377   Args.push_back(Entry);
7378 
7379   const char *LibcallName =
7380       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
7381   RTLIB::Libcall LC =
7382       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
7383   CallingConv::ID CC = getLibcallCallingConv(LC);
7384   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7385 
7386   TargetLowering::CallLoweringInfo CLI(DAG);
7387   CLI.setDebugLoc(dl)
7388       .setChain(DAG.getEntryNode())
7389       .setCallee(CC, RetTy, Callee, std::move(Args))
7390       .setDiscardResult(ShouldUseSRet);
7391   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7392 
7393   if (!ShouldUseSRet)
7394     return CallResult.first;
7395 
7396   SDValue LoadSin =
7397       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7398 
7399   // Address of cos field.
7400   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7401                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7402   SDValue LoadCos =
7403       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7404 
7405   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7406   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7407                      LoadSin.getValue(0), LoadCos.getValue(0));
7408 }
7409 
7410 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7411                                                   bool Signed,
7412                                                   SDValue &Chain) const {
7413   EVT VT = Op.getValueType();
7414   assert((VT == MVT::i32 || VT == MVT::i64) &&
7415          "unexpected type for custom lowering DIV");
7416   SDLoc dl(Op);
7417 
7418   const auto &DL = DAG.getDataLayout();
7419   const auto &TLI = DAG.getTargetLoweringInfo();
7420 
7421   const char *Name = nullptr;
7422   if (Signed)
7423     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7424   else
7425     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7426 
7427   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7428 
7429   ARMTargetLowering::ArgListTy Args;
7430 
7431   for (auto AI : {1, 0}) {
7432     ArgListEntry Arg;
7433     Arg.Node = Op.getOperand(AI);
7434     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7435     Args.push_back(Arg);
7436   }
7437 
7438   CallLoweringInfo CLI(DAG);
7439   CLI.setDebugLoc(dl)
7440     .setChain(Chain)
7441     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7442                ES, std::move(Args));
7443 
7444   return LowerCallTo(CLI).first;
7445 }
7446 
7447 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7448                                             bool Signed) const {
7449   assert(Op.getValueType() == MVT::i32 &&
7450          "unexpected type for custom lowering DIV");
7451   SDLoc dl(Op);
7452 
7453   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7454                                DAG.getEntryNode(), Op.getOperand(1));
7455 
7456   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7457 }
7458 
7459 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7460   SDLoc DL(N);
7461   SDValue Op = N->getOperand(1);
7462   if (N->getValueType(0) == MVT::i32)
7463     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7464   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7465                            DAG.getConstant(0, DL, MVT::i32));
7466   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7467                            DAG.getConstant(1, DL, MVT::i32));
7468   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7469                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7470 }
7471 
7472 void ARMTargetLowering::ExpandDIV_Windows(
7473     SDValue Op, SelectionDAG &DAG, bool Signed,
7474     SmallVectorImpl<SDValue> &Results) const {
7475   const auto &DL = DAG.getDataLayout();
7476   const auto &TLI = DAG.getTargetLoweringInfo();
7477 
7478   assert(Op.getValueType() == MVT::i64 &&
7479          "unexpected type for custom lowering DIV");
7480   SDLoc dl(Op);
7481 
7482   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7483 
7484   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7485 
7486   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7487   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7488                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7489   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7490 
7491   Results.push_back(Lower);
7492   Results.push_back(Upper);
7493 }
7494 
7495 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7496   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7497     // Acquire/Release load/store is not legal for targets without a dmb or
7498     // equivalent available.
7499     return SDValue();
7500 
7501   // Monotonic load/store is legal for all targets.
7502   return Op;
7503 }
7504 
7505 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7506                                     SmallVectorImpl<SDValue> &Results,
7507                                     SelectionDAG &DAG,
7508                                     const ARMSubtarget *Subtarget) {
7509   SDLoc DL(N);
7510   // Under Power Management extensions, the cycle-count is:
7511   //    mrc p15, #0, <Rt>, c9, c13, #0
7512   SDValue Ops[] = { N->getOperand(0), // Chain
7513                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7514                     DAG.getConstant(15, DL, MVT::i32),
7515                     DAG.getConstant(0, DL, MVT::i32),
7516                     DAG.getConstant(9, DL, MVT::i32),
7517                     DAG.getConstant(13, DL, MVT::i32),
7518                     DAG.getConstant(0, DL, MVT::i32)
7519   };
7520 
7521   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7522                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7523   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7524                                 DAG.getConstant(0, DL, MVT::i32)));
7525   Results.push_back(Cycles32.getValue(1));
7526 }
7527 
7528 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7529   SDLoc dl(V.getNode());
7530   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7531   SDValue VHi = DAG.getAnyExtOrTrunc(
7532       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7533       dl, MVT::i32);
7534   SDValue RegClass =
7535       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7536   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7537   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7538   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7539   return SDValue(
7540       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7541 }
7542 
7543 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7544                                        SmallVectorImpl<SDValue> & Results,
7545                                        SelectionDAG &DAG) {
7546   assert(N->getValueType(0) == MVT::i64 &&
7547          "AtomicCmpSwap on types less than 64 should be legal");
7548   SDValue Ops[] = {N->getOperand(1),
7549                    createGPRPairNode(DAG, N->getOperand(2)),
7550                    createGPRPairNode(DAG, N->getOperand(3)),
7551                    N->getOperand(0)};
7552   SDNode *CmpSwap = DAG.getMachineNode(
7553       ARM::CMP_SWAP_64, SDLoc(N),
7554       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7555 
7556   MachineFunction &MF = DAG.getMachineFunction();
7557   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7558   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7559   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7560 
7561   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_0, SDLoc(N), MVT::i32,
7562                                                SDValue(CmpSwap, 0)));
7563   Results.push_back(DAG.getTargetExtractSubreg(ARM::gsub_1, SDLoc(N), MVT::i32,
7564                                                SDValue(CmpSwap, 0)));
7565   Results.push_back(SDValue(CmpSwap, 2));
7566 }
7567 
7568 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7569                           SelectionDAG &DAG) {
7570   const auto &TLI = DAG.getTargetLoweringInfo();
7571 
7572   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7573          "Custom lowering is MSVCRT specific!");
7574 
7575   SDLoc dl(Op);
7576   SDValue Val = Op.getOperand(0);
7577   MVT Ty = Val->getSimpleValueType(0);
7578   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7579   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7580                                          TLI.getPointerTy(DAG.getDataLayout()));
7581 
7582   TargetLowering::ArgListTy Args;
7583   TargetLowering::ArgListEntry Entry;
7584 
7585   Entry.Node = Val;
7586   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7587   Entry.IsZExt = true;
7588   Args.push_back(Entry);
7589 
7590   Entry.Node = Exponent;
7591   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7592   Entry.IsZExt = true;
7593   Args.push_back(Entry);
7594 
7595   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7596 
7597   // In the in-chain to the call is the entry node  If we are emitting a
7598   // tailcall, the chain will be mutated if the node has a non-entry input
7599   // chain.
7600   SDValue InChain = DAG.getEntryNode();
7601   SDValue TCChain = InChain;
7602 
7603   const auto *F = DAG.getMachineFunction().getFunction();
7604   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
7605               F->getReturnType() == LCRTy;
7606   if (IsTC)
7607     InChain = TCChain;
7608 
7609   TargetLowering::CallLoweringInfo CLI(DAG);
7610   CLI.setDebugLoc(dl)
7611       .setChain(InChain)
7612       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
7613       .setTailCall(IsTC);
7614   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
7615 
7616   // Return the chain (the DAG root) if it is a tail call
7617   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
7618 }
7619 
7620 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7621   switch (Op.getOpcode()) {
7622   default: llvm_unreachable("Don't know how to custom lower this!");
7623   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7624   case ISD::ConstantPool:
7625     if (Subtarget->genExecuteOnly())
7626       llvm_unreachable("execute-only should not generate constant pools");
7627     return LowerConstantPool(Op, DAG);
7628   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7629   case ISD::GlobalAddress:
7630     switch (Subtarget->getTargetTriple().getObjectFormat()) {
7631     default: llvm_unreachable("unknown object format");
7632     case Triple::COFF:
7633       return LowerGlobalAddressWindows(Op, DAG);
7634     case Triple::ELF:
7635       return LowerGlobalAddressELF(Op, DAG);
7636     case Triple::MachO:
7637       return LowerGlobalAddressDarwin(Op, DAG);
7638     }
7639   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7640   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7641   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7642   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7643   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7644   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7645   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7646   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7647   case ISD::SINT_TO_FP:
7648   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7649   case ISD::FP_TO_SINT:
7650   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7651   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7652   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7653   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7654   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7655   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7656   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7657   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7658                                                                Subtarget);
7659   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
7660   case ISD::SHL:
7661   case ISD::SRL:
7662   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
7663   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
7664   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
7665   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
7666   case ISD::SRL_PARTS:
7667   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7668   case ISD::CTTZ:
7669   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7670   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7671   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7672   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
7673   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7674   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7675   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7676   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7677   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7678   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7679   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7680   case ISD::MUL:           return LowerMUL(Op, DAG);
7681   case ISD::SDIV:
7682     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7683       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7684     return LowerSDIV(Op, DAG);
7685   case ISD::UDIV:
7686     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7687       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7688     return LowerUDIV(Op, DAG);
7689   case ISD::ADDC:
7690   case ISD::ADDE:
7691   case ISD::SUBC:
7692   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7693   case ISD::SADDO:
7694   case ISD::UADDO:
7695   case ISD::SSUBO:
7696   case ISD::USUBO:
7697     return LowerXALUO(Op, DAG);
7698   case ISD::ATOMIC_LOAD:
7699   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7700   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7701   case ISD::SDIVREM:
7702   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7703   case ISD::DYNAMIC_STACKALLOC:
7704     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7705       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7706     llvm_unreachable("Don't know how to custom lower this!");
7707   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7708   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7709   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
7710   case ARMISD::WIN__DBZCHK: return SDValue();
7711   }
7712 }
7713 
7714 /// ReplaceNodeResults - Replace the results of node with an illegal result
7715 /// type with new values built out of custom code.
7716 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7717                                            SmallVectorImpl<SDValue> &Results,
7718                                            SelectionDAG &DAG) const {
7719   SDValue Res;
7720   switch (N->getOpcode()) {
7721   default:
7722     llvm_unreachable("Don't know how to custom expand this!");
7723   case ISD::READ_REGISTER:
7724     ExpandREAD_REGISTER(N, Results, DAG);
7725     break;
7726   case ISD::BITCAST:
7727     Res = ExpandBITCAST(N, DAG);
7728     break;
7729   case ISD::SRL:
7730   case ISD::SRA:
7731     Res = Expand64BitShift(N, DAG, Subtarget);
7732     break;
7733   case ISD::SREM:
7734   case ISD::UREM:
7735     Res = LowerREM(N, DAG);
7736     break;
7737   case ISD::SDIVREM:
7738   case ISD::UDIVREM:
7739     Res = LowerDivRem(SDValue(N, 0), DAG);
7740     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7741     Results.push_back(Res.getValue(0));
7742     Results.push_back(Res.getValue(1));
7743     return;
7744   case ISD::READCYCLECOUNTER:
7745     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7746     return;
7747   case ISD::UDIV:
7748   case ISD::SDIV:
7749     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7750     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7751                              Results);
7752   case ISD::ATOMIC_CMP_SWAP:
7753     ReplaceCMP_SWAP_64Results(N, Results, DAG);
7754     return;
7755   }
7756   if (Res.getNode())
7757     Results.push_back(Res);
7758 }
7759 
7760 //===----------------------------------------------------------------------===//
7761 //                           ARM Scheduler Hooks
7762 //===----------------------------------------------------------------------===//
7763 
7764 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7765 /// registers the function context.
7766 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
7767                                                MachineBasicBlock *MBB,
7768                                                MachineBasicBlock *DispatchBB,
7769                                                int FI) const {
7770   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
7771          "ROPI/RWPI not currently supported with SjLj");
7772   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7773   DebugLoc dl = MI.getDebugLoc();
7774   MachineFunction *MF = MBB->getParent();
7775   MachineRegisterInfo *MRI = &MF->getRegInfo();
7776   MachineConstantPool *MCP = MF->getConstantPool();
7777   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7778   const Function *F = MF->getFunction();
7779 
7780   bool isThumb = Subtarget->isThumb();
7781   bool isThumb2 = Subtarget->isThumb2();
7782 
7783   unsigned PCLabelId = AFI->createPICLabelUId();
7784   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7785   ARMConstantPoolValue *CPV =
7786     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7787   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7788 
7789   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7790                                            : &ARM::GPRRegClass;
7791 
7792   // Grab constant pool and fixed stack memory operands.
7793   MachineMemOperand *CPMMO =
7794       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7795                                MachineMemOperand::MOLoad, 4, 4);
7796 
7797   MachineMemOperand *FIMMOSt =
7798       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7799                                MachineMemOperand::MOStore, 4, 4);
7800 
7801   // Load the address of the dispatch MBB into the jump buffer.
7802   if (isThumb2) {
7803     // Incoming value: jbuf
7804     //   ldr.n  r5, LCPI1_1
7805     //   orr    r5, r5, #1
7806     //   add    r5, pc
7807     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7808     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7809     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7810         .addConstantPoolIndex(CPI)
7811         .addMemOperand(CPMMO)
7812         .add(predOps(ARMCC::AL));
7813     // Set the low bit because of thumb mode.
7814     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7815     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
7816         .addReg(NewVReg1, RegState::Kill)
7817         .addImm(0x01)
7818         .add(predOps(ARMCC::AL))
7819         .add(condCodeOp());
7820     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7821     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
7822       .addReg(NewVReg2, RegState::Kill)
7823       .addImm(PCLabelId);
7824     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
7825         .addReg(NewVReg3, RegState::Kill)
7826         .addFrameIndex(FI)
7827         .addImm(36) // &jbuf[1] :: pc
7828         .addMemOperand(FIMMOSt)
7829         .add(predOps(ARMCC::AL));
7830   } else if (isThumb) {
7831     // Incoming value: jbuf
7832     //   ldr.n  r1, LCPI1_4
7833     //   add    r1, pc
7834     //   mov    r2, #1
7835     //   orrs   r1, r2
7836     //   add    r2, $jbuf, #+4 ; &jbuf[1]
7837     //   str    r1, [r2]
7838     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7839     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
7840         .addConstantPoolIndex(CPI)
7841         .addMemOperand(CPMMO)
7842         .add(predOps(ARMCC::AL));
7843     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7844     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
7845       .addReg(NewVReg1, RegState::Kill)
7846       .addImm(PCLabelId);
7847     // Set the low bit because of thumb mode.
7848     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
7849     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
7850         .addReg(ARM::CPSR, RegState::Define)
7851         .addImm(1)
7852         .add(predOps(ARMCC::AL));
7853     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
7854     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
7855         .addReg(ARM::CPSR, RegState::Define)
7856         .addReg(NewVReg2, RegState::Kill)
7857         .addReg(NewVReg3, RegState::Kill)
7858         .add(predOps(ARMCC::AL));
7859     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
7860     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
7861             .addFrameIndex(FI)
7862             .addImm(36); // &jbuf[1] :: pc
7863     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
7864         .addReg(NewVReg4, RegState::Kill)
7865         .addReg(NewVReg5, RegState::Kill)
7866         .addImm(0)
7867         .addMemOperand(FIMMOSt)
7868         .add(predOps(ARMCC::AL));
7869   } else {
7870     // Incoming value: jbuf
7871     //   ldr  r1, LCPI1_1
7872     //   add  r1, pc, r1
7873     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
7874     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7875     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
7876         .addConstantPoolIndex(CPI)
7877         .addImm(0)
7878         .addMemOperand(CPMMO)
7879         .add(predOps(ARMCC::AL));
7880     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
7881     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
7882         .addReg(NewVReg1, RegState::Kill)
7883         .addImm(PCLabelId)
7884         .add(predOps(ARMCC::AL));
7885     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
7886         .addReg(NewVReg2, RegState::Kill)
7887         .addFrameIndex(FI)
7888         .addImm(36) // &jbuf[1] :: pc
7889         .addMemOperand(FIMMOSt)
7890         .add(predOps(ARMCC::AL));
7891   }
7892 }
7893 
7894 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
7895                                               MachineBasicBlock *MBB) const {
7896   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7897   DebugLoc dl = MI.getDebugLoc();
7898   MachineFunction *MF = MBB->getParent();
7899   MachineRegisterInfo *MRI = &MF->getRegInfo();
7900   MachineFrameInfo &MFI = MF->getFrameInfo();
7901   int FI = MFI.getFunctionContextIndex();
7902 
7903   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
7904                                                         : &ARM::GPRnopcRegClass;
7905 
7906   // Get a mapping of the call site numbers to all of the landing pads they're
7907   // associated with.
7908   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
7909   unsigned MaxCSNum = 0;
7910   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
7911        ++BB) {
7912     if (!BB->isEHPad()) continue;
7913 
7914     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
7915     // pad.
7916     for (MachineBasicBlock::iterator
7917            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
7918       if (!II->isEHLabel()) continue;
7919 
7920       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
7921       if (!MF->hasCallSiteLandingPad(Sym)) continue;
7922 
7923       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
7924       for (SmallVectorImpl<unsigned>::iterator
7925              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
7926            CSI != CSE; ++CSI) {
7927         CallSiteNumToLPad[*CSI].push_back(&*BB);
7928         MaxCSNum = std::max(MaxCSNum, *CSI);
7929       }
7930       break;
7931     }
7932   }
7933 
7934   // Get an ordered list of the machine basic blocks for the jump table.
7935   std::vector<MachineBasicBlock*> LPadList;
7936   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
7937   LPadList.reserve(CallSiteNumToLPad.size());
7938   for (unsigned I = 1; I <= MaxCSNum; ++I) {
7939     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
7940     for (SmallVectorImpl<MachineBasicBlock*>::iterator
7941            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
7942       LPadList.push_back(*II);
7943       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
7944     }
7945   }
7946 
7947   assert(!LPadList.empty() &&
7948          "No landing pad destinations for the dispatch jump table!");
7949 
7950   // Create the jump table and associated information.
7951   MachineJumpTableInfo *JTI =
7952     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
7953   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
7954 
7955   // Create the MBBs for the dispatch code.
7956 
7957   // Shove the dispatch's address into the return slot in the function context.
7958   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
7959   DispatchBB->setIsEHPad();
7960 
7961   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
7962   unsigned trap_opcode;
7963   if (Subtarget->isThumb())
7964     trap_opcode = ARM::tTRAP;
7965   else
7966     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
7967 
7968   BuildMI(TrapBB, dl, TII->get(trap_opcode));
7969   DispatchBB->addSuccessor(TrapBB);
7970 
7971   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
7972   DispatchBB->addSuccessor(DispContBB);
7973 
7974   // Insert and MBBs.
7975   MF->insert(MF->end(), DispatchBB);
7976   MF->insert(MF->end(), DispContBB);
7977   MF->insert(MF->end(), TrapBB);
7978 
7979   // Insert code into the entry block that creates and registers the function
7980   // context.
7981   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
7982 
7983   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
7984       MachinePointerInfo::getFixedStack(*MF, FI),
7985       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
7986 
7987   MachineInstrBuilder MIB;
7988   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
7989 
7990   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
7991   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
7992 
7993   // Add a register mask with no preserved registers.  This results in all
7994   // registers being marked as clobbered. This can't work if the dispatch block
7995   // is in a Thumb1 function and is linked with ARM code which uses the FP
7996   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
7997   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
7998 
7999   bool IsPositionIndependent = isPositionIndependent();
8000   unsigned NumLPads = LPadList.size();
8001   if (Subtarget->isThumb2()) {
8002     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8003     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8004         .addFrameIndex(FI)
8005         .addImm(4)
8006         .addMemOperand(FIMMOLd)
8007         .add(predOps(ARMCC::AL));
8008 
8009     if (NumLPads < 256) {
8010       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8011           .addReg(NewVReg1)
8012           .addImm(LPadList.size())
8013           .add(predOps(ARMCC::AL));
8014     } else {
8015       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8016       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8017           .addImm(NumLPads & 0xFFFF)
8018           .add(predOps(ARMCC::AL));
8019 
8020       unsigned VReg2 = VReg1;
8021       if ((NumLPads & 0xFFFF0000) != 0) {
8022         VReg2 = MRI->createVirtualRegister(TRC);
8023         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8024             .addReg(VReg1)
8025             .addImm(NumLPads >> 16)
8026             .add(predOps(ARMCC::AL));
8027       }
8028 
8029       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8030           .addReg(NewVReg1)
8031           .addReg(VReg2)
8032           .add(predOps(ARMCC::AL));
8033     }
8034 
8035     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8036       .addMBB(TrapBB)
8037       .addImm(ARMCC::HI)
8038       .addReg(ARM::CPSR);
8039 
8040     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8041     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8042         .addJumpTableIndex(MJTI)
8043         .add(predOps(ARMCC::AL));
8044 
8045     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8046     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8047         .addReg(NewVReg3, RegState::Kill)
8048         .addReg(NewVReg1)
8049         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8050         .add(predOps(ARMCC::AL))
8051         .add(condCodeOp());
8052 
8053     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8054       .addReg(NewVReg4, RegState::Kill)
8055       .addReg(NewVReg1)
8056       .addJumpTableIndex(MJTI);
8057   } else if (Subtarget->isThumb()) {
8058     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8059     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8060         .addFrameIndex(FI)
8061         .addImm(1)
8062         .addMemOperand(FIMMOLd)
8063         .add(predOps(ARMCC::AL));
8064 
8065     if (NumLPads < 256) {
8066       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8067           .addReg(NewVReg1)
8068           .addImm(NumLPads)
8069           .add(predOps(ARMCC::AL));
8070     } else {
8071       MachineConstantPool *ConstantPool = MF->getConstantPool();
8072       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8073       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8074 
8075       // MachineConstantPool wants an explicit alignment.
8076       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8077       if (Align == 0)
8078         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8079       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8080 
8081       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8082       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8083           .addReg(VReg1, RegState::Define)
8084           .addConstantPoolIndex(Idx)
8085           .add(predOps(ARMCC::AL));
8086       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8087           .addReg(NewVReg1)
8088           .addReg(VReg1)
8089           .add(predOps(ARMCC::AL));
8090     }
8091 
8092     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8093       .addMBB(TrapBB)
8094       .addImm(ARMCC::HI)
8095       .addReg(ARM::CPSR);
8096 
8097     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8098     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8099         .addReg(ARM::CPSR, RegState::Define)
8100         .addReg(NewVReg1)
8101         .addImm(2)
8102         .add(predOps(ARMCC::AL));
8103 
8104     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8105     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8106         .addJumpTableIndex(MJTI)
8107         .add(predOps(ARMCC::AL));
8108 
8109     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8110     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8111         .addReg(ARM::CPSR, RegState::Define)
8112         .addReg(NewVReg2, RegState::Kill)
8113         .addReg(NewVReg3)
8114         .add(predOps(ARMCC::AL));
8115 
8116     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8117         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8118 
8119     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8120     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8121         .addReg(NewVReg4, RegState::Kill)
8122         .addImm(0)
8123         .addMemOperand(JTMMOLd)
8124         .add(predOps(ARMCC::AL));
8125 
8126     unsigned NewVReg6 = NewVReg5;
8127     if (IsPositionIndependent) {
8128       NewVReg6 = MRI->createVirtualRegister(TRC);
8129       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8130           .addReg(ARM::CPSR, RegState::Define)
8131           .addReg(NewVReg5, RegState::Kill)
8132           .addReg(NewVReg3)
8133           .add(predOps(ARMCC::AL));
8134     }
8135 
8136     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8137       .addReg(NewVReg6, RegState::Kill)
8138       .addJumpTableIndex(MJTI);
8139   } else {
8140     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8141     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8142         .addFrameIndex(FI)
8143         .addImm(4)
8144         .addMemOperand(FIMMOLd)
8145         .add(predOps(ARMCC::AL));
8146 
8147     if (NumLPads < 256) {
8148       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8149           .addReg(NewVReg1)
8150           .addImm(NumLPads)
8151           .add(predOps(ARMCC::AL));
8152     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8153       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8154       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8155           .addImm(NumLPads & 0xFFFF)
8156           .add(predOps(ARMCC::AL));
8157 
8158       unsigned VReg2 = VReg1;
8159       if ((NumLPads & 0xFFFF0000) != 0) {
8160         VReg2 = MRI->createVirtualRegister(TRC);
8161         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8162             .addReg(VReg1)
8163             .addImm(NumLPads >> 16)
8164             .add(predOps(ARMCC::AL));
8165       }
8166 
8167       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8168           .addReg(NewVReg1)
8169           .addReg(VReg2)
8170           .add(predOps(ARMCC::AL));
8171     } else {
8172       MachineConstantPool *ConstantPool = MF->getConstantPool();
8173       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8174       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8175 
8176       // MachineConstantPool wants an explicit alignment.
8177       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8178       if (Align == 0)
8179         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8180       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8181 
8182       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8183       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8184           .addReg(VReg1, RegState::Define)
8185           .addConstantPoolIndex(Idx)
8186           .addImm(0)
8187           .add(predOps(ARMCC::AL));
8188       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8189           .addReg(NewVReg1)
8190           .addReg(VReg1, RegState::Kill)
8191           .add(predOps(ARMCC::AL));
8192     }
8193 
8194     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8195       .addMBB(TrapBB)
8196       .addImm(ARMCC::HI)
8197       .addReg(ARM::CPSR);
8198 
8199     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8200     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8201         .addReg(NewVReg1)
8202         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8203         .add(predOps(ARMCC::AL))
8204         .add(condCodeOp());
8205     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8206     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8207         .addJumpTableIndex(MJTI)
8208         .add(predOps(ARMCC::AL));
8209 
8210     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8211         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8212     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8213     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8214         .addReg(NewVReg3, RegState::Kill)
8215         .addReg(NewVReg4)
8216         .addImm(0)
8217         .addMemOperand(JTMMOLd)
8218         .add(predOps(ARMCC::AL));
8219 
8220     if (IsPositionIndependent) {
8221       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8222         .addReg(NewVReg5, RegState::Kill)
8223         .addReg(NewVReg4)
8224         .addJumpTableIndex(MJTI);
8225     } else {
8226       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8227         .addReg(NewVReg5, RegState::Kill)
8228         .addJumpTableIndex(MJTI);
8229     }
8230   }
8231 
8232   // Add the jump table entries as successors to the MBB.
8233   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8234   for (std::vector<MachineBasicBlock*>::iterator
8235          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8236     MachineBasicBlock *CurMBB = *I;
8237     if (SeenMBBs.insert(CurMBB).second)
8238       DispContBB->addSuccessor(CurMBB);
8239   }
8240 
8241   // N.B. the order the invoke BBs are processed in doesn't matter here.
8242   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8243   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8244   for (MachineBasicBlock *BB : InvokeBBs) {
8245 
8246     // Remove the landing pad successor from the invoke block and replace it
8247     // with the new dispatch block.
8248     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8249                                                   BB->succ_end());
8250     while (!Successors.empty()) {
8251       MachineBasicBlock *SMBB = Successors.pop_back_val();
8252       if (SMBB->isEHPad()) {
8253         BB->removeSuccessor(SMBB);
8254         MBBLPads.push_back(SMBB);
8255       }
8256     }
8257 
8258     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8259     BB->normalizeSuccProbs();
8260 
8261     // Find the invoke call and mark all of the callee-saved registers as
8262     // 'implicit defined' so that they're spilled. This prevents code from
8263     // moving instructions to before the EH block, where they will never be
8264     // executed.
8265     for (MachineBasicBlock::reverse_iterator
8266            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8267       if (!II->isCall()) continue;
8268 
8269       DenseMap<unsigned, bool> DefRegs;
8270       for (MachineInstr::mop_iterator
8271              OI = II->operands_begin(), OE = II->operands_end();
8272            OI != OE; ++OI) {
8273         if (!OI->isReg()) continue;
8274         DefRegs[OI->getReg()] = true;
8275       }
8276 
8277       MachineInstrBuilder MIB(*MF, &*II);
8278 
8279       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8280         unsigned Reg = SavedRegs[i];
8281         if (Subtarget->isThumb2() &&
8282             !ARM::tGPRRegClass.contains(Reg) &&
8283             !ARM::hGPRRegClass.contains(Reg))
8284           continue;
8285         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8286           continue;
8287         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8288           continue;
8289         if (!DefRegs[Reg])
8290           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8291       }
8292 
8293       break;
8294     }
8295   }
8296 
8297   // Mark all former landing pads as non-landing pads. The dispatch is the only
8298   // landing pad now.
8299   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8300          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8301     (*I)->setIsEHPad(false);
8302 
8303   // The instruction is gone now.
8304   MI.eraseFromParent();
8305 }
8306 
8307 static
8308 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8309   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8310        E = MBB->succ_end(); I != E; ++I)
8311     if (*I != Succ)
8312       return *I;
8313   llvm_unreachable("Expecting a BB with two successors!");
8314 }
8315 
8316 /// Return the load opcode for a given load size. If load size >= 8,
8317 /// neon opcode will be returned.
8318 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8319   if (LdSize >= 8)
8320     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8321                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8322   if (IsThumb1)
8323     return LdSize == 4 ? ARM::tLDRi
8324                        : LdSize == 2 ? ARM::tLDRHi
8325                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8326   if (IsThumb2)
8327     return LdSize == 4 ? ARM::t2LDR_POST
8328                        : LdSize == 2 ? ARM::t2LDRH_POST
8329                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8330   return LdSize == 4 ? ARM::LDR_POST_IMM
8331                      : LdSize == 2 ? ARM::LDRH_POST
8332                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8333 }
8334 
8335 /// Return the store opcode for a given store size. If store size >= 8,
8336 /// neon opcode will be returned.
8337 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8338   if (StSize >= 8)
8339     return StSize == 16 ? ARM::VST1q32wb_fixed
8340                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8341   if (IsThumb1)
8342     return StSize == 4 ? ARM::tSTRi
8343                        : StSize == 2 ? ARM::tSTRHi
8344                                      : StSize == 1 ? ARM::tSTRBi : 0;
8345   if (IsThumb2)
8346     return StSize == 4 ? ARM::t2STR_POST
8347                        : StSize == 2 ? ARM::t2STRH_POST
8348                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8349   return StSize == 4 ? ARM::STR_POST_IMM
8350                      : StSize == 2 ? ARM::STRH_POST
8351                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8352 }
8353 
8354 /// Emit a post-increment load operation with given size. The instructions
8355 /// will be added to BB at Pos.
8356 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8357                        const TargetInstrInfo *TII, const DebugLoc &dl,
8358                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8359                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8360   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8361   assert(LdOpc != 0 && "Should have a load opcode");
8362   if (LdSize >= 8) {
8363     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8364         .addReg(AddrOut, RegState::Define)
8365         .addReg(AddrIn)
8366         .addImm(0)
8367         .add(predOps(ARMCC::AL));
8368   } else if (IsThumb1) {
8369     // load + update AddrIn
8370     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8371         .addReg(AddrIn)
8372         .addImm(0)
8373         .add(predOps(ARMCC::AL));
8374     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8375         .add(t1CondCodeOp())
8376         .addReg(AddrIn)
8377         .addImm(LdSize)
8378         .add(predOps(ARMCC::AL));
8379   } else if (IsThumb2) {
8380     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8381         .addReg(AddrOut, RegState::Define)
8382         .addReg(AddrIn)
8383         .addImm(LdSize)
8384         .add(predOps(ARMCC::AL));
8385   } else { // arm
8386     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8387         .addReg(AddrOut, RegState::Define)
8388         .addReg(AddrIn)
8389         .addReg(0)
8390         .addImm(LdSize)
8391         .add(predOps(ARMCC::AL));
8392   }
8393 }
8394 
8395 /// Emit a post-increment store operation with given size. The instructions
8396 /// will be added to BB at Pos.
8397 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8398                        const TargetInstrInfo *TII, const DebugLoc &dl,
8399                        unsigned StSize, unsigned Data, unsigned AddrIn,
8400                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8401   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8402   assert(StOpc != 0 && "Should have a store opcode");
8403   if (StSize >= 8) {
8404     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8405         .addReg(AddrIn)
8406         .addImm(0)
8407         .addReg(Data)
8408         .add(predOps(ARMCC::AL));
8409   } else if (IsThumb1) {
8410     // store + update AddrIn
8411     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8412         .addReg(Data)
8413         .addReg(AddrIn)
8414         .addImm(0)
8415         .add(predOps(ARMCC::AL));
8416     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8417         .add(t1CondCodeOp())
8418         .addReg(AddrIn)
8419         .addImm(StSize)
8420         .add(predOps(ARMCC::AL));
8421   } else if (IsThumb2) {
8422     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8423         .addReg(Data)
8424         .addReg(AddrIn)
8425         .addImm(StSize)
8426         .add(predOps(ARMCC::AL));
8427   } else { // arm
8428     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8429         .addReg(Data)
8430         .addReg(AddrIn)
8431         .addReg(0)
8432         .addImm(StSize)
8433         .add(predOps(ARMCC::AL));
8434   }
8435 }
8436 
8437 MachineBasicBlock *
8438 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8439                                    MachineBasicBlock *BB) const {
8440   // This pseudo instruction has 3 operands: dst, src, size
8441   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8442   // Otherwise, we will generate unrolled scalar copies.
8443   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8444   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8445   MachineFunction::iterator It = ++BB->getIterator();
8446 
8447   unsigned dest = MI.getOperand(0).getReg();
8448   unsigned src = MI.getOperand(1).getReg();
8449   unsigned SizeVal = MI.getOperand(2).getImm();
8450   unsigned Align = MI.getOperand(3).getImm();
8451   DebugLoc dl = MI.getDebugLoc();
8452 
8453   MachineFunction *MF = BB->getParent();
8454   MachineRegisterInfo &MRI = MF->getRegInfo();
8455   unsigned UnitSize = 0;
8456   const TargetRegisterClass *TRC = nullptr;
8457   const TargetRegisterClass *VecTRC = nullptr;
8458 
8459   bool IsThumb1 = Subtarget->isThumb1Only();
8460   bool IsThumb2 = Subtarget->isThumb2();
8461   bool IsThumb = Subtarget->isThumb();
8462 
8463   if (Align & 1) {
8464     UnitSize = 1;
8465   } else if (Align & 2) {
8466     UnitSize = 2;
8467   } else {
8468     // Check whether we can use NEON instructions.
8469     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
8470         Subtarget->hasNEON()) {
8471       if ((Align % 16 == 0) && SizeVal >= 16)
8472         UnitSize = 16;
8473       else if ((Align % 8 == 0) && SizeVal >= 8)
8474         UnitSize = 8;
8475     }
8476     // Can't use NEON instructions.
8477     if (UnitSize == 0)
8478       UnitSize = 4;
8479   }
8480 
8481   // Select the correct opcode and register class for unit size load/store
8482   bool IsNeon = UnitSize >= 8;
8483   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8484   if (IsNeon)
8485     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8486                             : UnitSize == 8 ? &ARM::DPRRegClass
8487                                             : nullptr;
8488 
8489   unsigned BytesLeft = SizeVal % UnitSize;
8490   unsigned LoopSize = SizeVal - BytesLeft;
8491 
8492   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8493     // Use LDR and STR to copy.
8494     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8495     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8496     unsigned srcIn = src;
8497     unsigned destIn = dest;
8498     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8499       unsigned srcOut = MRI.createVirtualRegister(TRC);
8500       unsigned destOut = MRI.createVirtualRegister(TRC);
8501       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8502       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8503                  IsThumb1, IsThumb2);
8504       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8505                  IsThumb1, IsThumb2);
8506       srcIn = srcOut;
8507       destIn = destOut;
8508     }
8509 
8510     // Handle the leftover bytes with LDRB and STRB.
8511     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8512     // [destOut] = STRB_POST(scratch, destIn, 1)
8513     for (unsigned i = 0; i < BytesLeft; i++) {
8514       unsigned srcOut = MRI.createVirtualRegister(TRC);
8515       unsigned destOut = MRI.createVirtualRegister(TRC);
8516       unsigned scratch = MRI.createVirtualRegister(TRC);
8517       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8518                  IsThumb1, IsThumb2);
8519       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8520                  IsThumb1, IsThumb2);
8521       srcIn = srcOut;
8522       destIn = destOut;
8523     }
8524     MI.eraseFromParent(); // The instruction is gone now.
8525     return BB;
8526   }
8527 
8528   // Expand the pseudo op to a loop.
8529   // thisMBB:
8530   //   ...
8531   //   movw varEnd, # --> with thumb2
8532   //   movt varEnd, #
8533   //   ldrcp varEnd, idx --> without thumb2
8534   //   fallthrough --> loopMBB
8535   // loopMBB:
8536   //   PHI varPhi, varEnd, varLoop
8537   //   PHI srcPhi, src, srcLoop
8538   //   PHI destPhi, dst, destLoop
8539   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8540   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8541   //   subs varLoop, varPhi, #UnitSize
8542   //   bne loopMBB
8543   //   fallthrough --> exitMBB
8544   // exitMBB:
8545   //   epilogue to handle left-over bytes
8546   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8547   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8548   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8549   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8550   MF->insert(It, loopMBB);
8551   MF->insert(It, exitMBB);
8552 
8553   // Transfer the remainder of BB and its successor edges to exitMBB.
8554   exitMBB->splice(exitMBB->begin(), BB,
8555                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8556   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8557 
8558   // Load an immediate to varEnd.
8559   unsigned varEnd = MRI.createVirtualRegister(TRC);
8560   if (Subtarget->useMovt(*MF)) {
8561     unsigned Vtmp = varEnd;
8562     if ((LoopSize & 0xFFFF0000) != 0)
8563       Vtmp = MRI.createVirtualRegister(TRC);
8564     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8565         .addImm(LoopSize & 0xFFFF)
8566         .add(predOps(ARMCC::AL));
8567 
8568     if ((LoopSize & 0xFFFF0000) != 0)
8569       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8570           .addReg(Vtmp)
8571           .addImm(LoopSize >> 16)
8572           .add(predOps(ARMCC::AL));
8573   } else {
8574     MachineConstantPool *ConstantPool = MF->getConstantPool();
8575     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8576     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8577 
8578     // MachineConstantPool wants an explicit alignment.
8579     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8580     if (Align == 0)
8581       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8582     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8583 
8584     if (IsThumb)
8585       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
8586           .addReg(varEnd, RegState::Define)
8587           .addConstantPoolIndex(Idx)
8588           .add(predOps(ARMCC::AL));
8589     else
8590       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
8591           .addReg(varEnd, RegState::Define)
8592           .addConstantPoolIndex(Idx)
8593           .addImm(0)
8594           .add(predOps(ARMCC::AL));
8595   }
8596   BB->addSuccessor(loopMBB);
8597 
8598   // Generate the loop body:
8599   //   varPhi = PHI(varLoop, varEnd)
8600   //   srcPhi = PHI(srcLoop, src)
8601   //   destPhi = PHI(destLoop, dst)
8602   MachineBasicBlock *entryBB = BB;
8603   BB = loopMBB;
8604   unsigned varLoop = MRI.createVirtualRegister(TRC);
8605   unsigned varPhi = MRI.createVirtualRegister(TRC);
8606   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8607   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8608   unsigned destLoop = MRI.createVirtualRegister(TRC);
8609   unsigned destPhi = MRI.createVirtualRegister(TRC);
8610 
8611   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8612     .addReg(varLoop).addMBB(loopMBB)
8613     .addReg(varEnd).addMBB(entryBB);
8614   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8615     .addReg(srcLoop).addMBB(loopMBB)
8616     .addReg(src).addMBB(entryBB);
8617   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8618     .addReg(destLoop).addMBB(loopMBB)
8619     .addReg(dest).addMBB(entryBB);
8620 
8621   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8622   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8623   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8624   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8625              IsThumb1, IsThumb2);
8626   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8627              IsThumb1, IsThumb2);
8628 
8629   // Decrement loop variable by UnitSize.
8630   if (IsThumb1) {
8631     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
8632         .add(t1CondCodeOp())
8633         .addReg(varPhi)
8634         .addImm(UnitSize)
8635         .add(predOps(ARMCC::AL));
8636   } else {
8637     MachineInstrBuilder MIB =
8638         BuildMI(*BB, BB->end(), dl,
8639                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8640     MIB.addReg(varPhi)
8641         .addImm(UnitSize)
8642         .add(predOps(ARMCC::AL))
8643         .add(condCodeOp());
8644     MIB->getOperand(5).setReg(ARM::CPSR);
8645     MIB->getOperand(5).setIsDef(true);
8646   }
8647   BuildMI(*BB, BB->end(), dl,
8648           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8649       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8650 
8651   // loopMBB can loop back to loopMBB or fall through to exitMBB.
8652   BB->addSuccessor(loopMBB);
8653   BB->addSuccessor(exitMBB);
8654 
8655   // Add epilogue to handle BytesLeft.
8656   BB = exitMBB;
8657   auto StartOfExit = exitMBB->begin();
8658 
8659   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8660   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8661   unsigned srcIn = srcLoop;
8662   unsigned destIn = destLoop;
8663   for (unsigned i = 0; i < BytesLeft; i++) {
8664     unsigned srcOut = MRI.createVirtualRegister(TRC);
8665     unsigned destOut = MRI.createVirtualRegister(TRC);
8666     unsigned scratch = MRI.createVirtualRegister(TRC);
8667     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8668                IsThumb1, IsThumb2);
8669     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8670                IsThumb1, IsThumb2);
8671     srcIn = srcOut;
8672     destIn = destOut;
8673   }
8674 
8675   MI.eraseFromParent(); // The instruction is gone now.
8676   return BB;
8677 }
8678 
8679 MachineBasicBlock *
8680 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8681                                        MachineBasicBlock *MBB) const {
8682   const TargetMachine &TM = getTargetMachine();
8683   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8684   DebugLoc DL = MI.getDebugLoc();
8685 
8686   assert(Subtarget->isTargetWindows() &&
8687          "__chkstk is only supported on Windows");
8688   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8689 
8690   // __chkstk takes the number of words to allocate on the stack in R4, and
8691   // returns the stack adjustment in number of bytes in R4.  This will not
8692   // clober any other registers (other than the obvious lr).
8693   //
8694   // Although, technically, IP should be considered a register which may be
8695   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
8696   // thumb-2 environment, so there is no interworking required.  As a result, we
8697   // do not expect a veneer to be emitted by the linker, clobbering IP.
8698   //
8699   // Each module receives its own copy of __chkstk, so no import thunk is
8700   // required, again, ensuring that IP is not clobbered.
8701   //
8702   // Finally, although some linkers may theoretically provide a trampoline for
8703   // out of range calls (which is quite common due to a 32M range limitation of
8704   // branches for Thumb), we can generate the long-call version via
8705   // -mcmodel=large, alleviating the need for the trampoline which may clobber
8706   // IP.
8707 
8708   switch (TM.getCodeModel()) {
8709   case CodeModel::Small:
8710   case CodeModel::Medium:
8711   case CodeModel::Default:
8712   case CodeModel::Kernel:
8713     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8714         .add(predOps(ARMCC::AL))
8715         .addExternalSymbol("__chkstk")
8716         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8717         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8718         .addReg(ARM::R12,
8719                 RegState::Implicit | RegState::Define | RegState::Dead);
8720     break;
8721   case CodeModel::Large:
8722   case CodeModel::JITDefault: {
8723     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8724     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8725 
8726     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8727       .addExternalSymbol("__chkstk");
8728     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8729         .add(predOps(ARMCC::AL))
8730         .addReg(Reg, RegState::Kill)
8731         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8732         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8733         .addReg(ARM::R12,
8734                 RegState::Implicit | RegState::Define | RegState::Dead);
8735     break;
8736   }
8737   }
8738 
8739   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
8740       .addReg(ARM::SP, RegState::Kill)
8741       .addReg(ARM::R4, RegState::Kill)
8742       .setMIFlags(MachineInstr::FrameSetup)
8743       .add(predOps(ARMCC::AL))
8744       .add(condCodeOp());
8745 
8746   MI.eraseFromParent();
8747   return MBB;
8748 }
8749 
8750 MachineBasicBlock *
8751 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
8752                                        MachineBasicBlock *MBB) const {
8753   DebugLoc DL = MI.getDebugLoc();
8754   MachineFunction *MF = MBB->getParent();
8755   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8756 
8757   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8758   MF->insert(++MBB->getIterator(), ContBB);
8759   ContBB->splice(ContBB->begin(), MBB,
8760                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8761   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
8762   MBB->addSuccessor(ContBB);
8763 
8764   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8765   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
8766   MF->push_back(TrapBB);
8767   MBB->addSuccessor(TrapBB);
8768 
8769   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
8770       .addReg(MI.getOperand(0).getReg())
8771       .addImm(0)
8772       .add(predOps(ARMCC::AL));
8773   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
8774       .addMBB(TrapBB)
8775       .addImm(ARMCC::EQ)
8776       .addReg(ARM::CPSR);
8777 
8778   MI.eraseFromParent();
8779   return ContBB;
8780 }
8781 
8782 MachineBasicBlock *
8783 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8784                                                MachineBasicBlock *BB) const {
8785   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8786   DebugLoc dl = MI.getDebugLoc();
8787   bool isThumb2 = Subtarget->isThumb2();
8788   switch (MI.getOpcode()) {
8789   default: {
8790     MI.print(errs());
8791     llvm_unreachable("Unexpected instr type to insert");
8792   }
8793 
8794   // Thumb1 post-indexed loads are really just single-register LDMs.
8795   case ARM::tLDR_postidx: {
8796     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
8797         .add(MI.getOperand(1))  // Rn_wb
8798         .add(MI.getOperand(2))  // Rn
8799         .add(MI.getOperand(3))  // PredImm
8800         .add(MI.getOperand(4))  // PredReg
8801         .add(MI.getOperand(0)); // Rt
8802     MI.eraseFromParent();
8803     return BB;
8804   }
8805 
8806   // The Thumb2 pre-indexed stores have the same MI operands, they just
8807   // define them differently in the .td files from the isel patterns, so
8808   // they need pseudos.
8809   case ARM::t2STR_preidx:
8810     MI.setDesc(TII->get(ARM::t2STR_PRE));
8811     return BB;
8812   case ARM::t2STRB_preidx:
8813     MI.setDesc(TII->get(ARM::t2STRB_PRE));
8814     return BB;
8815   case ARM::t2STRH_preidx:
8816     MI.setDesc(TII->get(ARM::t2STRH_PRE));
8817     return BB;
8818 
8819   case ARM::STRi_preidx:
8820   case ARM::STRBi_preidx: {
8821     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
8822                                                          : ARM::STRB_PRE_IMM;
8823     // Decode the offset.
8824     unsigned Offset = MI.getOperand(4).getImm();
8825     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
8826     Offset = ARM_AM::getAM2Offset(Offset);
8827     if (isSub)
8828       Offset = -Offset;
8829 
8830     MachineMemOperand *MMO = *MI.memoperands_begin();
8831     BuildMI(*BB, MI, dl, TII->get(NewOpc))
8832         .add(MI.getOperand(0)) // Rn_wb
8833         .add(MI.getOperand(1)) // Rt
8834         .add(MI.getOperand(2)) // Rn
8835         .addImm(Offset)        // offset (skip GPR==zero_reg)
8836         .add(MI.getOperand(5)) // pred
8837         .add(MI.getOperand(6))
8838         .addMemOperand(MMO);
8839     MI.eraseFromParent();
8840     return BB;
8841   }
8842   case ARM::STRr_preidx:
8843   case ARM::STRBr_preidx:
8844   case ARM::STRH_preidx: {
8845     unsigned NewOpc;
8846     switch (MI.getOpcode()) {
8847     default: llvm_unreachable("unexpected opcode!");
8848     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
8849     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
8850     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
8851     }
8852     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
8853     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
8854       MIB.add(MI.getOperand(i));
8855     MI.eraseFromParent();
8856     return BB;
8857   }
8858 
8859   case ARM::tMOVCCr_pseudo: {
8860     // To "insert" a SELECT_CC instruction, we actually have to insert the
8861     // diamond control-flow pattern.  The incoming instruction knows the
8862     // destination vreg to set, the condition code register to branch on, the
8863     // true/false values to select between, and a branch opcode to use.
8864     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8865     MachineFunction::iterator It = ++BB->getIterator();
8866 
8867     //  thisMBB:
8868     //  ...
8869     //   TrueVal = ...
8870     //   cmpTY ccX, r1, r2
8871     //   bCC copy1MBB
8872     //   fallthrough --> copy0MBB
8873     MachineBasicBlock *thisMBB  = BB;
8874     MachineFunction *F = BB->getParent();
8875     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
8876     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
8877     F->insert(It, copy0MBB);
8878     F->insert(It, sinkMBB);
8879 
8880     // Transfer the remainder of BB and its successor edges to sinkMBB.
8881     sinkMBB->splice(sinkMBB->begin(), BB,
8882                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
8883     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
8884 
8885     BB->addSuccessor(copy0MBB);
8886     BB->addSuccessor(sinkMBB);
8887 
8888     BuildMI(BB, dl, TII->get(ARM::tBcc))
8889         .addMBB(sinkMBB)
8890         .addImm(MI.getOperand(3).getImm())
8891         .addReg(MI.getOperand(4).getReg());
8892 
8893     //  copy0MBB:
8894     //   %FalseValue = ...
8895     //   # fallthrough to sinkMBB
8896     BB = copy0MBB;
8897 
8898     // Update machine-CFG edges
8899     BB->addSuccessor(sinkMBB);
8900 
8901     //  sinkMBB:
8902     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
8903     //  ...
8904     BB = sinkMBB;
8905     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
8906         .addReg(MI.getOperand(1).getReg())
8907         .addMBB(copy0MBB)
8908         .addReg(MI.getOperand(2).getReg())
8909         .addMBB(thisMBB);
8910 
8911     MI.eraseFromParent(); // The pseudo instruction is gone now.
8912     return BB;
8913   }
8914 
8915   case ARM::BCCi64:
8916   case ARM::BCCZi64: {
8917     // If there is an unconditional branch to the other successor, remove it.
8918     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
8919 
8920     // Compare both parts that make up the double comparison separately for
8921     // equality.
8922     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
8923 
8924     unsigned LHS1 = MI.getOperand(1).getReg();
8925     unsigned LHS2 = MI.getOperand(2).getReg();
8926     if (RHSisZero) {
8927       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8928           .addReg(LHS1)
8929           .addImm(0)
8930           .add(predOps(ARMCC::AL));
8931       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
8932         .addReg(LHS2).addImm(0)
8933         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8934     } else {
8935       unsigned RHS1 = MI.getOperand(3).getReg();
8936       unsigned RHS2 = MI.getOperand(4).getReg();
8937       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8938           .addReg(LHS1)
8939           .addReg(RHS1)
8940           .add(predOps(ARMCC::AL));
8941       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
8942         .addReg(LHS2).addReg(RHS2)
8943         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
8944     }
8945 
8946     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
8947     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
8948     if (MI.getOperand(0).getImm() == ARMCC::NE)
8949       std::swap(destMBB, exitMBB);
8950 
8951     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
8952       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
8953     if (isThumb2)
8954       BuildMI(BB, dl, TII->get(ARM::t2B))
8955           .addMBB(exitMBB)
8956           .add(predOps(ARMCC::AL));
8957     else
8958       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
8959 
8960     MI.eraseFromParent(); // The pseudo instruction is gone now.
8961     return BB;
8962   }
8963 
8964   case ARM::Int_eh_sjlj_setjmp:
8965   case ARM::Int_eh_sjlj_setjmp_nofp:
8966   case ARM::tInt_eh_sjlj_setjmp:
8967   case ARM::t2Int_eh_sjlj_setjmp:
8968   case ARM::t2Int_eh_sjlj_setjmp_nofp:
8969     return BB;
8970 
8971   case ARM::Int_eh_sjlj_setup_dispatch:
8972     EmitSjLjDispatchBlock(MI, BB);
8973     return BB;
8974 
8975   case ARM::ABS:
8976   case ARM::t2ABS: {
8977     // To insert an ABS instruction, we have to insert the
8978     // diamond control-flow pattern.  The incoming instruction knows the
8979     // source vreg to test against 0, the destination vreg to set,
8980     // the condition code register to branch on, the
8981     // true/false values to select between, and a branch opcode to use.
8982     // It transforms
8983     //     V1 = ABS V0
8984     // into
8985     //     V2 = MOVS V0
8986     //     BCC                      (branch to SinkBB if V0 >= 0)
8987     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
8988     //     SinkBB: V1 = PHI(V2, V3)
8989     const BasicBlock *LLVM_BB = BB->getBasicBlock();
8990     MachineFunction::iterator BBI = ++BB->getIterator();
8991     MachineFunction *Fn = BB->getParent();
8992     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
8993     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
8994     Fn->insert(BBI, RSBBB);
8995     Fn->insert(BBI, SinkBB);
8996 
8997     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
8998     unsigned int ABSDstReg = MI.getOperand(0).getReg();
8999     bool ABSSrcKIll = MI.getOperand(1).isKill();
9000     bool isThumb2 = Subtarget->isThumb2();
9001     MachineRegisterInfo &MRI = Fn->getRegInfo();
9002     // In Thumb mode S must not be specified if source register is the SP or
9003     // PC and if destination register is the SP, so restrict register class
9004     unsigned NewRsbDstReg =
9005       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9006 
9007     // Transfer the remainder of BB and its successor edges to sinkMBB.
9008     SinkBB->splice(SinkBB->begin(), BB,
9009                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9010     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9011 
9012     BB->addSuccessor(RSBBB);
9013     BB->addSuccessor(SinkBB);
9014 
9015     // fall through to SinkMBB
9016     RSBBB->addSuccessor(SinkBB);
9017 
9018     // insert a cmp at the end of BB
9019     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9020         .addReg(ABSSrcReg)
9021         .addImm(0)
9022         .add(predOps(ARMCC::AL));
9023 
9024     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9025     BuildMI(BB, dl,
9026       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9027       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9028 
9029     // insert rsbri in RSBBB
9030     // Note: BCC and rsbri will be converted into predicated rsbmi
9031     // by if-conversion pass
9032     BuildMI(*RSBBB, RSBBB->begin(), dl,
9033             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9034         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9035         .addImm(0)
9036         .add(predOps(ARMCC::AL))
9037         .add(condCodeOp());
9038 
9039     // insert PHI in SinkBB,
9040     // reuse ABSDstReg to not change uses of ABS instruction
9041     BuildMI(*SinkBB, SinkBB->begin(), dl,
9042       TII->get(ARM::PHI), ABSDstReg)
9043       .addReg(NewRsbDstReg).addMBB(RSBBB)
9044       .addReg(ABSSrcReg).addMBB(BB);
9045 
9046     // remove ABS instruction
9047     MI.eraseFromParent();
9048 
9049     // return last added BB
9050     return SinkBB;
9051   }
9052   case ARM::COPY_STRUCT_BYVAL_I32:
9053     ++NumLoopByVals;
9054     return EmitStructByval(MI, BB);
9055   case ARM::WIN__CHKSTK:
9056     return EmitLowered__chkstk(MI, BB);
9057   case ARM::WIN__DBZCHK:
9058     return EmitLowered__dbzchk(MI, BB);
9059   }
9060 }
9061 
9062 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
9063 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9064 /// instead of as a custom inserter because we need the use list from the SDNode.
9065 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9066                                     MachineInstr &MI, const SDNode *Node) {
9067   bool isThumb1 = Subtarget->isThumb1Only();
9068 
9069   DebugLoc DL = MI.getDebugLoc();
9070   MachineFunction *MF = MI.getParent()->getParent();
9071   MachineRegisterInfo &MRI = MF->getRegInfo();
9072   MachineInstrBuilder MIB(*MF, MI);
9073 
9074   // If the new dst/src is unused mark it as dead.
9075   if (!Node->hasAnyUseOfValue(0)) {
9076     MI.getOperand(0).setIsDead(true);
9077   }
9078   if (!Node->hasAnyUseOfValue(1)) {
9079     MI.getOperand(1).setIsDead(true);
9080   }
9081 
9082   // The MEMCPY both defines and kills the scratch registers.
9083   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9084     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9085                                                          : &ARM::GPRRegClass);
9086     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9087   }
9088 }
9089 
9090 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9091                                                       SDNode *Node) const {
9092   if (MI.getOpcode() == ARM::MEMCPY) {
9093     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9094     return;
9095   }
9096 
9097   const MCInstrDesc *MCID = &MI.getDesc();
9098   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9099   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9100   // operand is still set to noreg. If needed, set the optional operand's
9101   // register to CPSR, and remove the redundant implicit def.
9102   //
9103   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
9104 
9105   // Rename pseudo opcodes.
9106   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9107   unsigned ccOutIdx;
9108   if (NewOpc) {
9109     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9110     MCID = &TII->get(NewOpc);
9111 
9112     assert(MCID->getNumOperands() ==
9113            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9114         && "converted opcode should be the same except for cc_out"
9115            " (and, on Thumb1, pred)");
9116 
9117     MI.setDesc(*MCID);
9118 
9119     // Add the optional cc_out operand
9120     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9121 
9122     // On Thumb1, move all input operands to the end, then add the predicate
9123     if (Subtarget->isThumb1Only()) {
9124       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9125         MI.addOperand(MI.getOperand(1));
9126         MI.RemoveOperand(1);
9127       }
9128 
9129       // Restore the ties
9130       for (unsigned i = MI.getNumOperands(); i--;) {
9131         const MachineOperand& op = MI.getOperand(i);
9132         if (op.isReg() && op.isUse()) {
9133           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9134           if (DefIdx != -1)
9135             MI.tieOperands(DefIdx, i);
9136         }
9137       }
9138 
9139       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9140       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9141       ccOutIdx = 1;
9142     } else
9143       ccOutIdx = MCID->getNumOperands() - 1;
9144   } else
9145     ccOutIdx = MCID->getNumOperands() - 1;
9146 
9147   // Any ARM instruction that sets the 's' bit should specify an optional
9148   // "cc_out" operand in the last operand position.
9149   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9150     assert(!NewOpc && "Optional cc_out operand required");
9151     return;
9152   }
9153   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9154   // since we already have an optional CPSR def.
9155   bool definesCPSR = false;
9156   bool deadCPSR = false;
9157   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9158        ++i) {
9159     const MachineOperand &MO = MI.getOperand(i);
9160     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9161       definesCPSR = true;
9162       if (MO.isDead())
9163         deadCPSR = true;
9164       MI.RemoveOperand(i);
9165       break;
9166     }
9167   }
9168   if (!definesCPSR) {
9169     assert(!NewOpc && "Optional cc_out operand required");
9170     return;
9171   }
9172   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9173   if (deadCPSR) {
9174     assert(!MI.getOperand(ccOutIdx).getReg() &&
9175            "expect uninitialized optional cc_out operand");
9176     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9177     if (!Subtarget->isThumb1Only())
9178       return;
9179   }
9180 
9181   // If this instruction was defined with an optional CPSR def and its dag node
9182   // had a live implicit CPSR def, then activate the optional CPSR def.
9183   MachineOperand &MO = MI.getOperand(ccOutIdx);
9184   MO.setReg(ARM::CPSR);
9185   MO.setIsDef(true);
9186 }
9187 
9188 //===----------------------------------------------------------------------===//
9189 //                           ARM Optimization Hooks
9190 //===----------------------------------------------------------------------===//
9191 
9192 // Helper function that checks if N is a null or all ones constant.
9193 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9194   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9195 }
9196 
9197 // Return true if N is conditionally 0 or all ones.
9198 // Detects these expressions where cc is an i1 value:
9199 //
9200 //   (select cc 0, y)   [AllOnes=0]
9201 //   (select cc y, 0)   [AllOnes=0]
9202 //   (zext cc)          [AllOnes=0]
9203 //   (sext cc)          [AllOnes=0/1]
9204 //   (select cc -1, y)  [AllOnes=1]
9205 //   (select cc y, -1)  [AllOnes=1]
9206 //
9207 // Invert is set when N is the null/all ones constant when CC is false.
9208 // OtherOp is set to the alternative value of N.
9209 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9210                                        SDValue &CC, bool &Invert,
9211                                        SDValue &OtherOp,
9212                                        SelectionDAG &DAG) {
9213   switch (N->getOpcode()) {
9214   default: return false;
9215   case ISD::SELECT: {
9216     CC = N->getOperand(0);
9217     SDValue N1 = N->getOperand(1);
9218     SDValue N2 = N->getOperand(2);
9219     if (isZeroOrAllOnes(N1, AllOnes)) {
9220       Invert = false;
9221       OtherOp = N2;
9222       return true;
9223     }
9224     if (isZeroOrAllOnes(N2, AllOnes)) {
9225       Invert = true;
9226       OtherOp = N1;
9227       return true;
9228     }
9229     return false;
9230   }
9231   case ISD::ZERO_EXTEND:
9232     // (zext cc) can never be the all ones value.
9233     if (AllOnes)
9234       return false;
9235     LLVM_FALLTHROUGH;
9236   case ISD::SIGN_EXTEND: {
9237     SDLoc dl(N);
9238     EVT VT = N->getValueType(0);
9239     CC = N->getOperand(0);
9240     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9241       return false;
9242     Invert = !AllOnes;
9243     if (AllOnes)
9244       // When looking for an AllOnes constant, N is an sext, and the 'other'
9245       // value is 0.
9246       OtherOp = DAG.getConstant(0, dl, VT);
9247     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9248       // When looking for a 0 constant, N can be zext or sext.
9249       OtherOp = DAG.getConstant(1, dl, VT);
9250     else
9251       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9252                                 VT);
9253     return true;
9254   }
9255   }
9256 }
9257 
9258 // Combine a constant select operand into its use:
9259 //
9260 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9261 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9262 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9263 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9264 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9265 //
9266 // The transform is rejected if the select doesn't have a constant operand that
9267 // is null, or all ones when AllOnes is set.
9268 //
9269 // Also recognize sext/zext from i1:
9270 //
9271 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9272 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9273 //
9274 // These transformations eventually create predicated instructions.
9275 //
9276 // @param N       The node to transform.
9277 // @param Slct    The N operand that is a select.
9278 // @param OtherOp The other N operand (x above).
9279 // @param DCI     Context.
9280 // @param AllOnes Require the select constant to be all ones instead of null.
9281 // @returns The new node, or SDValue() on failure.
9282 static
9283 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9284                             TargetLowering::DAGCombinerInfo &DCI,
9285                             bool AllOnes = false) {
9286   SelectionDAG &DAG = DCI.DAG;
9287   EVT VT = N->getValueType(0);
9288   SDValue NonConstantVal;
9289   SDValue CCOp;
9290   bool SwapSelectOps;
9291   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9292                                   NonConstantVal, DAG))
9293     return SDValue();
9294 
9295   // Slct is now know to be the desired identity constant when CC is true.
9296   SDValue TrueVal = OtherOp;
9297   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9298                                  OtherOp, NonConstantVal);
9299   // Unless SwapSelectOps says CC should be false.
9300   if (SwapSelectOps)
9301     std::swap(TrueVal, FalseVal);
9302 
9303   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9304                      CCOp, TrueVal, FalseVal);
9305 }
9306 
9307 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9308 static
9309 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9310                                        TargetLowering::DAGCombinerInfo &DCI) {
9311   SDValue N0 = N->getOperand(0);
9312   SDValue N1 = N->getOperand(1);
9313   if (N0.getNode()->hasOneUse())
9314     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9315       return Result;
9316   if (N1.getNode()->hasOneUse())
9317     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9318       return Result;
9319   return SDValue();
9320 }
9321 
9322 static bool IsVUZPShuffleNode(SDNode *N) {
9323   // VUZP shuffle node.
9324   if (N->getOpcode() == ARMISD::VUZP)
9325     return true;
9326 
9327   // "VUZP" on i32 is an alias for VTRN.
9328   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9329     return true;
9330 
9331   return false;
9332 }
9333 
9334 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9335                                  TargetLowering::DAGCombinerInfo &DCI,
9336                                  const ARMSubtarget *Subtarget) {
9337   // Look for ADD(VUZP.0, VUZP.1).
9338   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9339       N0 == N1)
9340    return SDValue();
9341 
9342   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9343   if (!N->getValueType(0).is64BitVector())
9344     return SDValue();
9345 
9346   // Generate vpadd.
9347   SelectionDAG &DAG = DCI.DAG;
9348   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9349   SDLoc dl(N);
9350   SDNode *Unzip = N0.getNode();
9351   EVT VT = N->getValueType(0);
9352 
9353   SmallVector<SDValue, 8> Ops;
9354   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9355                                 TLI.getPointerTy(DAG.getDataLayout())));
9356   Ops.push_back(Unzip->getOperand(0));
9357   Ops.push_back(Unzip->getOperand(1));
9358 
9359   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9360 }
9361 
9362 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9363                                       TargetLowering::DAGCombinerInfo &DCI,
9364                                       const ARMSubtarget *Subtarget) {
9365   // Check for two extended operands.
9366   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9367         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9368       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9369         N1.getOpcode() == ISD::ZERO_EXTEND))
9370     return SDValue();
9371 
9372   SDValue N00 = N0.getOperand(0);
9373   SDValue N10 = N1.getOperand(0);
9374 
9375   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9376   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9377       N00 == N10)
9378     return SDValue();
9379 
9380   // We only recognize Q register paddl here; this can't be reached until
9381   // after type legalization.
9382   if (!N00.getValueType().is64BitVector() ||
9383       !N0.getValueType().is128BitVector())
9384     return SDValue();
9385 
9386   // Generate vpaddl.
9387   SelectionDAG &DAG = DCI.DAG;
9388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9389   SDLoc dl(N);
9390   EVT VT = N->getValueType(0);
9391 
9392   SmallVector<SDValue, 8> Ops;
9393   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9394   unsigned Opcode;
9395   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9396     Opcode = Intrinsic::arm_neon_vpaddls;
9397   else
9398     Opcode = Intrinsic::arm_neon_vpaddlu;
9399   Ops.push_back(DAG.getConstant(Opcode, dl,
9400                                 TLI.getPointerTy(DAG.getDataLayout())));
9401   EVT ElemTy = N00.getValueType().getVectorElementType();
9402   unsigned NumElts = VT.getVectorNumElements();
9403   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9404   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9405                                N00.getOperand(0), N00.getOperand(1));
9406   Ops.push_back(Concat);
9407 
9408   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9409 }
9410 
9411 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9412 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9413 // much easier to match.
9414 static SDValue
9415 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9416                                TargetLowering::DAGCombinerInfo &DCI,
9417                                const ARMSubtarget *Subtarget) {
9418   // Only perform optimization if after legalize, and if NEON is available. We
9419   // also expected both operands to be BUILD_VECTORs.
9420   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9421       || N0.getOpcode() != ISD::BUILD_VECTOR
9422       || N1.getOpcode() != ISD::BUILD_VECTOR)
9423     return SDValue();
9424 
9425   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9426   EVT VT = N->getValueType(0);
9427   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9428     return SDValue();
9429 
9430   // Check that the vector operands are of the right form.
9431   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9432   // operands, where N is the size of the formed vector.
9433   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9434   // index such that we have a pair wise add pattern.
9435 
9436   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9437   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9438     return SDValue();
9439   SDValue Vec = N0->getOperand(0)->getOperand(0);
9440   SDNode *V = Vec.getNode();
9441   unsigned nextIndex = 0;
9442 
9443   // For each operands to the ADD which are BUILD_VECTORs,
9444   // check to see if each of their operands are an EXTRACT_VECTOR with
9445   // the same vector and appropriate index.
9446   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9447     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9448         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9449 
9450       SDValue ExtVec0 = N0->getOperand(i);
9451       SDValue ExtVec1 = N1->getOperand(i);
9452 
9453       // First operand is the vector, verify its the same.
9454       if (V != ExtVec0->getOperand(0).getNode() ||
9455           V != ExtVec1->getOperand(0).getNode())
9456         return SDValue();
9457 
9458       // Second is the constant, verify its correct.
9459       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9460       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9461 
9462       // For the constant, we want to see all the even or all the odd.
9463       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9464           || C1->getZExtValue() != nextIndex+1)
9465         return SDValue();
9466 
9467       // Increment index.
9468       nextIndex+=2;
9469     } else
9470       return SDValue();
9471   }
9472 
9473   // Don't generate vpaddl+vmovn; we'll match it to vpadd later.
9474   if (Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9475     return SDValue();
9476 
9477   // Create VPADDL node.
9478   SelectionDAG &DAG = DCI.DAG;
9479   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9480 
9481   SDLoc dl(N);
9482 
9483   // Build operand list.
9484   SmallVector<SDValue, 8> Ops;
9485   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9486                                 TLI.getPointerTy(DAG.getDataLayout())));
9487 
9488   // Input is the vector.
9489   Ops.push_back(Vec);
9490 
9491   // Get widened type and narrowed type.
9492   MVT widenType;
9493   unsigned numElem = VT.getVectorNumElements();
9494 
9495   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9496   switch (inputLaneType.getSimpleVT().SimpleTy) {
9497     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9498     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9499     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9500     default:
9501       llvm_unreachable("Invalid vector element type for padd optimization.");
9502   }
9503 
9504   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9505   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9506   return DAG.getNode(ExtOp, dl, VT, tmp);
9507 }
9508 
9509 static SDValue findMUL_LOHI(SDValue V) {
9510   if (V->getOpcode() == ISD::UMUL_LOHI ||
9511       V->getOpcode() == ISD::SMUL_LOHI)
9512     return V;
9513   return SDValue();
9514 }
9515 
9516 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9517                                         TargetLowering::DAGCombinerInfo &DCI,
9518                                         const ARMSubtarget *Subtarget) {
9519 
9520   if (Subtarget->isThumb()) {
9521     if (!Subtarget->hasDSP())
9522       return SDValue();
9523   } else if (!Subtarget->hasV5TEOps())
9524     return SDValue();
9525 
9526   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
9527   // accumulates the product into a 64-bit value. The 16-bit values will
9528   // be sign extended somehow or SRA'd into 32-bit values
9529   // (addc (adde (mul 16bit, 16bit), lo), hi)
9530   SDValue Mul = AddcNode->getOperand(0);
9531   SDValue Lo = AddcNode->getOperand(1);
9532   if (Mul.getOpcode() != ISD::MUL) {
9533     Lo = AddcNode->getOperand(0);
9534     Mul = AddcNode->getOperand(1);
9535     if (Mul.getOpcode() != ISD::MUL)
9536       return SDValue();
9537   }
9538 
9539   SDValue SRA = AddeNode->getOperand(0);
9540   SDValue Hi = AddeNode->getOperand(1);
9541   if (SRA.getOpcode() != ISD::SRA) {
9542     SRA = AddeNode->getOperand(1);
9543     Hi = AddeNode->getOperand(0);
9544     if (SRA.getOpcode() != ISD::SRA)
9545       return SDValue();
9546   }
9547   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
9548     if (Const->getZExtValue() != 31)
9549       return SDValue();
9550   } else
9551     return SDValue();
9552 
9553   if (SRA.getOperand(0) != Mul)
9554     return SDValue();
9555 
9556   SelectionDAG &DAG = DCI.DAG;
9557   SDLoc dl(AddcNode);
9558   unsigned Opcode = 0;
9559   SDValue Op0;
9560   SDValue Op1;
9561 
9562   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
9563     Opcode = ARMISD::SMLALBB;
9564     Op0 = Mul.getOperand(0);
9565     Op1 = Mul.getOperand(1);
9566   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
9567     Opcode = ARMISD::SMLALBT;
9568     Op0 = Mul.getOperand(0);
9569     Op1 = Mul.getOperand(1).getOperand(0);
9570   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
9571     Opcode = ARMISD::SMLALTB;
9572     Op0 = Mul.getOperand(0).getOperand(0);
9573     Op1 = Mul.getOperand(1);
9574   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
9575     Opcode = ARMISD::SMLALTT;
9576     Op0 = Mul->getOperand(0).getOperand(0);
9577     Op1 = Mul->getOperand(1).getOperand(0);
9578   }
9579 
9580   if (!Op0 || !Op1)
9581     return SDValue();
9582 
9583   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
9584                               Op0, Op1, Lo, Hi);
9585   // Replace the ADDs' nodes uses by the MLA node's values.
9586   SDValue HiMLALResult(SMLAL.getNode(), 1);
9587   SDValue LoMLALResult(SMLAL.getNode(), 0);
9588 
9589   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9590   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9591 
9592   // Return original node to notify the driver to stop replacing.
9593   SDValue resNode(AddcNode, 0);
9594   return resNode;
9595 }
9596 
9597 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode,
9598                                      TargetLowering::DAGCombinerInfo &DCI,
9599                                      const ARMSubtarget *Subtarget) {
9600   // Look for multiply add opportunities.
9601   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9602   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9603   // a glue link from the first add to the second add.
9604   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9605   // a S/UMLAL instruction.
9606   //                  UMUL_LOHI
9607   //                 / :lo    \ :hi
9608   //                /          \          [no multiline comment]
9609   //    loAdd ->  ADDE         |
9610   //                 \ :glue  /
9611   //                  \      /
9612   //                    ADDC   <- hiAdd
9613   //
9614   assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE");
9615 
9616   assert(AddeNode->getNumOperands() == 3 &&
9617          AddeNode->getOperand(2).getValueType() == MVT::i32 &&
9618          "ADDE node has the wrong inputs");
9619 
9620   // Check that we have a glued ADDC node.
9621   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9622   if (AddcNode->getOpcode() != ARMISD::ADDC)
9623     return SDValue();
9624 
9625   SDValue AddcOp0 = AddcNode->getOperand(0);
9626   SDValue AddcOp1 = AddcNode->getOperand(1);
9627 
9628   // Check if the two operands are from the same mul_lohi node.
9629   if (AddcOp0.getNode() == AddcOp1.getNode())
9630     return SDValue();
9631 
9632   assert(AddcNode->getNumValues() == 2 &&
9633          AddcNode->getValueType(0) == MVT::i32 &&
9634          "Expect ADDC with two result values. First: i32");
9635 
9636   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
9637   // maybe a SMLAL which multiplies two 16-bit values.
9638   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
9639       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
9640       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
9641       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
9642     return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget);
9643 
9644   // Check for the triangle shape.
9645   SDValue AddeOp0 = AddeNode->getOperand(0);
9646   SDValue AddeOp1 = AddeNode->getOperand(1);
9647 
9648   // Make sure that the ADDE operands are not coming from the same node.
9649   if (AddeOp0.getNode() == AddeOp1.getNode())
9650     return SDValue();
9651 
9652   // Find the MUL_LOHI node walking up ADDE's operands.
9653   bool IsLeftOperandMUL = false;
9654   SDValue MULOp = findMUL_LOHI(AddeOp0);
9655   if (MULOp == SDValue())
9656    MULOp = findMUL_LOHI(AddeOp1);
9657   else
9658     IsLeftOperandMUL = true;
9659   if (MULOp == SDValue())
9660     return SDValue();
9661 
9662   // Figure out the right opcode.
9663   unsigned Opc = MULOp->getOpcode();
9664   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
9665 
9666   // Figure out the high and low input values to the MLAL node.
9667   SDValue* HiAdd = nullptr;
9668   SDValue* LoMul = nullptr;
9669   SDValue* LowAdd = nullptr;
9670 
9671   // Ensure that ADDE is from high result of ISD::SMUL_LOHI.
9672   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
9673     return SDValue();
9674 
9675   if (IsLeftOperandMUL)
9676     HiAdd = &AddeOp1;
9677   else
9678     HiAdd = &AddeOp0;
9679 
9680 
9681   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
9682   // whose low result is fed to the ADDC we are checking.
9683 
9684   if (AddcOp0 == MULOp.getValue(0)) {
9685     LoMul = &AddcOp0;
9686     LowAdd = &AddcOp1;
9687   }
9688   if (AddcOp1 == MULOp.getValue(0)) {
9689     LoMul = &AddcOp1;
9690     LowAdd = &AddcOp0;
9691   }
9692 
9693   if (!LoMul)
9694     return SDValue();
9695 
9696   // Create the merged node.
9697   SelectionDAG &DAG = DCI.DAG;
9698 
9699   // Build operand list.
9700   SmallVector<SDValue, 8> Ops;
9701   Ops.push_back(LoMul->getOperand(0));
9702   Ops.push_back(LoMul->getOperand(1));
9703   Ops.push_back(*LowAdd);
9704   Ops.push_back(*HiAdd);
9705 
9706   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
9707                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9708 
9709   // Replace the ADDs' nodes uses by the MLA node's values.
9710   SDValue HiMLALResult(MLALNode.getNode(), 1);
9711   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9712 
9713   SDValue LoMLALResult(MLALNode.getNode(), 0);
9714   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9715 
9716   // Return original node to notify the driver to stop replacing.
9717   return SDValue(AddeNode, 0);
9718 }
9719 
9720 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
9721                                       TargetLowering::DAGCombinerInfo &DCI,
9722                                       const ARMSubtarget *Subtarget) {
9723   // UMAAL is similar to UMLAL except that it adds two unsigned values.
9724   // While trying to combine for the other MLAL nodes, first search for the
9725   // chance to use UMAAL. Check if Addc uses a node which has already
9726   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
9727   // as the addend, and it's handled in PerformUMLALCombine.
9728 
9729   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9730     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9731 
9732   // Check that we have a glued ADDC node.
9733   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9734   if (AddcNode->getOpcode() != ARMISD::ADDC)
9735     return SDValue();
9736 
9737   // Find the converted UMAAL or quit if it doesn't exist.
9738   SDNode *UmlalNode = nullptr;
9739   SDValue AddHi;
9740   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
9741     UmlalNode = AddcNode->getOperand(0).getNode();
9742     AddHi = AddcNode->getOperand(1);
9743   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
9744     UmlalNode = AddcNode->getOperand(1).getNode();
9745     AddHi = AddcNode->getOperand(0);
9746   } else {
9747     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9748   }
9749 
9750   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
9751   // the ADDC as well as Zero.
9752   if (!isNullConstant(UmlalNode->getOperand(3)))
9753     return SDValue();
9754 
9755   if ((isNullConstant(AddeNode->getOperand(0)) &&
9756        AddeNode->getOperand(1).getNode() == UmlalNode) ||
9757       (AddeNode->getOperand(0).getNode() == UmlalNode &&
9758        isNullConstant(AddeNode->getOperand(1)))) {
9759 
9760     SelectionDAG &DAG = DCI.DAG;
9761     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
9762                       UmlalNode->getOperand(2), AddHi };
9763     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
9764                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9765 
9766     // Replace the ADDs' nodes uses by the UMAAL node's values.
9767     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
9768     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
9769 
9770     // Return original node to notify the driver to stop replacing.
9771     return SDValue(AddeNode, 0);
9772   }
9773   return SDValue();
9774 }
9775 
9776 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
9777                                    const ARMSubtarget *Subtarget) {
9778   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9779     return SDValue();
9780 
9781   // Check that we have a pair of ADDC and ADDE as operands.
9782   // Both addends of the ADDE must be zero.
9783   SDNode* AddcNode = N->getOperand(2).getNode();
9784   SDNode* AddeNode = N->getOperand(3).getNode();
9785   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
9786       (AddeNode->getOpcode() == ARMISD::ADDE) &&
9787       isNullConstant(AddeNode->getOperand(0)) &&
9788       isNullConstant(AddeNode->getOperand(1)) &&
9789       (AddeNode->getOperand(2).getNode() == AddcNode))
9790     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
9791                        DAG.getVTList(MVT::i32, MVT::i32),
9792                        {N->getOperand(0), N->getOperand(1),
9793                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
9794   else
9795     return SDValue();
9796 }
9797 
9798 static SDValue PerformAddcSubcCombine(SDNode *N, SelectionDAG &DAG,
9799                                       const ARMSubtarget *Subtarget) {
9800   if (Subtarget->isThumb1Only()) {
9801     SDValue RHS = N->getOperand(1);
9802     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
9803       int32_t imm = C->getSExtValue();
9804       if (imm < 0 && imm > INT_MIN) {
9805         SDLoc DL(N);
9806         RHS = DAG.getConstant(-imm, DL, MVT::i32);
9807         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
9808                                                            : ARMISD::ADDC;
9809         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
9810       }
9811     }
9812   }
9813   return SDValue();
9814 }
9815 
9816 static SDValue PerformAddeSubeCombine(SDNode *N, SelectionDAG &DAG,
9817                                       const ARMSubtarget *Subtarget) {
9818   if (Subtarget->isThumb1Only()) {
9819     SDValue RHS = N->getOperand(1);
9820     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
9821       int64_t imm = C->getSExtValue();
9822       if (imm < 0) {
9823         SDLoc DL(N);
9824 
9825         // The with-carry-in form matches bitwise not instead of the negation.
9826         // Effectively, the inverse interpretation of the carry flag already
9827         // accounts for part of the negation.
9828         RHS = DAG.getConstant(~imm, DL, MVT::i32);
9829 
9830         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
9831                                                            : ARMISD::ADDE;
9832         return DAG.getNode(Opcode, DL, N->getVTList(),
9833                            N->getOperand(0), RHS, N->getOperand(2));
9834       }
9835     }
9836   }
9837   return SDValue();
9838 }
9839 
9840 /// PerformADDECombine - Target-specific dag combine transform from
9841 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
9842 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
9843 static SDValue PerformADDECombine(SDNode *N,
9844                                   TargetLowering::DAGCombinerInfo &DCI,
9845                                   const ARMSubtarget *Subtarget) {
9846   // Only ARM and Thumb2 support UMLAL/SMLAL.
9847   if (Subtarget->isThumb1Only())
9848     return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
9849 
9850   // Only perform the checks after legalize when the pattern is available.
9851   if (DCI.isBeforeLegalize()) return SDValue();
9852 
9853   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
9854 }
9855 
9856 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
9857 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
9858 /// called with the default operands, and if that fails, with commuted
9859 /// operands.
9860 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
9861                                           TargetLowering::DAGCombinerInfo &DCI,
9862                                           const ARMSubtarget *Subtarget){
9863   // Attempt to create vpadd for this add.
9864   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
9865     return Result;
9866 
9867   // Attempt to create vpaddl for this add.
9868   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
9869     return Result;
9870   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
9871                                                       Subtarget))
9872     return Result;
9873 
9874   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
9875   if (N0.getNode()->hasOneUse())
9876     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
9877       return Result;
9878   return SDValue();
9879 }
9880 
9881 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
9882 ///
9883 static SDValue PerformADDCombine(SDNode *N,
9884                                  TargetLowering::DAGCombinerInfo &DCI,
9885                                  const ARMSubtarget *Subtarget) {
9886   SDValue N0 = N->getOperand(0);
9887   SDValue N1 = N->getOperand(1);
9888 
9889   // First try with the default operand order.
9890   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
9891     return Result;
9892 
9893   // If that didn't work, try again with the operands commuted.
9894   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
9895 }
9896 
9897 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
9898 ///
9899 static SDValue PerformSUBCombine(SDNode *N,
9900                                  TargetLowering::DAGCombinerInfo &DCI) {
9901   SDValue N0 = N->getOperand(0);
9902   SDValue N1 = N->getOperand(1);
9903 
9904   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
9905   if (N1.getNode()->hasOneUse())
9906     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
9907       return Result;
9908 
9909   return SDValue();
9910 }
9911 
9912 /// PerformVMULCombine
9913 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
9914 /// special multiplier accumulator forwarding.
9915 ///   vmul d3, d0, d2
9916 ///   vmla d3, d1, d2
9917 /// is faster than
9918 ///   vadd d3, d0, d1
9919 ///   vmul d3, d3, d2
9920 //  However, for (A + B) * (A + B),
9921 //    vadd d2, d0, d1
9922 //    vmul d3, d0, d2
9923 //    vmla d3, d1, d2
9924 //  is slower than
9925 //    vadd d2, d0, d1
9926 //    vmul d3, d2, d2
9927 static SDValue PerformVMULCombine(SDNode *N,
9928                                   TargetLowering::DAGCombinerInfo &DCI,
9929                                   const ARMSubtarget *Subtarget) {
9930   if (!Subtarget->hasVMLxForwarding())
9931     return SDValue();
9932 
9933   SelectionDAG &DAG = DCI.DAG;
9934   SDValue N0 = N->getOperand(0);
9935   SDValue N1 = N->getOperand(1);
9936   unsigned Opcode = N0.getOpcode();
9937   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9938       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
9939     Opcode = N1.getOpcode();
9940     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
9941         Opcode != ISD::FADD && Opcode != ISD::FSUB)
9942       return SDValue();
9943     std::swap(N0, N1);
9944   }
9945 
9946   if (N0 == N1)
9947     return SDValue();
9948 
9949   EVT VT = N->getValueType(0);
9950   SDLoc DL(N);
9951   SDValue N00 = N0->getOperand(0);
9952   SDValue N01 = N0->getOperand(1);
9953   return DAG.getNode(Opcode, DL, VT,
9954                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
9955                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
9956 }
9957 
9958 static SDValue PerformMULCombine(SDNode *N,
9959                                  TargetLowering::DAGCombinerInfo &DCI,
9960                                  const ARMSubtarget *Subtarget) {
9961   SelectionDAG &DAG = DCI.DAG;
9962 
9963   if (Subtarget->isThumb1Only())
9964     return SDValue();
9965 
9966   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
9967     return SDValue();
9968 
9969   EVT VT = N->getValueType(0);
9970   if (VT.is64BitVector() || VT.is128BitVector())
9971     return PerformVMULCombine(N, DCI, Subtarget);
9972   if (VT != MVT::i32)
9973     return SDValue();
9974 
9975   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9976   if (!C)
9977     return SDValue();
9978 
9979   int64_t MulAmt = C->getSExtValue();
9980   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
9981 
9982   ShiftAmt = ShiftAmt & (32 - 1);
9983   SDValue V = N->getOperand(0);
9984   SDLoc DL(N);
9985 
9986   SDValue Res;
9987   MulAmt >>= ShiftAmt;
9988 
9989   if (MulAmt >= 0) {
9990     if (isPowerOf2_32(MulAmt - 1)) {
9991       // (mul x, 2^N + 1) => (add (shl x, N), x)
9992       Res = DAG.getNode(ISD::ADD, DL, VT,
9993                         V,
9994                         DAG.getNode(ISD::SHL, DL, VT,
9995                                     V,
9996                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
9997                                                     MVT::i32)));
9998     } else if (isPowerOf2_32(MulAmt + 1)) {
9999       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10000       Res = DAG.getNode(ISD::SUB, DL, VT,
10001                         DAG.getNode(ISD::SHL, DL, VT,
10002                                     V,
10003                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10004                                                     MVT::i32)),
10005                         V);
10006     } else
10007       return SDValue();
10008   } else {
10009     uint64_t MulAmtAbs = -MulAmt;
10010     if (isPowerOf2_32(MulAmtAbs + 1)) {
10011       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10012       Res = DAG.getNode(ISD::SUB, DL, VT,
10013                         V,
10014                         DAG.getNode(ISD::SHL, DL, VT,
10015                                     V,
10016                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10017                                                     MVT::i32)));
10018     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10019       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10020       Res = DAG.getNode(ISD::ADD, DL, VT,
10021                         V,
10022                         DAG.getNode(ISD::SHL, DL, VT,
10023                                     V,
10024                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10025                                                     MVT::i32)));
10026       Res = DAG.getNode(ISD::SUB, DL, VT,
10027                         DAG.getConstant(0, DL, MVT::i32), Res);
10028 
10029     } else
10030       return SDValue();
10031   }
10032 
10033   if (ShiftAmt != 0)
10034     Res = DAG.getNode(ISD::SHL, DL, VT,
10035                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10036 
10037   // Do not add new nodes to DAG combiner worklist.
10038   DCI.CombineTo(N, Res, false);
10039   return SDValue();
10040 }
10041 
10042 static SDValue PerformANDCombine(SDNode *N,
10043                                  TargetLowering::DAGCombinerInfo &DCI,
10044                                  const ARMSubtarget *Subtarget) {
10045   // Attempt to use immediate-form VBIC
10046   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10047   SDLoc dl(N);
10048   EVT VT = N->getValueType(0);
10049   SelectionDAG &DAG = DCI.DAG;
10050 
10051   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10052     return SDValue();
10053 
10054   APInt SplatBits, SplatUndef;
10055   unsigned SplatBitSize;
10056   bool HasAnyUndefs;
10057   if (BVN &&
10058       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10059     if (SplatBitSize <= 64) {
10060       EVT VbicVT;
10061       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10062                                       SplatUndef.getZExtValue(), SplatBitSize,
10063                                       DAG, dl, VbicVT, VT.is128BitVector(),
10064                                       OtherModImm);
10065       if (Val.getNode()) {
10066         SDValue Input =
10067           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10068         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10069         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10070       }
10071     }
10072   }
10073 
10074   if (!Subtarget->isThumb1Only()) {
10075     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10076     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10077       return Result;
10078   }
10079 
10080   return SDValue();
10081 }
10082 
10083 // Try combining OR nodes to SMULWB, SMULWT.
10084 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10085                                          TargetLowering::DAGCombinerInfo &DCI,
10086                                          const ARMSubtarget *Subtarget) {
10087   if (!Subtarget->hasV6Ops() ||
10088       (Subtarget->isThumb() &&
10089        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10090     return SDValue();
10091 
10092   SDValue SRL = OR->getOperand(0);
10093   SDValue SHL = OR->getOperand(1);
10094 
10095   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10096     SRL = OR->getOperand(1);
10097     SHL = OR->getOperand(0);
10098   }
10099   if (!isSRL16(SRL) || !isSHL16(SHL))
10100     return SDValue();
10101 
10102   // The first operands to the shifts need to be the two results from the
10103   // same smul_lohi node.
10104   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10105        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10106     return SDValue();
10107 
10108   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10109   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10110       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10111     return SDValue();
10112 
10113   // Now we have:
10114   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10115   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10116   // For SMUWB the 16-bit value will signed extended somehow.
10117   // For SMULWT only the SRA is required.
10118   // Check both sides of SMUL_LOHI
10119   SDValue OpS16 = SMULLOHI->getOperand(0);
10120   SDValue OpS32 = SMULLOHI->getOperand(1);
10121 
10122   SelectionDAG &DAG = DCI.DAG;
10123   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10124     OpS16 = OpS32;
10125     OpS32 = SMULLOHI->getOperand(0);
10126   }
10127 
10128   SDLoc dl(OR);
10129   unsigned Opcode = 0;
10130   if (isS16(OpS16, DAG))
10131     Opcode = ARMISD::SMULWB;
10132   else if (isSRA16(OpS16)) {
10133     Opcode = ARMISD::SMULWT;
10134     OpS16 = OpS16->getOperand(0);
10135   }
10136   else
10137     return SDValue();
10138 
10139   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10140   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10141   return SDValue(OR, 0);
10142 }
10143 
10144 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
10145 static SDValue PerformORCombine(SDNode *N,
10146                                 TargetLowering::DAGCombinerInfo &DCI,
10147                                 const ARMSubtarget *Subtarget) {
10148   // Attempt to use immediate-form VORR
10149   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10150   SDLoc dl(N);
10151   EVT VT = N->getValueType(0);
10152   SelectionDAG &DAG = DCI.DAG;
10153 
10154   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10155     return SDValue();
10156 
10157   APInt SplatBits, SplatUndef;
10158   unsigned SplatBitSize;
10159   bool HasAnyUndefs;
10160   if (BVN && Subtarget->hasNEON() &&
10161       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10162     if (SplatBitSize <= 64) {
10163       EVT VorrVT;
10164       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
10165                                       SplatUndef.getZExtValue(), SplatBitSize,
10166                                       DAG, dl, VorrVT, VT.is128BitVector(),
10167                                       OtherModImm);
10168       if (Val.getNode()) {
10169         SDValue Input =
10170           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
10171         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
10172         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
10173       }
10174     }
10175   }
10176 
10177   if (!Subtarget->isThumb1Only()) {
10178     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10179     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10180       return Result;
10181     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
10182       return Result;
10183   }
10184 
10185   // The code below optimizes (or (and X, Y), Z).
10186   // The AND operand needs to have a single user to make these optimizations
10187   // profitable.
10188   SDValue N0 = N->getOperand(0);
10189   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
10190     return SDValue();
10191   SDValue N1 = N->getOperand(1);
10192 
10193   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
10194   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
10195       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10196     APInt SplatUndef;
10197     unsigned SplatBitSize;
10198     bool HasAnyUndefs;
10199 
10200     APInt SplatBits0, SplatBits1;
10201     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
10202     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
10203     // Ensure that the second operand of both ands are constants
10204     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
10205                                       HasAnyUndefs) && !HasAnyUndefs) {
10206         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
10207                                           HasAnyUndefs) && !HasAnyUndefs) {
10208             // Ensure that the bit width of the constants are the same and that
10209             // the splat arguments are logical inverses as per the pattern we
10210             // are trying to simplify.
10211             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
10212                 SplatBits0 == ~SplatBits1) {
10213                 // Canonicalize the vector type to make instruction selection
10214                 // simpler.
10215                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
10216                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
10217                                              N0->getOperand(1),
10218                                              N0->getOperand(0),
10219                                              N1->getOperand(0));
10220                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10221             }
10222         }
10223     }
10224   }
10225 
10226   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
10227   // reasonable.
10228 
10229   // BFI is only available on V6T2+
10230   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10231     return SDValue();
10232 
10233   SDLoc DL(N);
10234   // 1) or (and A, mask), val => ARMbfi A, val, mask
10235   //      iff (val & mask) == val
10236   //
10237   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10238   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10239   //          && mask == ~mask2
10240   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10241   //          && ~mask == mask2
10242   //  (i.e., copy a bitfield value into another bitfield of the same width)
10243 
10244   if (VT != MVT::i32)
10245     return SDValue();
10246 
10247   SDValue N00 = N0.getOperand(0);
10248 
10249   // The value and the mask need to be constants so we can verify this is
10250   // actually a bitfield set. If the mask is 0xffff, we can do better
10251   // via a movt instruction, so don't use BFI in that case.
10252   SDValue MaskOp = N0.getOperand(1);
10253   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10254   if (!MaskC)
10255     return SDValue();
10256   unsigned Mask = MaskC->getZExtValue();
10257   if (Mask == 0xffff)
10258     return SDValue();
10259   SDValue Res;
10260   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10261   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10262   if (N1C) {
10263     unsigned Val = N1C->getZExtValue();
10264     if ((Val & ~Mask) != Val)
10265       return SDValue();
10266 
10267     if (ARM::isBitFieldInvertedMask(Mask)) {
10268       Val >>= countTrailingZeros(~Mask);
10269 
10270       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10271                         DAG.getConstant(Val, DL, MVT::i32),
10272                         DAG.getConstant(Mask, DL, MVT::i32));
10273 
10274       // Do not add new nodes to DAG combiner worklist.
10275       DCI.CombineTo(N, Res, false);
10276       return SDValue();
10277     }
10278   } else if (N1.getOpcode() == ISD::AND) {
10279     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10280     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10281     if (!N11C)
10282       return SDValue();
10283     unsigned Mask2 = N11C->getZExtValue();
10284 
10285     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10286     // as is to match.
10287     if (ARM::isBitFieldInvertedMask(Mask) &&
10288         (Mask == ~Mask2)) {
10289       // The pack halfword instruction works better for masks that fit it,
10290       // so use that when it's available.
10291       if (Subtarget->hasDSP() &&
10292           (Mask == 0xffff || Mask == 0xffff0000))
10293         return SDValue();
10294       // 2a
10295       unsigned amt = countTrailingZeros(Mask2);
10296       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10297                         DAG.getConstant(amt, DL, MVT::i32));
10298       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10299                         DAG.getConstant(Mask, DL, MVT::i32));
10300       // Do not add new nodes to DAG combiner worklist.
10301       DCI.CombineTo(N, Res, false);
10302       return SDValue();
10303     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10304                (~Mask == Mask2)) {
10305       // The pack halfword instruction works better for masks that fit it,
10306       // so use that when it's available.
10307       if (Subtarget->hasDSP() &&
10308           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10309         return SDValue();
10310       // 2b
10311       unsigned lsb = countTrailingZeros(Mask);
10312       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10313                         DAG.getConstant(lsb, DL, MVT::i32));
10314       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10315                         DAG.getConstant(Mask2, DL, MVT::i32));
10316       // Do not add new nodes to DAG combiner worklist.
10317       DCI.CombineTo(N, Res, false);
10318       return SDValue();
10319     }
10320   }
10321 
10322   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10323       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10324       ARM::isBitFieldInvertedMask(~Mask)) {
10325     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10326     // where lsb(mask) == #shamt and masked bits of B are known zero.
10327     SDValue ShAmt = N00.getOperand(1);
10328     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10329     unsigned LSB = countTrailingZeros(Mask);
10330     if (ShAmtC != LSB)
10331       return SDValue();
10332 
10333     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10334                       DAG.getConstant(~Mask, DL, MVT::i32));
10335 
10336     // Do not add new nodes to DAG combiner worklist.
10337     DCI.CombineTo(N, Res, false);
10338   }
10339 
10340   return SDValue();
10341 }
10342 
10343 static SDValue PerformXORCombine(SDNode *N,
10344                                  TargetLowering::DAGCombinerInfo &DCI,
10345                                  const ARMSubtarget *Subtarget) {
10346   EVT VT = N->getValueType(0);
10347   SelectionDAG &DAG = DCI.DAG;
10348 
10349   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10350     return SDValue();
10351 
10352   if (!Subtarget->isThumb1Only()) {
10353     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10354     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10355       return Result;
10356   }
10357 
10358   return SDValue();
10359 }
10360 
10361 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
10362 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
10363 // their position in "to" (Rd).
10364 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
10365   assert(N->getOpcode() == ARMISD::BFI);
10366 
10367   SDValue From = N->getOperand(1);
10368   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
10369   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
10370 
10371   // If the Base came from a SHR #C, we can deduce that it is really testing bit
10372   // #C in the base of the SHR.
10373   if (From->getOpcode() == ISD::SRL &&
10374       isa<ConstantSDNode>(From->getOperand(1))) {
10375     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
10376     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
10377     FromMask <<= Shift.getLimitedValue(31);
10378     From = From->getOperand(0);
10379   }
10380 
10381   return From;
10382 }
10383 
10384 // If A and B contain one contiguous set of bits, does A | B == A . B?
10385 //
10386 // Neither A nor B must be zero.
10387 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
10388   unsigned LastActiveBitInA =  A.countTrailingZeros();
10389   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
10390   return LastActiveBitInA - 1 == FirstActiveBitInB;
10391 }
10392 
10393 static SDValue FindBFIToCombineWith(SDNode *N) {
10394   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
10395   // if one exists.
10396   APInt ToMask, FromMask;
10397   SDValue From = ParseBFI(N, ToMask, FromMask);
10398   SDValue To = N->getOperand(0);
10399 
10400   // Now check for a compatible BFI to merge with. We can pass through BFIs that
10401   // aren't compatible, but not if they set the same bit in their destination as
10402   // we do (or that of any BFI we're going to combine with).
10403   SDValue V = To;
10404   APInt CombinedToMask = ToMask;
10405   while (V.getOpcode() == ARMISD::BFI) {
10406     APInt NewToMask, NewFromMask;
10407     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
10408     if (NewFrom != From) {
10409       // This BFI has a different base. Keep going.
10410       CombinedToMask |= NewToMask;
10411       V = V.getOperand(0);
10412       continue;
10413     }
10414 
10415     // Do the written bits conflict with any we've seen so far?
10416     if ((NewToMask & CombinedToMask).getBoolValue())
10417       // Conflicting bits - bail out because going further is unsafe.
10418       return SDValue();
10419 
10420     // Are the new bits contiguous when combined with the old bits?
10421     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
10422         BitsProperlyConcatenate(FromMask, NewFromMask))
10423       return V;
10424     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
10425         BitsProperlyConcatenate(NewFromMask, FromMask))
10426       return V;
10427 
10428     // We've seen a write to some bits, so track it.
10429     CombinedToMask |= NewToMask;
10430     // Keep going...
10431     V = V.getOperand(0);
10432   }
10433 
10434   return SDValue();
10435 }
10436 
10437 static SDValue PerformBFICombine(SDNode *N,
10438                                  TargetLowering::DAGCombinerInfo &DCI) {
10439   SDValue N1 = N->getOperand(1);
10440   if (N1.getOpcode() == ISD::AND) {
10441     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
10442     // the bits being cleared by the AND are not demanded by the BFI.
10443     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10444     if (!N11C)
10445       return SDValue();
10446     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10447     unsigned LSB = countTrailingZeros(~InvMask);
10448     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
10449     assert(Width <
10450                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
10451            "undefined behavior");
10452     unsigned Mask = (1u << Width) - 1;
10453     unsigned Mask2 = N11C->getZExtValue();
10454     if ((Mask & (~Mask2)) == 0)
10455       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
10456                              N->getOperand(0), N1.getOperand(0),
10457                              N->getOperand(2));
10458   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
10459     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
10460     // Keep track of any consecutive bits set that all come from the same base
10461     // value. We can combine these together into a single BFI.
10462     SDValue CombineBFI = FindBFIToCombineWith(N);
10463     if (CombineBFI == SDValue())
10464       return SDValue();
10465 
10466     // We've found a BFI.
10467     APInt ToMask1, FromMask1;
10468     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
10469 
10470     APInt ToMask2, FromMask2;
10471     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
10472     assert(From1 == From2);
10473     (void)From2;
10474 
10475     // First, unlink CombineBFI.
10476     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
10477     // Then create a new BFI, combining the two together.
10478     APInt NewFromMask = FromMask1 | FromMask2;
10479     APInt NewToMask = ToMask1 | ToMask2;
10480 
10481     EVT VT = N->getValueType(0);
10482     SDLoc dl(N);
10483 
10484     if (NewFromMask[0] == 0)
10485       From1 = DCI.DAG.getNode(
10486         ISD::SRL, dl, VT, From1,
10487         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
10488     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
10489                            DCI.DAG.getConstant(~NewToMask, dl, VT));
10490   }
10491   return SDValue();
10492 }
10493 
10494 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
10495 /// ARMISD::VMOVRRD.
10496 static SDValue PerformVMOVRRDCombine(SDNode *N,
10497                                      TargetLowering::DAGCombinerInfo &DCI,
10498                                      const ARMSubtarget *Subtarget) {
10499   // vmovrrd(vmovdrr x, y) -> x,y
10500   SDValue InDouble = N->getOperand(0);
10501   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
10502     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
10503 
10504   // vmovrrd(load f64) -> (load i32), (load i32)
10505   SDNode *InNode = InDouble.getNode();
10506   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
10507       InNode->getValueType(0) == MVT::f64 &&
10508       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
10509       !cast<LoadSDNode>(InNode)->isVolatile()) {
10510     // TODO: Should this be done for non-FrameIndex operands?
10511     LoadSDNode *LD = cast<LoadSDNode>(InNode);
10512 
10513     SelectionDAG &DAG = DCI.DAG;
10514     SDLoc DL(LD);
10515     SDValue BasePtr = LD->getBasePtr();
10516     SDValue NewLD1 =
10517         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
10518                     LD->getAlignment(), LD->getMemOperand()->getFlags());
10519 
10520     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10521                                     DAG.getConstant(4, DL, MVT::i32));
10522     SDValue NewLD2 = DAG.getLoad(
10523         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
10524         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
10525 
10526     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
10527     if (DCI.DAG.getDataLayout().isBigEndian())
10528       std::swap (NewLD1, NewLD2);
10529     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
10530     return Result;
10531   }
10532 
10533   return SDValue();
10534 }
10535 
10536 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
10537 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
10538 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
10539   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
10540   SDValue Op0 = N->getOperand(0);
10541   SDValue Op1 = N->getOperand(1);
10542   if (Op0.getOpcode() == ISD::BITCAST)
10543     Op0 = Op0.getOperand(0);
10544   if (Op1.getOpcode() == ISD::BITCAST)
10545     Op1 = Op1.getOperand(0);
10546   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
10547       Op0.getNode() == Op1.getNode() &&
10548       Op0.getResNo() == 0 && Op1.getResNo() == 1)
10549     return DAG.getNode(ISD::BITCAST, SDLoc(N),
10550                        N->getValueType(0), Op0.getOperand(0));
10551   return SDValue();
10552 }
10553 
10554 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
10555 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
10556 /// i64 vector to have f64 elements, since the value can then be loaded
10557 /// directly into a VFP register.
10558 static bool hasNormalLoadOperand(SDNode *N) {
10559   unsigned NumElts = N->getValueType(0).getVectorNumElements();
10560   for (unsigned i = 0; i < NumElts; ++i) {
10561     SDNode *Elt = N->getOperand(i).getNode();
10562     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
10563       return true;
10564   }
10565   return false;
10566 }
10567 
10568 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
10569 /// ISD::BUILD_VECTOR.
10570 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
10571                                           TargetLowering::DAGCombinerInfo &DCI,
10572                                           const ARMSubtarget *Subtarget) {
10573   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
10574   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
10575   // into a pair of GPRs, which is fine when the value is used as a scalar,
10576   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
10577   SelectionDAG &DAG = DCI.DAG;
10578   if (N->getNumOperands() == 2)
10579     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
10580       return RV;
10581 
10582   // Load i64 elements as f64 values so that type legalization does not split
10583   // them up into i32 values.
10584   EVT VT = N->getValueType(0);
10585   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
10586     return SDValue();
10587   SDLoc dl(N);
10588   SmallVector<SDValue, 8> Ops;
10589   unsigned NumElts = VT.getVectorNumElements();
10590   for (unsigned i = 0; i < NumElts; ++i) {
10591     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
10592     Ops.push_back(V);
10593     // Make the DAGCombiner fold the bitcast.
10594     DCI.AddToWorklist(V.getNode());
10595   }
10596   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
10597   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
10598   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10599 }
10600 
10601 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
10602 static SDValue
10603 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10604   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
10605   // At that time, we may have inserted bitcasts from integer to float.
10606   // If these bitcasts have survived DAGCombine, change the lowering of this
10607   // BUILD_VECTOR in something more vector friendly, i.e., that does not
10608   // force to use floating point types.
10609 
10610   // Make sure we can change the type of the vector.
10611   // This is possible iff:
10612   // 1. The vector is only used in a bitcast to a integer type. I.e.,
10613   //    1.1. Vector is used only once.
10614   //    1.2. Use is a bit convert to an integer type.
10615   // 2. The size of its operands are 32-bits (64-bits are not legal).
10616   EVT VT = N->getValueType(0);
10617   EVT EltVT = VT.getVectorElementType();
10618 
10619   // Check 1.1. and 2.
10620   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
10621     return SDValue();
10622 
10623   // By construction, the input type must be float.
10624   assert(EltVT == MVT::f32 && "Unexpected type!");
10625 
10626   // Check 1.2.
10627   SDNode *Use = *N->use_begin();
10628   if (Use->getOpcode() != ISD::BITCAST ||
10629       Use->getValueType(0).isFloatingPoint())
10630     return SDValue();
10631 
10632   // Check profitability.
10633   // Model is, if more than half of the relevant operands are bitcast from
10634   // i32, turn the build_vector into a sequence of insert_vector_elt.
10635   // Relevant operands are everything that is not statically
10636   // (i.e., at compile time) bitcasted.
10637   unsigned NumOfBitCastedElts = 0;
10638   unsigned NumElts = VT.getVectorNumElements();
10639   unsigned NumOfRelevantElts = NumElts;
10640   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
10641     SDValue Elt = N->getOperand(Idx);
10642     if (Elt->getOpcode() == ISD::BITCAST) {
10643       // Assume only bit cast to i32 will go away.
10644       if (Elt->getOperand(0).getValueType() == MVT::i32)
10645         ++NumOfBitCastedElts;
10646     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
10647       // Constants are statically casted, thus do not count them as
10648       // relevant operands.
10649       --NumOfRelevantElts;
10650   }
10651 
10652   // Check if more than half of the elements require a non-free bitcast.
10653   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
10654     return SDValue();
10655 
10656   SelectionDAG &DAG = DCI.DAG;
10657   // Create the new vector type.
10658   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
10659   // Check if the type is legal.
10660   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10661   if (!TLI.isTypeLegal(VecVT))
10662     return SDValue();
10663 
10664   // Combine:
10665   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
10666   // => BITCAST INSERT_VECTOR_ELT
10667   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
10668   //                      (BITCAST EN), N.
10669   SDValue Vec = DAG.getUNDEF(VecVT);
10670   SDLoc dl(N);
10671   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
10672     SDValue V = N->getOperand(Idx);
10673     if (V.isUndef())
10674       continue;
10675     if (V.getOpcode() == ISD::BITCAST &&
10676         V->getOperand(0).getValueType() == MVT::i32)
10677       // Fold obvious case.
10678       V = V.getOperand(0);
10679     else {
10680       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
10681       // Make the DAGCombiner fold the bitcasts.
10682       DCI.AddToWorklist(V.getNode());
10683     }
10684     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
10685     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
10686   }
10687   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
10688   // Make the DAGCombiner fold the bitcasts.
10689   DCI.AddToWorklist(Vec.getNode());
10690   return Vec;
10691 }
10692 
10693 /// PerformInsertEltCombine - Target-specific dag combine xforms for
10694 /// ISD::INSERT_VECTOR_ELT.
10695 static SDValue PerformInsertEltCombine(SDNode *N,
10696                                        TargetLowering::DAGCombinerInfo &DCI) {
10697   // Bitcast an i64 load inserted into a vector to f64.
10698   // Otherwise, the i64 value will be legalized to a pair of i32 values.
10699   EVT VT = N->getValueType(0);
10700   SDNode *Elt = N->getOperand(1).getNode();
10701   if (VT.getVectorElementType() != MVT::i64 ||
10702       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
10703     return SDValue();
10704 
10705   SelectionDAG &DAG = DCI.DAG;
10706   SDLoc dl(N);
10707   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10708                                  VT.getVectorNumElements());
10709   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
10710   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
10711   // Make the DAGCombiner fold the bitcasts.
10712   DCI.AddToWorklist(Vec.getNode());
10713   DCI.AddToWorklist(V.getNode());
10714   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
10715                                Vec, V, N->getOperand(2));
10716   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
10717 }
10718 
10719 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
10720 /// ISD::VECTOR_SHUFFLE.
10721 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
10722   // The LLVM shufflevector instruction does not require the shuffle mask
10723   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
10724   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
10725   // operands do not match the mask length, they are extended by concatenating
10726   // them with undef vectors.  That is probably the right thing for other
10727   // targets, but for NEON it is better to concatenate two double-register
10728   // size vector operands into a single quad-register size vector.  Do that
10729   // transformation here:
10730   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
10731   //   shuffle(concat(v1, v2), undef)
10732   SDValue Op0 = N->getOperand(0);
10733   SDValue Op1 = N->getOperand(1);
10734   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
10735       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
10736       Op0.getNumOperands() != 2 ||
10737       Op1.getNumOperands() != 2)
10738     return SDValue();
10739   SDValue Concat0Op1 = Op0.getOperand(1);
10740   SDValue Concat1Op1 = Op1.getOperand(1);
10741   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
10742     return SDValue();
10743   // Skip the transformation if any of the types are illegal.
10744   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10745   EVT VT = N->getValueType(0);
10746   if (!TLI.isTypeLegal(VT) ||
10747       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
10748       !TLI.isTypeLegal(Concat1Op1.getValueType()))
10749     return SDValue();
10750 
10751   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10752                                   Op0.getOperand(0), Op1.getOperand(0));
10753   // Translate the shuffle mask.
10754   SmallVector<int, 16> NewMask;
10755   unsigned NumElts = VT.getVectorNumElements();
10756   unsigned HalfElts = NumElts/2;
10757   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10758   for (unsigned n = 0; n < NumElts; ++n) {
10759     int MaskElt = SVN->getMaskElt(n);
10760     int NewElt = -1;
10761     if (MaskElt < (int)HalfElts)
10762       NewElt = MaskElt;
10763     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
10764       NewElt = HalfElts + MaskElt - NumElts;
10765     NewMask.push_back(NewElt);
10766   }
10767   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
10768                               DAG.getUNDEF(VT), NewMask);
10769 }
10770 
10771 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
10772 /// NEON load/store intrinsics, and generic vector load/stores, to merge
10773 /// base address updates.
10774 /// For generic load/stores, the memory type is assumed to be a vector.
10775 /// The caller is assumed to have checked legality.
10776 static SDValue CombineBaseUpdate(SDNode *N,
10777                                  TargetLowering::DAGCombinerInfo &DCI) {
10778   SelectionDAG &DAG = DCI.DAG;
10779   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
10780                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
10781   const bool isStore = N->getOpcode() == ISD::STORE;
10782   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
10783   SDValue Addr = N->getOperand(AddrOpIdx);
10784   MemSDNode *MemN = cast<MemSDNode>(N);
10785   SDLoc dl(N);
10786 
10787   // Search for a use of the address operand that is an increment.
10788   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10789          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10790     SDNode *User = *UI;
10791     if (User->getOpcode() != ISD::ADD ||
10792         UI.getUse().getResNo() != Addr.getResNo())
10793       continue;
10794 
10795     // Check that the add is independent of the load/store.  Otherwise, folding
10796     // it would create a cycle.
10797     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
10798       continue;
10799 
10800     // Find the new opcode for the updating load/store.
10801     bool isLoadOp = true;
10802     bool isLaneOp = false;
10803     unsigned NewOpc = 0;
10804     unsigned NumVecs = 0;
10805     if (isIntrinsic) {
10806       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10807       switch (IntNo) {
10808       default: llvm_unreachable("unexpected intrinsic for Neon base update");
10809       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
10810         NumVecs = 1; break;
10811       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
10812         NumVecs = 2; break;
10813       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
10814         NumVecs = 3; break;
10815       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
10816         NumVecs = 4; break;
10817       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
10818         NumVecs = 2; isLaneOp = true; break;
10819       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
10820         NumVecs = 3; isLaneOp = true; break;
10821       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
10822         NumVecs = 4; isLaneOp = true; break;
10823       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
10824         NumVecs = 1; isLoadOp = false; break;
10825       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
10826         NumVecs = 2; isLoadOp = false; break;
10827       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
10828         NumVecs = 3; isLoadOp = false; break;
10829       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
10830         NumVecs = 4; isLoadOp = false; break;
10831       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
10832         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
10833       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
10834         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
10835       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
10836         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
10837       }
10838     } else {
10839       isLaneOp = true;
10840       switch (N->getOpcode()) {
10841       default: llvm_unreachable("unexpected opcode for Neon base update");
10842       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
10843       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
10844       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
10845       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
10846       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
10847         NumVecs = 1; isLaneOp = false; break;
10848       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
10849         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
10850       }
10851     }
10852 
10853     // Find the size of memory referenced by the load/store.
10854     EVT VecTy;
10855     if (isLoadOp) {
10856       VecTy = N->getValueType(0);
10857     } else if (isIntrinsic) {
10858       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
10859     } else {
10860       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
10861       VecTy = N->getOperand(1).getValueType();
10862     }
10863 
10864     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
10865     if (isLaneOp)
10866       NumBytes /= VecTy.getVectorNumElements();
10867 
10868     // If the increment is a constant, it must match the memory ref size.
10869     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
10870     if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
10871       uint64_t IncVal = CInc->getZExtValue();
10872       if (IncVal != NumBytes)
10873         continue;
10874     } else if (NumBytes >= 3 * 16) {
10875       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
10876       // separate instructions that make it harder to use a non-constant update.
10877       continue;
10878     }
10879 
10880     // OK, we found an ADD we can fold into the base update.
10881     // Now, create a _UPD node, taking care of not breaking alignment.
10882 
10883     EVT AlignedVecTy = VecTy;
10884     unsigned Alignment = MemN->getAlignment();
10885 
10886     // If this is a less-than-standard-aligned load/store, change the type to
10887     // match the standard alignment.
10888     // The alignment is overlooked when selecting _UPD variants; and it's
10889     // easier to introduce bitcasts here than fix that.
10890     // There are 3 ways to get to this base-update combine:
10891     // - intrinsics: they are assumed to be properly aligned (to the standard
10892     //   alignment of the memory type), so we don't need to do anything.
10893     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
10894     //   intrinsics, so, likewise, there's nothing to do.
10895     // - generic load/store instructions: the alignment is specified as an
10896     //   explicit operand, rather than implicitly as the standard alignment
10897     //   of the memory type (like the intrisics).  We need to change the
10898     //   memory type to match the explicit alignment.  That way, we don't
10899     //   generate non-standard-aligned ARMISD::VLDx nodes.
10900     if (isa<LSBaseSDNode>(N)) {
10901       if (Alignment == 0)
10902         Alignment = 1;
10903       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
10904         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
10905         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
10906         assert(!isLaneOp && "Unexpected generic load/store lane.");
10907         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
10908         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
10909       }
10910       // Don't set an explicit alignment on regular load/stores that we want
10911       // to transform to VLD/VST 1_UPD nodes.
10912       // This matches the behavior of regular load/stores, which only get an
10913       // explicit alignment if the MMO alignment is larger than the standard
10914       // alignment of the memory type.
10915       // Intrinsics, however, always get an explicit alignment, set to the
10916       // alignment of the MMO.
10917       Alignment = 1;
10918     }
10919 
10920     // Create the new updating load/store node.
10921     // First, create an SDVTList for the new updating node's results.
10922     EVT Tys[6];
10923     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
10924     unsigned n;
10925     for (n = 0; n < NumResultVecs; ++n)
10926       Tys[n] = AlignedVecTy;
10927     Tys[n++] = MVT::i32;
10928     Tys[n] = MVT::Other;
10929     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
10930 
10931     // Then, gather the new node's operands.
10932     SmallVector<SDValue, 8> Ops;
10933     Ops.push_back(N->getOperand(0)); // incoming chain
10934     Ops.push_back(N->getOperand(AddrOpIdx));
10935     Ops.push_back(Inc);
10936 
10937     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
10938       // Try to match the intrinsic's signature
10939       Ops.push_back(StN->getValue());
10940     } else {
10941       // Loads (and of course intrinsics) match the intrinsics' signature,
10942       // so just add all but the alignment operand.
10943       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
10944         Ops.push_back(N->getOperand(i));
10945     }
10946 
10947     // For all node types, the alignment operand is always the last one.
10948     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
10949 
10950     // If this is a non-standard-aligned STORE, the penultimate operand is the
10951     // stored value.  Bitcast it to the aligned type.
10952     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
10953       SDValue &StVal = Ops[Ops.size()-2];
10954       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
10955     }
10956 
10957     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
10958     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
10959                                            MemN->getMemOperand());
10960 
10961     // Update the uses.
10962     SmallVector<SDValue, 5> NewResults;
10963     for (unsigned i = 0; i < NumResultVecs; ++i)
10964       NewResults.push_back(SDValue(UpdN.getNode(), i));
10965 
10966     // If this is an non-standard-aligned LOAD, the first result is the loaded
10967     // value.  Bitcast it to the expected result type.
10968     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
10969       SDValue &LdVal = NewResults[0];
10970       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
10971     }
10972 
10973     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
10974     DCI.CombineTo(N, NewResults);
10975     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
10976 
10977     break;
10978   }
10979   return SDValue();
10980 }
10981 
10982 static SDValue PerformVLDCombine(SDNode *N,
10983                                  TargetLowering::DAGCombinerInfo &DCI) {
10984   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10985     return SDValue();
10986 
10987   return CombineBaseUpdate(N, DCI);
10988 }
10989 
10990 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
10991 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
10992 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
10993 /// return true.
10994 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10995   SelectionDAG &DAG = DCI.DAG;
10996   EVT VT = N->getValueType(0);
10997   // vldN-dup instructions only support 64-bit vectors for N > 1.
10998   if (!VT.is64BitVector())
10999     return false;
11000 
11001   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11002   SDNode *VLD = N->getOperand(0).getNode();
11003   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11004     return false;
11005   unsigned NumVecs = 0;
11006   unsigned NewOpc = 0;
11007   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11008   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11009     NumVecs = 2;
11010     NewOpc = ARMISD::VLD2DUP;
11011   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11012     NumVecs = 3;
11013     NewOpc = ARMISD::VLD3DUP;
11014   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11015     NumVecs = 4;
11016     NewOpc = ARMISD::VLD4DUP;
11017   } else {
11018     return false;
11019   }
11020 
11021   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11022   // numbers match the load.
11023   unsigned VLDLaneNo =
11024     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11025   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11026        UI != UE; ++UI) {
11027     // Ignore uses of the chain result.
11028     if (UI.getUse().getResNo() == NumVecs)
11029       continue;
11030     SDNode *User = *UI;
11031     if (User->getOpcode() != ARMISD::VDUPLANE ||
11032         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11033       return false;
11034   }
11035 
11036   // Create the vldN-dup node.
11037   EVT Tys[5];
11038   unsigned n;
11039   for (n = 0; n < NumVecs; ++n)
11040     Tys[n] = VT;
11041   Tys[n] = MVT::Other;
11042   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11043   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11044   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11045   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11046                                            Ops, VLDMemInt->getMemoryVT(),
11047                                            VLDMemInt->getMemOperand());
11048 
11049   // Update the uses.
11050   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11051        UI != UE; ++UI) {
11052     unsigned ResNo = UI.getUse().getResNo();
11053     // Ignore uses of the chain result.
11054     if (ResNo == NumVecs)
11055       continue;
11056     SDNode *User = *UI;
11057     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11058   }
11059 
11060   // Now the vldN-lane intrinsic is dead except for its chain result.
11061   // Update uses of the chain.
11062   std::vector<SDValue> VLDDupResults;
11063   for (unsigned n = 0; n < NumVecs; ++n)
11064     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11065   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11066   DCI.CombineTo(VLD, VLDDupResults);
11067 
11068   return true;
11069 }
11070 
11071 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11072 /// ARMISD::VDUPLANE.
11073 static SDValue PerformVDUPLANECombine(SDNode *N,
11074                                       TargetLowering::DAGCombinerInfo &DCI) {
11075   SDValue Op = N->getOperand(0);
11076 
11077   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11078   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11079   if (CombineVLDDUP(N, DCI))
11080     return SDValue(N, 0);
11081 
11082   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11083   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11084   while (Op.getOpcode() == ISD::BITCAST)
11085     Op = Op.getOperand(0);
11086   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11087     return SDValue();
11088 
11089   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11090   unsigned EltSize = Op.getScalarValueSizeInBits();
11091   // The canonical VMOV for a zero vector uses a 32-bit element size.
11092   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11093   unsigned EltBits;
11094   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11095     EltSize = 8;
11096   EVT VT = N->getValueType(0);
11097   if (EltSize > VT.getScalarSizeInBits())
11098     return SDValue();
11099 
11100   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11101 }
11102 
11103 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11104 static SDValue PerformVDUPCombine(SDNode *N,
11105                                   TargetLowering::DAGCombinerInfo &DCI) {
11106   SelectionDAG &DAG = DCI.DAG;
11107   SDValue Op = N->getOperand(0);
11108 
11109   // Match VDUP(LOAD) -> VLD1DUP.
11110   // We match this pattern here rather than waiting for isel because the
11111   // transform is only legal for unindexed loads.
11112   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11113   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11114       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11115     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11116                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11117     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11118     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11119                                              Ops, LD->getMemoryVT(),
11120                                              LD->getMemOperand());
11121     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11122     return VLDDup;
11123   }
11124 
11125   return SDValue();
11126 }
11127 
11128 static SDValue PerformLOADCombine(SDNode *N,
11129                                   TargetLowering::DAGCombinerInfo &DCI) {
11130   EVT VT = N->getValueType(0);
11131 
11132   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11133   if (ISD::isNormalLoad(N) && VT.isVector() &&
11134       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11135     return CombineBaseUpdate(N, DCI);
11136 
11137   return SDValue();
11138 }
11139 
11140 /// PerformSTORECombine - Target-specific dag combine xforms for
11141 /// ISD::STORE.
11142 static SDValue PerformSTORECombine(SDNode *N,
11143                                    TargetLowering::DAGCombinerInfo &DCI) {
11144   StoreSDNode *St = cast<StoreSDNode>(N);
11145   if (St->isVolatile())
11146     return SDValue();
11147 
11148   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11149   // pack all of the elements in one place.  Next, store to memory in fewer
11150   // chunks.
11151   SDValue StVal = St->getValue();
11152   EVT VT = StVal.getValueType();
11153   if (St->isTruncatingStore() && VT.isVector()) {
11154     SelectionDAG &DAG = DCI.DAG;
11155     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11156     EVT StVT = St->getMemoryVT();
11157     unsigned NumElems = VT.getVectorNumElements();
11158     assert(StVT != VT && "Cannot truncate to the same type");
11159     unsigned FromEltSz = VT.getScalarSizeInBits();
11160     unsigned ToEltSz = StVT.getScalarSizeInBits();
11161 
11162     // From, To sizes and ElemCount must be pow of two
11163     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11164 
11165     // We are going to use the original vector elt for storing.
11166     // Accumulated smaller vector elements must be a multiple of the store size.
11167     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11168 
11169     unsigned SizeRatio  = FromEltSz / ToEltSz;
11170     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11171 
11172     // Create a type on which we perform the shuffle.
11173     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11174                                      NumElems*SizeRatio);
11175     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11176 
11177     SDLoc DL(St);
11178     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11179     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11180     for (unsigned i = 0; i < NumElems; ++i)
11181       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11182                           ? (i + 1) * SizeRatio - 1
11183                           : i * SizeRatio;
11184 
11185     // Can't shuffle using an illegal type.
11186     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11187 
11188     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11189                                 DAG.getUNDEF(WideVec.getValueType()),
11190                                 ShuffleVec);
11191     // At this point all of the data is stored at the bottom of the
11192     // register. We now need to save it to mem.
11193 
11194     // Find the largest store unit
11195     MVT StoreType = MVT::i8;
11196     for (MVT Tp : MVT::integer_valuetypes()) {
11197       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11198         StoreType = Tp;
11199     }
11200     // Didn't find a legal store type.
11201     if (!TLI.isTypeLegal(StoreType))
11202       return SDValue();
11203 
11204     // Bitcast the original vector into a vector of store-size units
11205     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11206             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11207     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11208     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11209     SmallVector<SDValue, 8> Chains;
11210     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11211                                         TLI.getPointerTy(DAG.getDataLayout()));
11212     SDValue BasePtr = St->getBasePtr();
11213 
11214     // Perform one or more big stores into memory.
11215     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11216     for (unsigned I = 0; I < E; I++) {
11217       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11218                                    StoreType, ShuffWide,
11219                                    DAG.getIntPtrConstant(I, DL));
11220       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
11221                                 St->getPointerInfo(), St->getAlignment(),
11222                                 St->getMemOperand()->getFlags());
11223       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
11224                             Increment);
11225       Chains.push_back(Ch);
11226     }
11227     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11228   }
11229 
11230   if (!ISD::isNormalStore(St))
11231     return SDValue();
11232 
11233   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
11234   // ARM stores of arguments in the same cache line.
11235   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
11236       StVal.getNode()->hasOneUse()) {
11237     SelectionDAG  &DAG = DCI.DAG;
11238     bool isBigEndian = DAG.getDataLayout().isBigEndian();
11239     SDLoc DL(St);
11240     SDValue BasePtr = St->getBasePtr();
11241     SDValue NewST1 = DAG.getStore(
11242         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
11243         BasePtr, St->getPointerInfo(), St->getAlignment(),
11244         St->getMemOperand()->getFlags());
11245 
11246     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11247                                     DAG.getConstant(4, DL, MVT::i32));
11248     return DAG.getStore(NewST1.getValue(0), DL,
11249                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
11250                         OffsetPtr, St->getPointerInfo(),
11251                         std::min(4U, St->getAlignment() / 2),
11252                         St->getMemOperand()->getFlags());
11253   }
11254 
11255   if (StVal.getValueType() == MVT::i64 &&
11256       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11257 
11258     // Bitcast an i64 store extracted from a vector to f64.
11259     // Otherwise, the i64 value will be legalized to a pair of i32 values.
11260     SelectionDAG &DAG = DCI.DAG;
11261     SDLoc dl(StVal);
11262     SDValue IntVec = StVal.getOperand(0);
11263     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11264                                    IntVec.getValueType().getVectorNumElements());
11265     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
11266     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11267                                  Vec, StVal.getOperand(1));
11268     dl = SDLoc(N);
11269     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
11270     // Make the DAGCombiner fold the bitcasts.
11271     DCI.AddToWorklist(Vec.getNode());
11272     DCI.AddToWorklist(ExtElt.getNode());
11273     DCI.AddToWorklist(V.getNode());
11274     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
11275                         St->getPointerInfo(), St->getAlignment(),
11276                         St->getMemOperand()->getFlags(), St->getAAInfo());
11277   }
11278 
11279   // If this is a legal vector store, try to combine it into a VST1_UPD.
11280   if (ISD::isNormalStore(N) && VT.isVector() &&
11281       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11282     return CombineBaseUpdate(N, DCI);
11283 
11284   return SDValue();
11285 }
11286 
11287 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11288 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11289 /// when the VMUL has a constant operand that is a power of 2.
11290 ///
11291 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11292 ///  vmul.f32        d16, d17, d16
11293 ///  vcvt.s32.f32    d16, d16
11294 /// becomes:
11295 ///  vcvt.s32.f32    d16, d16, #3
11296 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11297                                   const ARMSubtarget *Subtarget) {
11298   if (!Subtarget->hasNEON())
11299     return SDValue();
11300 
11301   SDValue Op = N->getOperand(0);
11302   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11303       Op.getOpcode() != ISD::FMUL)
11304     return SDValue();
11305 
11306   SDValue ConstVec = Op->getOperand(1);
11307   if (!isa<BuildVectorSDNode>(ConstVec))
11308     return SDValue();
11309 
11310   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11311   uint32_t FloatBits = FloatTy.getSizeInBits();
11312   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11313   uint32_t IntBits = IntTy.getSizeInBits();
11314   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11315   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11316     // These instructions only exist converting from f32 to i32. We can handle
11317     // smaller integers by generating an extra truncate, but larger ones would
11318     // be lossy. We also can't handle more then 4 lanes, since these intructions
11319     // only support v2i32/v4i32 types.
11320     return SDValue();
11321   }
11322 
11323   BitVector UndefElements;
11324   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11325   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11326   if (C == -1 || C == 0 || C > 32)
11327     return SDValue();
11328 
11329   SDLoc dl(N);
11330   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
11331   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
11332     Intrinsic::arm_neon_vcvtfp2fxu;
11333   SDValue FixConv = DAG.getNode(
11334       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11335       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
11336       DAG.getConstant(C, dl, MVT::i32));
11337 
11338   if (IntBits < FloatBits)
11339     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
11340 
11341   return FixConv;
11342 }
11343 
11344 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
11345 /// can replace combinations of VCVT (integer to floating-point) and VDIV
11346 /// when the VDIV has a constant operand that is a power of 2.
11347 ///
11348 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11349 ///  vcvt.f32.s32    d16, d16
11350 ///  vdiv.f32        d16, d17, d16
11351 /// becomes:
11352 ///  vcvt.f32.s32    d16, d16, #3
11353 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
11354                                   const ARMSubtarget *Subtarget) {
11355   if (!Subtarget->hasNEON())
11356     return SDValue();
11357 
11358   SDValue Op = N->getOperand(0);
11359   unsigned OpOpcode = Op.getNode()->getOpcode();
11360   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
11361       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
11362     return SDValue();
11363 
11364   SDValue ConstVec = N->getOperand(1);
11365   if (!isa<BuildVectorSDNode>(ConstVec))
11366     return SDValue();
11367 
11368   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11369   uint32_t FloatBits = FloatTy.getSizeInBits();
11370   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11371   uint32_t IntBits = IntTy.getSizeInBits();
11372   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11373   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11374     // These instructions only exist converting from i32 to f32. We can handle
11375     // smaller integers by generating an extra extend, but larger ones would
11376     // be lossy. We also can't handle more then 4 lanes, since these intructions
11377     // only support v2i32/v4i32 types.
11378     return SDValue();
11379   }
11380 
11381   BitVector UndefElements;
11382   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11383   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11384   if (C == -1 || C == 0 || C > 32)
11385     return SDValue();
11386 
11387   SDLoc dl(N);
11388   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
11389   SDValue ConvInput = Op.getOperand(0);
11390   if (IntBits < FloatBits)
11391     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
11392                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11393                             ConvInput);
11394 
11395   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
11396     Intrinsic::arm_neon_vcvtfxu2fp;
11397   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
11398                      Op.getValueType(),
11399                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
11400                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
11401 }
11402 
11403 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
11404 /// operand of a vector shift operation, where all the elements of the
11405 /// build_vector must have the same constant integer value.
11406 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
11407   // Ignore bit_converts.
11408   while (Op.getOpcode() == ISD::BITCAST)
11409     Op = Op.getOperand(0);
11410   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
11411   APInt SplatBits, SplatUndef;
11412   unsigned SplatBitSize;
11413   bool HasAnyUndefs;
11414   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
11415                                       HasAnyUndefs, ElementBits) ||
11416       SplatBitSize > ElementBits)
11417     return false;
11418   Cnt = SplatBits.getSExtValue();
11419   return true;
11420 }
11421 
11422 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
11423 /// operand of a vector shift left operation.  That value must be in the range:
11424 ///   0 <= Value < ElementBits for a left shift; or
11425 ///   0 <= Value <= ElementBits for a long left shift.
11426 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
11427   assert(VT.isVector() && "vector shift count is not a vector type");
11428   int64_t ElementBits = VT.getScalarSizeInBits();
11429   if (! getVShiftImm(Op, ElementBits, Cnt))
11430     return false;
11431   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
11432 }
11433 
11434 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
11435 /// operand of a vector shift right operation.  For a shift opcode, the value
11436 /// is positive, but for an intrinsic the value count must be negative. The
11437 /// absolute value must be in the range:
11438 ///   1 <= |Value| <= ElementBits for a right shift; or
11439 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
11440 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
11441                          int64_t &Cnt) {
11442   assert(VT.isVector() && "vector shift count is not a vector type");
11443   int64_t ElementBits = VT.getScalarSizeInBits();
11444   if (! getVShiftImm(Op, ElementBits, Cnt))
11445     return false;
11446   if (!isIntrinsic)
11447     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
11448   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
11449     Cnt = -Cnt;
11450     return true;
11451   }
11452   return false;
11453 }
11454 
11455 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
11456 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
11457   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11458   switch (IntNo) {
11459   default:
11460     // Don't do anything for most intrinsics.
11461     break;
11462 
11463   // Vector shifts: check for immediate versions and lower them.
11464   // Note: This is done during DAG combining instead of DAG legalizing because
11465   // the build_vectors for 64-bit vector element shift counts are generally
11466   // not legal, and it is hard to see their values after they get legalized to
11467   // loads from a constant pool.
11468   case Intrinsic::arm_neon_vshifts:
11469   case Intrinsic::arm_neon_vshiftu:
11470   case Intrinsic::arm_neon_vrshifts:
11471   case Intrinsic::arm_neon_vrshiftu:
11472   case Intrinsic::arm_neon_vrshiftn:
11473   case Intrinsic::arm_neon_vqshifts:
11474   case Intrinsic::arm_neon_vqshiftu:
11475   case Intrinsic::arm_neon_vqshiftsu:
11476   case Intrinsic::arm_neon_vqshiftns:
11477   case Intrinsic::arm_neon_vqshiftnu:
11478   case Intrinsic::arm_neon_vqshiftnsu:
11479   case Intrinsic::arm_neon_vqrshiftns:
11480   case Intrinsic::arm_neon_vqrshiftnu:
11481   case Intrinsic::arm_neon_vqrshiftnsu: {
11482     EVT VT = N->getOperand(1).getValueType();
11483     int64_t Cnt;
11484     unsigned VShiftOpc = 0;
11485 
11486     switch (IntNo) {
11487     case Intrinsic::arm_neon_vshifts:
11488     case Intrinsic::arm_neon_vshiftu:
11489       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
11490         VShiftOpc = ARMISD::VSHL;
11491         break;
11492       }
11493       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
11494         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
11495                      ARMISD::VSHRs : ARMISD::VSHRu);
11496         break;
11497       }
11498       return SDValue();
11499 
11500     case Intrinsic::arm_neon_vrshifts:
11501     case Intrinsic::arm_neon_vrshiftu:
11502       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
11503         break;
11504       return SDValue();
11505 
11506     case Intrinsic::arm_neon_vqshifts:
11507     case Intrinsic::arm_neon_vqshiftu:
11508       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11509         break;
11510       return SDValue();
11511 
11512     case Intrinsic::arm_neon_vqshiftsu:
11513       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11514         break;
11515       llvm_unreachable("invalid shift count for vqshlu intrinsic");
11516 
11517     case Intrinsic::arm_neon_vrshiftn:
11518     case Intrinsic::arm_neon_vqshiftns:
11519     case Intrinsic::arm_neon_vqshiftnu:
11520     case Intrinsic::arm_neon_vqshiftnsu:
11521     case Intrinsic::arm_neon_vqrshiftns:
11522     case Intrinsic::arm_neon_vqrshiftnu:
11523     case Intrinsic::arm_neon_vqrshiftnsu:
11524       // Narrowing shifts require an immediate right shift.
11525       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
11526         break;
11527       llvm_unreachable("invalid shift count for narrowing vector shift "
11528                        "intrinsic");
11529 
11530     default:
11531       llvm_unreachable("unhandled vector shift");
11532     }
11533 
11534     switch (IntNo) {
11535     case Intrinsic::arm_neon_vshifts:
11536     case Intrinsic::arm_neon_vshiftu:
11537       // Opcode already set above.
11538       break;
11539     case Intrinsic::arm_neon_vrshifts:
11540       VShiftOpc = ARMISD::VRSHRs; break;
11541     case Intrinsic::arm_neon_vrshiftu:
11542       VShiftOpc = ARMISD::VRSHRu; break;
11543     case Intrinsic::arm_neon_vrshiftn:
11544       VShiftOpc = ARMISD::VRSHRN; break;
11545     case Intrinsic::arm_neon_vqshifts:
11546       VShiftOpc = ARMISD::VQSHLs; break;
11547     case Intrinsic::arm_neon_vqshiftu:
11548       VShiftOpc = ARMISD::VQSHLu; break;
11549     case Intrinsic::arm_neon_vqshiftsu:
11550       VShiftOpc = ARMISD::VQSHLsu; break;
11551     case Intrinsic::arm_neon_vqshiftns:
11552       VShiftOpc = ARMISD::VQSHRNs; break;
11553     case Intrinsic::arm_neon_vqshiftnu:
11554       VShiftOpc = ARMISD::VQSHRNu; break;
11555     case Intrinsic::arm_neon_vqshiftnsu:
11556       VShiftOpc = ARMISD::VQSHRNsu; break;
11557     case Intrinsic::arm_neon_vqrshiftns:
11558       VShiftOpc = ARMISD::VQRSHRNs; break;
11559     case Intrinsic::arm_neon_vqrshiftnu:
11560       VShiftOpc = ARMISD::VQRSHRNu; break;
11561     case Intrinsic::arm_neon_vqrshiftnsu:
11562       VShiftOpc = ARMISD::VQRSHRNsu; break;
11563     }
11564 
11565     SDLoc dl(N);
11566     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11567                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
11568   }
11569 
11570   case Intrinsic::arm_neon_vshiftins: {
11571     EVT VT = N->getOperand(1).getValueType();
11572     int64_t Cnt;
11573     unsigned VShiftOpc = 0;
11574 
11575     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
11576       VShiftOpc = ARMISD::VSLI;
11577     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
11578       VShiftOpc = ARMISD::VSRI;
11579     else {
11580       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
11581     }
11582 
11583     SDLoc dl(N);
11584     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11585                        N->getOperand(1), N->getOperand(2),
11586                        DAG.getConstant(Cnt, dl, MVT::i32));
11587   }
11588 
11589   case Intrinsic::arm_neon_vqrshifts:
11590   case Intrinsic::arm_neon_vqrshiftu:
11591     // No immediate versions of these to check for.
11592     break;
11593   }
11594 
11595   return SDValue();
11596 }
11597 
11598 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
11599 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
11600 /// combining instead of DAG legalizing because the build_vectors for 64-bit
11601 /// vector element shift counts are generally not legal, and it is hard to see
11602 /// their values after they get legalized to loads from a constant pool.
11603 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
11604                                    const ARMSubtarget *ST) {
11605   EVT VT = N->getValueType(0);
11606   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
11607     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
11608     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
11609     SDValue N1 = N->getOperand(1);
11610     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11611       SDValue N0 = N->getOperand(0);
11612       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
11613           DAG.MaskedValueIsZero(N0.getOperand(0),
11614                                 APInt::getHighBitsSet(32, 16)))
11615         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
11616     }
11617   }
11618 
11619   // Nothing to be done for scalar shifts.
11620   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11621   if (!VT.isVector() || !TLI.isTypeLegal(VT))
11622     return SDValue();
11623 
11624   assert(ST->hasNEON() && "unexpected vector shift");
11625   int64_t Cnt;
11626 
11627   switch (N->getOpcode()) {
11628   default: llvm_unreachable("unexpected shift opcode");
11629 
11630   case ISD::SHL:
11631     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
11632       SDLoc dl(N);
11633       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
11634                          DAG.getConstant(Cnt, dl, MVT::i32));
11635     }
11636     break;
11637 
11638   case ISD::SRA:
11639   case ISD::SRL:
11640     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
11641       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
11642                             ARMISD::VSHRs : ARMISD::VSHRu);
11643       SDLoc dl(N);
11644       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
11645                          DAG.getConstant(Cnt, dl, MVT::i32));
11646     }
11647   }
11648   return SDValue();
11649 }
11650 
11651 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
11652 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
11653 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
11654                                     const ARMSubtarget *ST) {
11655   SDValue N0 = N->getOperand(0);
11656 
11657   // Check for sign- and zero-extensions of vector extract operations of 8-
11658   // and 16-bit vector elements.  NEON supports these directly.  They are
11659   // handled during DAG combining because type legalization will promote them
11660   // to 32-bit types and it is messy to recognize the operations after that.
11661   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11662     SDValue Vec = N0.getOperand(0);
11663     SDValue Lane = N0.getOperand(1);
11664     EVT VT = N->getValueType(0);
11665     EVT EltVT = N0.getValueType();
11666     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11667 
11668     if (VT == MVT::i32 &&
11669         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
11670         TLI.isTypeLegal(Vec.getValueType()) &&
11671         isa<ConstantSDNode>(Lane)) {
11672 
11673       unsigned Opc = 0;
11674       switch (N->getOpcode()) {
11675       default: llvm_unreachable("unexpected opcode");
11676       case ISD::SIGN_EXTEND:
11677         Opc = ARMISD::VGETLANEs;
11678         break;
11679       case ISD::ZERO_EXTEND:
11680       case ISD::ANY_EXTEND:
11681         Opc = ARMISD::VGETLANEu;
11682         break;
11683       }
11684       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
11685     }
11686   }
11687 
11688   return SDValue();
11689 }
11690 
11691 static void computeKnownBits(SelectionDAG &DAG, SDValue Op, APInt &KnownZero,
11692                              APInt &KnownOne) {
11693   if (Op.getOpcode() == ARMISD::BFI) {
11694     // Conservatively, we can recurse down the first operand
11695     // and just mask out all affected bits.
11696     computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
11697 
11698     // The operand to BFI is already a mask suitable for removing the bits it
11699     // sets.
11700     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
11701     const APInt &Mask = CI->getAPIntValue();
11702     KnownZero &= Mask;
11703     KnownOne &= Mask;
11704     return;
11705   }
11706   if (Op.getOpcode() == ARMISD::CMOV) {
11707     APInt KZ2(KnownZero.getBitWidth(), 0);
11708     APInt KO2(KnownOne.getBitWidth(), 0);
11709     computeKnownBits(DAG, Op.getOperand(0), KnownZero, KnownOne);
11710     computeKnownBits(DAG, Op.getOperand(1), KZ2, KO2);
11711 
11712     KnownZero &= KZ2;
11713     KnownOne &= KO2;
11714     return;
11715   }
11716   return DAG.computeKnownBits(Op, KnownZero, KnownOne);
11717 }
11718 
11719 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
11720   // If we have a CMOV, OR and AND combination such as:
11721   //   if (x & CN)
11722   //     y |= CM;
11723   //
11724   // And:
11725   //   * CN is a single bit;
11726   //   * All bits covered by CM are known zero in y
11727   //
11728   // Then we can convert this into a sequence of BFI instructions. This will
11729   // always be a win if CM is a single bit, will always be no worse than the
11730   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
11731   // three bits (due to the extra IT instruction).
11732 
11733   SDValue Op0 = CMOV->getOperand(0);
11734   SDValue Op1 = CMOV->getOperand(1);
11735   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
11736   auto CC = CCNode->getAPIntValue().getLimitedValue();
11737   SDValue CmpZ = CMOV->getOperand(4);
11738 
11739   // The compare must be against zero.
11740   if (!isNullConstant(CmpZ->getOperand(1)))
11741     return SDValue();
11742 
11743   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
11744   SDValue And = CmpZ->getOperand(0);
11745   if (And->getOpcode() != ISD::AND)
11746     return SDValue();
11747   ConstantSDNode *AndC = dyn_cast<ConstantSDNode>(And->getOperand(1));
11748   if (!AndC || !AndC->getAPIntValue().isPowerOf2())
11749     return SDValue();
11750   SDValue X = And->getOperand(0);
11751 
11752   if (CC == ARMCC::EQ) {
11753     // We're performing an "equal to zero" compare. Swap the operands so we
11754     // canonicalize on a "not equal to zero" compare.
11755     std::swap(Op0, Op1);
11756   } else {
11757     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
11758   }
11759 
11760   if (Op1->getOpcode() != ISD::OR)
11761     return SDValue();
11762 
11763   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
11764   if (!OrC)
11765     return SDValue();
11766   SDValue Y = Op1->getOperand(0);
11767 
11768   if (Op0 != Y)
11769     return SDValue();
11770 
11771   // Now, is it profitable to continue?
11772   APInt OrCI = OrC->getAPIntValue();
11773   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
11774   if (OrCI.countPopulation() > Heuristic)
11775     return SDValue();
11776 
11777   // Lastly, can we determine that the bits defined by OrCI
11778   // are zero in Y?
11779   APInt KnownZero, KnownOne;
11780   computeKnownBits(DAG, Y, KnownZero, KnownOne);
11781   if ((OrCI & KnownZero) != OrCI)
11782     return SDValue();
11783 
11784   // OK, we can do the combine.
11785   SDValue V = Y;
11786   SDLoc dl(X);
11787   EVT VT = X.getValueType();
11788   unsigned BitInX = AndC->getAPIntValue().logBase2();
11789 
11790   if (BitInX != 0) {
11791     // We must shift X first.
11792     X = DAG.getNode(ISD::SRL, dl, VT, X,
11793                     DAG.getConstant(BitInX, dl, VT));
11794   }
11795 
11796   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
11797        BitInY < NumActiveBits; ++BitInY) {
11798     if (OrCI[BitInY] == 0)
11799       continue;
11800     APInt Mask(VT.getSizeInBits(), 0);
11801     Mask.setBit(BitInY);
11802     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
11803                     // Confusingly, the operand is an *inverted* mask.
11804                     DAG.getConstant(~Mask, dl, VT));
11805   }
11806 
11807   return V;
11808 }
11809 
11810 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
11811 SDValue
11812 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
11813   SDValue Cmp = N->getOperand(4);
11814   if (Cmp.getOpcode() != ARMISD::CMPZ)
11815     // Only looking at NE cases.
11816     return SDValue();
11817 
11818   EVT VT = N->getValueType(0);
11819   SDLoc dl(N);
11820   SDValue LHS = Cmp.getOperand(0);
11821   SDValue RHS = Cmp.getOperand(1);
11822   SDValue Chain = N->getOperand(0);
11823   SDValue BB = N->getOperand(1);
11824   SDValue ARMcc = N->getOperand(2);
11825   ARMCC::CondCodes CC =
11826     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11827 
11828   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
11829   // -> (brcond Chain BB CC CPSR Cmp)
11830   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
11831       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
11832       LHS->getOperand(0)->hasOneUse()) {
11833     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
11834     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
11835     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11836     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11837     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
11838         (LHS01C && LHS01C->getZExtValue() == 1) &&
11839         (LHS1C && LHS1C->getZExtValue() == 1) &&
11840         (RHSC && RHSC->getZExtValue() == 0)) {
11841       return DAG.getNode(
11842           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
11843           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
11844     }
11845   }
11846 
11847   return SDValue();
11848 }
11849 
11850 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
11851 SDValue
11852 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
11853   SDValue Cmp = N->getOperand(4);
11854   if (Cmp.getOpcode() != ARMISD::CMPZ)
11855     // Only looking at EQ and NE cases.
11856     return SDValue();
11857 
11858   EVT VT = N->getValueType(0);
11859   SDLoc dl(N);
11860   SDValue LHS = Cmp.getOperand(0);
11861   SDValue RHS = Cmp.getOperand(1);
11862   SDValue FalseVal = N->getOperand(0);
11863   SDValue TrueVal = N->getOperand(1);
11864   SDValue ARMcc = N->getOperand(2);
11865   ARMCC::CondCodes CC =
11866     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
11867 
11868   // BFI is only available on V6T2+.
11869   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
11870     SDValue R = PerformCMOVToBFICombine(N, DAG);
11871     if (R)
11872       return R;
11873   }
11874 
11875   // Simplify
11876   //   mov     r1, r0
11877   //   cmp     r1, x
11878   //   mov     r0, y
11879   //   moveq   r0, x
11880   // to
11881   //   cmp     r0, x
11882   //   movne   r0, y
11883   //
11884   //   mov     r1, r0
11885   //   cmp     r1, x
11886   //   mov     r0, x
11887   //   movne   r0, y
11888   // to
11889   //   cmp     r0, x
11890   //   movne   r0, y
11891   /// FIXME: Turn this into a target neutral optimization?
11892   SDValue Res;
11893   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
11894     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
11895                       N->getOperand(3), Cmp);
11896   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
11897     SDValue ARMcc;
11898     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
11899     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
11900                       N->getOperand(3), NewCmp);
11901   }
11902 
11903   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
11904   // -> (cmov F T CC CPSR Cmp)
11905   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
11906     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
11907     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
11908     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
11909     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
11910         (LHS1C && LHS1C->getZExtValue() == 1) &&
11911         (RHSC && RHSC->getZExtValue() == 0)) {
11912       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
11913                          LHS->getOperand(2), LHS->getOperand(3),
11914                          LHS->getOperand(4));
11915     }
11916   }
11917 
11918   if (Res.getNode()) {
11919     APInt KnownZero, KnownOne;
11920     DAG.computeKnownBits(SDValue(N,0), KnownZero, KnownOne);
11921     // Capture demanded bits information that would be otherwise lost.
11922     if (KnownZero == 0xfffffffe)
11923       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11924                         DAG.getValueType(MVT::i1));
11925     else if (KnownZero == 0xffffff00)
11926       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11927                         DAG.getValueType(MVT::i8));
11928     else if (KnownZero == 0xffff0000)
11929       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
11930                         DAG.getValueType(MVT::i16));
11931   }
11932 
11933   return Res;
11934 }
11935 
11936 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
11937                                              DAGCombinerInfo &DCI) const {
11938   switch (N->getOpcode()) {
11939   default: break;
11940   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
11941   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
11942   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
11943   case ISD::SUB:        return PerformSUBCombine(N, DCI);
11944   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
11945   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
11946   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
11947   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
11948   case ARMISD::ADDC:
11949   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI.DAG, Subtarget);
11950   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
11951   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
11952   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
11953   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
11954   case ISD::STORE:      return PerformSTORECombine(N, DCI);
11955   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
11956   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
11957   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
11958   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
11959   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
11960   case ISD::FP_TO_SINT:
11961   case ISD::FP_TO_UINT:
11962     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
11963   case ISD::FDIV:
11964     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
11965   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
11966   case ISD::SHL:
11967   case ISD::SRA:
11968   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
11969   case ISD::SIGN_EXTEND:
11970   case ISD::ZERO_EXTEND:
11971   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
11972   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
11973   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
11974   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
11975   case ARMISD::VLD1DUP:
11976   case ARMISD::VLD2DUP:
11977   case ARMISD::VLD3DUP:
11978   case ARMISD::VLD4DUP:
11979     return PerformVLDCombine(N, DCI);
11980   case ARMISD::BUILD_VECTOR:
11981     return PerformARMBUILD_VECTORCombine(N, DCI);
11982   case ARMISD::SMULWB: {
11983     unsigned BitWidth = N->getValueType(0).getSizeInBits();
11984     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
11985     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
11986       return SDValue();
11987     break;
11988   }
11989   case ARMISD::SMULWT: {
11990     unsigned BitWidth = N->getValueType(0).getSizeInBits();
11991     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
11992     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
11993       return SDValue();
11994     break;
11995   }
11996   case ARMISD::SMLALBB: {
11997     unsigned BitWidth = N->getValueType(0).getSizeInBits();
11998     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
11999     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12000         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12001       return SDValue();
12002     break;
12003   }
12004   case ARMISD::SMLALBT: {
12005     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12006     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12007     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12008     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12009     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12010         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12011       return SDValue();
12012     break;
12013   }
12014   case ARMISD::SMLALTB: {
12015     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12016     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12017     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12018     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12019     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12020         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12021       return SDValue();
12022     break;
12023   }
12024   case ARMISD::SMLALTT: {
12025     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12026     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12027     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12028         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12029       return SDValue();
12030     break;
12031   }
12032   case ISD::INTRINSIC_VOID:
12033   case ISD::INTRINSIC_W_CHAIN:
12034     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12035     case Intrinsic::arm_neon_vld1:
12036     case Intrinsic::arm_neon_vld2:
12037     case Intrinsic::arm_neon_vld3:
12038     case Intrinsic::arm_neon_vld4:
12039     case Intrinsic::arm_neon_vld2lane:
12040     case Intrinsic::arm_neon_vld3lane:
12041     case Intrinsic::arm_neon_vld4lane:
12042     case Intrinsic::arm_neon_vst1:
12043     case Intrinsic::arm_neon_vst2:
12044     case Intrinsic::arm_neon_vst3:
12045     case Intrinsic::arm_neon_vst4:
12046     case Intrinsic::arm_neon_vst2lane:
12047     case Intrinsic::arm_neon_vst3lane:
12048     case Intrinsic::arm_neon_vst4lane:
12049       return PerformVLDCombine(N, DCI);
12050     default: break;
12051     }
12052     break;
12053   }
12054   return SDValue();
12055 }
12056 
12057 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12058                                                           EVT VT) const {
12059   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12060 }
12061 
12062 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12063                                                        unsigned,
12064                                                        unsigned,
12065                                                        bool *Fast) const {
12066   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12067   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12068 
12069   switch (VT.getSimpleVT().SimpleTy) {
12070   default:
12071     return false;
12072   case MVT::i8:
12073   case MVT::i16:
12074   case MVT::i32: {
12075     // Unaligned access can use (for example) LRDB, LRDH, LDR
12076     if (AllowsUnaligned) {
12077       if (Fast)
12078         *Fast = Subtarget->hasV7Ops();
12079       return true;
12080     }
12081     return false;
12082   }
12083   case MVT::f64:
12084   case MVT::v2f64: {
12085     // For any little-endian targets with neon, we can support unaligned ld/st
12086     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12087     // A big-endian target may also explicitly support unaligned accesses
12088     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12089       if (Fast)
12090         *Fast = true;
12091       return true;
12092     }
12093     return false;
12094   }
12095   }
12096 }
12097 
12098 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12099                        unsigned AlignCheck) {
12100   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12101           (DstAlign == 0 || DstAlign % AlignCheck == 0));
12102 }
12103 
12104 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12105                                            unsigned DstAlign, unsigned SrcAlign,
12106                                            bool IsMemset, bool ZeroMemset,
12107                                            bool MemcpyStrSrc,
12108                                            MachineFunction &MF) const {
12109   const Function *F = MF.getFunction();
12110 
12111   // See if we can use NEON instructions for this...
12112   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12113       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12114     bool Fast;
12115     if (Size >= 16 &&
12116         (memOpAlign(SrcAlign, DstAlign, 16) ||
12117          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12118       return MVT::v2f64;
12119     } else if (Size >= 8 &&
12120                (memOpAlign(SrcAlign, DstAlign, 8) ||
12121                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12122                  Fast))) {
12123       return MVT::f64;
12124     }
12125   }
12126 
12127   // Lowering to i32/i16 if the size permits.
12128   if (Size >= 4)
12129     return MVT::i32;
12130   else if (Size >= 2)
12131     return MVT::i16;
12132 
12133   // Let the target-independent logic figure it out.
12134   return MVT::Other;
12135 }
12136 
12137 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12138   if (Val.getOpcode() != ISD::LOAD)
12139     return false;
12140 
12141   EVT VT1 = Val.getValueType();
12142   if (!VT1.isSimple() || !VT1.isInteger() ||
12143       !VT2.isSimple() || !VT2.isInteger())
12144     return false;
12145 
12146   switch (VT1.getSimpleVT().SimpleTy) {
12147   default: break;
12148   case MVT::i1:
12149   case MVT::i8:
12150   case MVT::i16:
12151     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
12152     return true;
12153   }
12154 
12155   return false;
12156 }
12157 
12158 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
12159   EVT VT = ExtVal.getValueType();
12160 
12161   if (!isTypeLegal(VT))
12162     return false;
12163 
12164   // Don't create a loadext if we can fold the extension into a wide/long
12165   // instruction.
12166   // If there's more than one user instruction, the loadext is desirable no
12167   // matter what.  There can be two uses by the same instruction.
12168   if (ExtVal->use_empty() ||
12169       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
12170     return true;
12171 
12172   SDNode *U = *ExtVal->use_begin();
12173   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
12174        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
12175     return false;
12176 
12177   return true;
12178 }
12179 
12180 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
12181   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12182     return false;
12183 
12184   if (!isTypeLegal(EVT::getEVT(Ty1)))
12185     return false;
12186 
12187   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
12188 
12189   // Assuming the caller doesn't have a zeroext or signext return parameter,
12190   // truncation all the way down to i1 is valid.
12191   return true;
12192 }
12193 
12194 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
12195                                                 const AddrMode &AM, Type *Ty,
12196                                                 unsigned AS) const {
12197   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
12198     if (Subtarget->hasFPAO())
12199       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
12200     return 0;
12201   }
12202   return -1;
12203 }
12204 
12205 
12206 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
12207   if (V < 0)
12208     return false;
12209 
12210   unsigned Scale = 1;
12211   switch (VT.getSimpleVT().SimpleTy) {
12212   default: return false;
12213   case MVT::i1:
12214   case MVT::i8:
12215     // Scale == 1;
12216     break;
12217   case MVT::i16:
12218     // Scale == 2;
12219     Scale = 2;
12220     break;
12221   case MVT::i32:
12222     // Scale == 4;
12223     Scale = 4;
12224     break;
12225   }
12226 
12227   if ((V & (Scale - 1)) != 0)
12228     return false;
12229   V /= Scale;
12230   return V == (V & ((1LL << 5) - 1));
12231 }
12232 
12233 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
12234                                       const ARMSubtarget *Subtarget) {
12235   bool isNeg = false;
12236   if (V < 0) {
12237     isNeg = true;
12238     V = - V;
12239   }
12240 
12241   switch (VT.getSimpleVT().SimpleTy) {
12242   default: return false;
12243   case MVT::i1:
12244   case MVT::i8:
12245   case MVT::i16:
12246   case MVT::i32:
12247     // + imm12 or - imm8
12248     if (isNeg)
12249       return V == (V & ((1LL << 8) - 1));
12250     return V == (V & ((1LL << 12) - 1));
12251   case MVT::f32:
12252   case MVT::f64:
12253     // Same as ARM mode. FIXME: NEON?
12254     if (!Subtarget->hasVFP2())
12255       return false;
12256     if ((V & 3) != 0)
12257       return false;
12258     V >>= 2;
12259     return V == (V & ((1LL << 8) - 1));
12260   }
12261 }
12262 
12263 /// isLegalAddressImmediate - Return true if the integer value can be used
12264 /// as the offset of the target addressing mode for load / store of the
12265 /// given type.
12266 static bool isLegalAddressImmediate(int64_t V, EVT VT,
12267                                     const ARMSubtarget *Subtarget) {
12268   if (V == 0)
12269     return true;
12270 
12271   if (!VT.isSimple())
12272     return false;
12273 
12274   if (Subtarget->isThumb1Only())
12275     return isLegalT1AddressImmediate(V, VT);
12276   else if (Subtarget->isThumb2())
12277     return isLegalT2AddressImmediate(V, VT, Subtarget);
12278 
12279   // ARM mode.
12280   if (V < 0)
12281     V = - V;
12282   switch (VT.getSimpleVT().SimpleTy) {
12283   default: return false;
12284   case MVT::i1:
12285   case MVT::i8:
12286   case MVT::i32:
12287     // +- imm12
12288     return V == (V & ((1LL << 12) - 1));
12289   case MVT::i16:
12290     // +- imm8
12291     return V == (V & ((1LL << 8) - 1));
12292   case MVT::f32:
12293   case MVT::f64:
12294     if (!Subtarget->hasVFP2()) // FIXME: NEON?
12295       return false;
12296     if ((V & 3) != 0)
12297       return false;
12298     V >>= 2;
12299     return V == (V & ((1LL << 8) - 1));
12300   }
12301 }
12302 
12303 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
12304                                                       EVT VT) const {
12305   int Scale = AM.Scale;
12306   if (Scale < 0)
12307     return false;
12308 
12309   switch (VT.getSimpleVT().SimpleTy) {
12310   default: return false;
12311   case MVT::i1:
12312   case MVT::i8:
12313   case MVT::i16:
12314   case MVT::i32:
12315     if (Scale == 1)
12316       return true;
12317     // r + r << imm
12318     Scale = Scale & ~1;
12319     return Scale == 2 || Scale == 4 || Scale == 8;
12320   case MVT::i64:
12321     // r + r
12322     if (((unsigned)AM.HasBaseReg + Scale) <= 2)
12323       return true;
12324     return false;
12325   case MVT::isVoid:
12326     // Note, we allow "void" uses (basically, uses that aren't loads or
12327     // stores), because arm allows folding a scale into many arithmetic
12328     // operations.  This should be made more precise and revisited later.
12329 
12330     // Allow r << imm, but the imm has to be a multiple of two.
12331     if (Scale & 1) return false;
12332     return isPowerOf2_32(Scale);
12333   }
12334 }
12335 
12336 /// isLegalAddressingMode - Return true if the addressing mode represented
12337 /// by AM is legal for this target, for a load/store of the specified type.
12338 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12339                                               const AddrMode &AM, Type *Ty,
12340                                               unsigned AS) const {
12341   EVT VT = getValueType(DL, Ty, true);
12342   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
12343     return false;
12344 
12345   // Can never fold addr of global into load/store.
12346   if (AM.BaseGV)
12347     return false;
12348 
12349   switch (AM.Scale) {
12350   case 0:  // no scale reg, must be "r+i" or "r", or "i".
12351     break;
12352   case 1:
12353     if (Subtarget->isThumb1Only())
12354       return false;
12355     LLVM_FALLTHROUGH;
12356   default:
12357     // ARM doesn't support any R+R*scale+imm addr modes.
12358     if (AM.BaseOffs)
12359       return false;
12360 
12361     if (!VT.isSimple())
12362       return false;
12363 
12364     if (Subtarget->isThumb2())
12365       return isLegalT2ScaledAddressingMode(AM, VT);
12366 
12367     int Scale = AM.Scale;
12368     switch (VT.getSimpleVT().SimpleTy) {
12369     default: return false;
12370     case MVT::i1:
12371     case MVT::i8:
12372     case MVT::i32:
12373       if (Scale < 0) Scale = -Scale;
12374       if (Scale == 1)
12375         return true;
12376       // r + r << imm
12377       return isPowerOf2_32(Scale & ~1);
12378     case MVT::i16:
12379     case MVT::i64:
12380       // r + r
12381       if (((unsigned)AM.HasBaseReg + Scale) <= 2)
12382         return true;
12383       return false;
12384 
12385     case MVT::isVoid:
12386       // Note, we allow "void" uses (basically, uses that aren't loads or
12387       // stores), because arm allows folding a scale into many arithmetic
12388       // operations.  This should be made more precise and revisited later.
12389 
12390       // Allow r << imm, but the imm has to be a multiple of two.
12391       if (Scale & 1) return false;
12392       return isPowerOf2_32(Scale);
12393     }
12394   }
12395   return true;
12396 }
12397 
12398 /// isLegalICmpImmediate - Return true if the specified immediate is legal
12399 /// icmp immediate, that is the target has icmp instructions which can compare
12400 /// a register against the immediate without having to materialize the
12401 /// immediate into a register.
12402 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12403   // Thumb2 and ARM modes can use cmn for negative immediates.
12404   if (!Subtarget->isThumb())
12405     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
12406   if (Subtarget->isThumb2())
12407     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
12408   // Thumb1 doesn't have cmn, and only 8-bit immediates.
12409   return Imm >= 0 && Imm <= 255;
12410 }
12411 
12412 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
12413 /// *or sub* immediate, that is the target has add or sub instructions which can
12414 /// add a register with the immediate without having to materialize the
12415 /// immediate into a register.
12416 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12417   // Same encoding for add/sub, just flip the sign.
12418   int64_t AbsImm = std::abs(Imm);
12419   if (!Subtarget->isThumb())
12420     return ARM_AM::getSOImmVal(AbsImm) != -1;
12421   if (Subtarget->isThumb2())
12422     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
12423   // Thumb1 only has 8-bit unsigned immediate.
12424   return AbsImm >= 0 && AbsImm <= 255;
12425 }
12426 
12427 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
12428                                       bool isSEXTLoad, SDValue &Base,
12429                                       SDValue &Offset, bool &isInc,
12430                                       SelectionDAG &DAG) {
12431   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12432     return false;
12433 
12434   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
12435     // AddressingMode 3
12436     Base = Ptr->getOperand(0);
12437     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12438       int RHSC = (int)RHS->getZExtValue();
12439       if (RHSC < 0 && RHSC > -256) {
12440         assert(Ptr->getOpcode() == ISD::ADD);
12441         isInc = false;
12442         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12443         return true;
12444       }
12445     }
12446     isInc = (Ptr->getOpcode() == ISD::ADD);
12447     Offset = Ptr->getOperand(1);
12448     return true;
12449   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
12450     // AddressingMode 2
12451     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12452       int RHSC = (int)RHS->getZExtValue();
12453       if (RHSC < 0 && RHSC > -0x1000) {
12454         assert(Ptr->getOpcode() == ISD::ADD);
12455         isInc = false;
12456         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12457         Base = Ptr->getOperand(0);
12458         return true;
12459       }
12460     }
12461 
12462     if (Ptr->getOpcode() == ISD::ADD) {
12463       isInc = true;
12464       ARM_AM::ShiftOpc ShOpcVal=
12465         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
12466       if (ShOpcVal != ARM_AM::no_shift) {
12467         Base = Ptr->getOperand(1);
12468         Offset = Ptr->getOperand(0);
12469       } else {
12470         Base = Ptr->getOperand(0);
12471         Offset = Ptr->getOperand(1);
12472       }
12473       return true;
12474     }
12475 
12476     isInc = (Ptr->getOpcode() == ISD::ADD);
12477     Base = Ptr->getOperand(0);
12478     Offset = Ptr->getOperand(1);
12479     return true;
12480   }
12481 
12482   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
12483   return false;
12484 }
12485 
12486 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
12487                                      bool isSEXTLoad, SDValue &Base,
12488                                      SDValue &Offset, bool &isInc,
12489                                      SelectionDAG &DAG) {
12490   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12491     return false;
12492 
12493   Base = Ptr->getOperand(0);
12494   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12495     int RHSC = (int)RHS->getZExtValue();
12496     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
12497       assert(Ptr->getOpcode() == ISD::ADD);
12498       isInc = false;
12499       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12500       return true;
12501     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
12502       isInc = Ptr->getOpcode() == ISD::ADD;
12503       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
12504       return true;
12505     }
12506   }
12507 
12508   return false;
12509 }
12510 
12511 /// getPreIndexedAddressParts - returns true by value, base pointer and
12512 /// offset pointer and addressing mode by reference if the node's address
12513 /// can be legally represented as pre-indexed load / store address.
12514 bool
12515 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12516                                              SDValue &Offset,
12517                                              ISD::MemIndexedMode &AM,
12518                                              SelectionDAG &DAG) const {
12519   if (Subtarget->isThumb1Only())
12520     return false;
12521 
12522   EVT VT;
12523   SDValue Ptr;
12524   bool isSEXTLoad = false;
12525   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12526     Ptr = LD->getBasePtr();
12527     VT  = LD->getMemoryVT();
12528     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12529   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12530     Ptr = ST->getBasePtr();
12531     VT  = ST->getMemoryVT();
12532   } else
12533     return false;
12534 
12535   bool isInc;
12536   bool isLegal = false;
12537   if (Subtarget->isThumb2())
12538     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12539                                        Offset, isInc, DAG);
12540   else
12541     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12542                                         Offset, isInc, DAG);
12543   if (!isLegal)
12544     return false;
12545 
12546   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
12547   return true;
12548 }
12549 
12550 /// getPostIndexedAddressParts - returns true by value, base pointer and
12551 /// offset pointer and addressing mode by reference if this node can be
12552 /// combined with a load / store to form a post-indexed load / store.
12553 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
12554                                                    SDValue &Base,
12555                                                    SDValue &Offset,
12556                                                    ISD::MemIndexedMode &AM,
12557                                                    SelectionDAG &DAG) const {
12558   EVT VT;
12559   SDValue Ptr;
12560   bool isSEXTLoad = false, isNonExt;
12561   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12562     VT  = LD->getMemoryVT();
12563     Ptr = LD->getBasePtr();
12564     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12565     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
12566   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12567     VT  = ST->getMemoryVT();
12568     Ptr = ST->getBasePtr();
12569     isNonExt = !ST->isTruncatingStore();
12570   } else
12571     return false;
12572 
12573   if (Subtarget->isThumb1Only()) {
12574     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
12575     // must be non-extending/truncating, i32, with an offset of 4.
12576     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
12577     if (Op->getOpcode() != ISD::ADD || !isNonExt)
12578       return false;
12579     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12580     if (!RHS || RHS->getZExtValue() != 4)
12581       return false;
12582 
12583     Offset = Op->getOperand(1);
12584     Base = Op->getOperand(0);
12585     AM = ISD::POST_INC;
12586     return true;
12587   }
12588 
12589   bool isInc;
12590   bool isLegal = false;
12591   if (Subtarget->isThumb2())
12592     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12593                                        isInc, DAG);
12594   else
12595     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12596                                         isInc, DAG);
12597   if (!isLegal)
12598     return false;
12599 
12600   if (Ptr != Base) {
12601     // Swap base ptr and offset to catch more post-index load / store when
12602     // it's legal. In Thumb2 mode, offset must be an immediate.
12603     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
12604         !Subtarget->isThumb2())
12605       std::swap(Base, Offset);
12606 
12607     // Post-indexed load / store update the base pointer.
12608     if (Ptr != Base)
12609       return false;
12610   }
12611 
12612   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
12613   return true;
12614 }
12615 
12616 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12617                                                       APInt &KnownZero,
12618                                                       APInt &KnownOne,
12619                                                       const APInt &DemandedElts,
12620                                                       const SelectionDAG &DAG,
12621                                                       unsigned Depth) const {
12622   unsigned BitWidth = KnownOne.getBitWidth();
12623   KnownZero = KnownOne = APInt(BitWidth, 0);
12624   switch (Op.getOpcode()) {
12625   default: break;
12626   case ARMISD::ADDC:
12627   case ARMISD::ADDE:
12628   case ARMISD::SUBC:
12629   case ARMISD::SUBE:
12630     // These nodes' second result is a boolean
12631     if (Op.getResNo() == 0)
12632       break;
12633     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12634     break;
12635   case ARMISD::CMOV: {
12636     // Bits are known zero/one if known on the LHS and RHS.
12637     DAG.computeKnownBits(Op.getOperand(0), KnownZero, KnownOne, Depth+1);
12638     if (KnownZero == 0 && KnownOne == 0) return;
12639 
12640     APInt KnownZeroRHS, KnownOneRHS;
12641     DAG.computeKnownBits(Op.getOperand(1), KnownZeroRHS, KnownOneRHS, Depth+1);
12642     KnownZero &= KnownZeroRHS;
12643     KnownOne  &= KnownOneRHS;
12644     return;
12645   }
12646   case ISD::INTRINSIC_W_CHAIN: {
12647     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
12648     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
12649     switch (IntID) {
12650     default: return;
12651     case Intrinsic::arm_ldaex:
12652     case Intrinsic::arm_ldrex: {
12653       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
12654       unsigned MemBits = VT.getScalarSizeInBits();
12655       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
12656       return;
12657     }
12658     }
12659   }
12660   }
12661 }
12662 
12663 //===----------------------------------------------------------------------===//
12664 //                           ARM Inline Assembly Support
12665 //===----------------------------------------------------------------------===//
12666 
12667 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
12668   // Looking for "rev" which is V6+.
12669   if (!Subtarget->hasV6Ops())
12670     return false;
12671 
12672   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12673   std::string AsmStr = IA->getAsmString();
12674   SmallVector<StringRef, 4> AsmPieces;
12675   SplitString(AsmStr, AsmPieces, ";\n");
12676 
12677   switch (AsmPieces.size()) {
12678   default: return false;
12679   case 1:
12680     AsmStr = AsmPieces[0];
12681     AsmPieces.clear();
12682     SplitString(AsmStr, AsmPieces, " \t,");
12683 
12684     // rev $0, $1
12685     if (AsmPieces.size() == 3 &&
12686         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
12687         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
12688       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12689       if (Ty && Ty->getBitWidth() == 32)
12690         return IntrinsicLowering::LowerToByteSwap(CI);
12691     }
12692     break;
12693   }
12694 
12695   return false;
12696 }
12697 
12698 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
12699   // At this point, we have to lower this constraint to something else, so we
12700   // lower it to an "r" or "w". However, by doing this we will force the result
12701   // to be in register, while the X constraint is much more permissive.
12702   //
12703   // Although we are correct (we are free to emit anything, without
12704   // constraints), we might break use cases that would expect us to be more
12705   // efficient and emit something else.
12706   if (!Subtarget->hasVFP2())
12707     return "r";
12708   if (ConstraintVT.isFloatingPoint())
12709     return "w";
12710   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
12711      (ConstraintVT.getSizeInBits() == 64 ||
12712       ConstraintVT.getSizeInBits() == 128))
12713     return "w";
12714 
12715   return "r";
12716 }
12717 
12718 /// getConstraintType - Given a constraint letter, return the type of
12719 /// constraint it is for this target.
12720 ARMTargetLowering::ConstraintType
12721 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
12722   if (Constraint.size() == 1) {
12723     switch (Constraint[0]) {
12724     default:  break;
12725     case 'l': return C_RegisterClass;
12726     case 'w': return C_RegisterClass;
12727     case 'h': return C_RegisterClass;
12728     case 'x': return C_RegisterClass;
12729     case 't': return C_RegisterClass;
12730     case 'j': return C_Other; // Constant for movw.
12731       // An address with a single base register. Due to the way we
12732       // currently handle addresses it is the same as an 'r' memory constraint.
12733     case 'Q': return C_Memory;
12734     }
12735   } else if (Constraint.size() == 2) {
12736     switch (Constraint[0]) {
12737     default: break;
12738     // All 'U+' constraints are addresses.
12739     case 'U': return C_Memory;
12740     }
12741   }
12742   return TargetLowering::getConstraintType(Constraint);
12743 }
12744 
12745 /// Examine constraint type and operand type and determine a weight value.
12746 /// This object must already have been set up with the operand type
12747 /// and the current alternative constraint selected.
12748 TargetLowering::ConstraintWeight
12749 ARMTargetLowering::getSingleConstraintMatchWeight(
12750     AsmOperandInfo &info, const char *constraint) const {
12751   ConstraintWeight weight = CW_Invalid;
12752   Value *CallOperandVal = info.CallOperandVal;
12753     // If we don't have a value, we can't do a match,
12754     // but allow it at the lowest weight.
12755   if (!CallOperandVal)
12756     return CW_Default;
12757   Type *type = CallOperandVal->getType();
12758   // Look at the constraint type.
12759   switch (*constraint) {
12760   default:
12761     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
12762     break;
12763   case 'l':
12764     if (type->isIntegerTy()) {
12765       if (Subtarget->isThumb())
12766         weight = CW_SpecificReg;
12767       else
12768         weight = CW_Register;
12769     }
12770     break;
12771   case 'w':
12772     if (type->isFloatingPointTy())
12773       weight = CW_Register;
12774     break;
12775   }
12776   return weight;
12777 }
12778 
12779 typedef std::pair<unsigned, const TargetRegisterClass*> RCPair;
12780 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
12781     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
12782   if (Constraint.size() == 1) {
12783     // GCC ARM Constraint Letters
12784     switch (Constraint[0]) {
12785     case 'l': // Low regs or general regs.
12786       if (Subtarget->isThumb())
12787         return RCPair(0U, &ARM::tGPRRegClass);
12788       return RCPair(0U, &ARM::GPRRegClass);
12789     case 'h': // High regs or no regs.
12790       if (Subtarget->isThumb())
12791         return RCPair(0U, &ARM::hGPRRegClass);
12792       break;
12793     case 'r':
12794       if (Subtarget->isThumb1Only())
12795         return RCPair(0U, &ARM::tGPRRegClass);
12796       return RCPair(0U, &ARM::GPRRegClass);
12797     case 'w':
12798       if (VT == MVT::Other)
12799         break;
12800       if (VT == MVT::f32)
12801         return RCPair(0U, &ARM::SPRRegClass);
12802       if (VT.getSizeInBits() == 64)
12803         return RCPair(0U, &ARM::DPRRegClass);
12804       if (VT.getSizeInBits() == 128)
12805         return RCPair(0U, &ARM::QPRRegClass);
12806       break;
12807     case 'x':
12808       if (VT == MVT::Other)
12809         break;
12810       if (VT == MVT::f32)
12811         return RCPair(0U, &ARM::SPR_8RegClass);
12812       if (VT.getSizeInBits() == 64)
12813         return RCPair(0U, &ARM::DPR_8RegClass);
12814       if (VT.getSizeInBits() == 128)
12815         return RCPair(0U, &ARM::QPR_8RegClass);
12816       break;
12817     case 't':
12818       if (VT == MVT::f32)
12819         return RCPair(0U, &ARM::SPRRegClass);
12820       break;
12821     }
12822   }
12823   if (StringRef("{cc}").equals_lower(Constraint))
12824     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
12825 
12826   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
12827 }
12828 
12829 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
12830 /// vector.  If it is invalid, don't add anything to Ops.
12831 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
12832                                                      std::string &Constraint,
12833                                                      std::vector<SDValue>&Ops,
12834                                                      SelectionDAG &DAG) const {
12835   SDValue Result;
12836 
12837   // Currently only support length 1 constraints.
12838   if (Constraint.length() != 1) return;
12839 
12840   char ConstraintLetter = Constraint[0];
12841   switch (ConstraintLetter) {
12842   default: break;
12843   case 'j':
12844   case 'I': case 'J': case 'K': case 'L':
12845   case 'M': case 'N': case 'O':
12846     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
12847     if (!C)
12848       return;
12849 
12850     int64_t CVal64 = C->getSExtValue();
12851     int CVal = (int) CVal64;
12852     // None of these constraints allow values larger than 32 bits.  Check
12853     // that the value fits in an int.
12854     if (CVal != CVal64)
12855       return;
12856 
12857     switch (ConstraintLetter) {
12858       case 'j':
12859         // Constant suitable for movw, must be between 0 and
12860         // 65535.
12861         if (Subtarget->hasV6T2Ops())
12862           if (CVal >= 0 && CVal <= 65535)
12863             break;
12864         return;
12865       case 'I':
12866         if (Subtarget->isThumb1Only()) {
12867           // This must be a constant between 0 and 255, for ADD
12868           // immediates.
12869           if (CVal >= 0 && CVal <= 255)
12870             break;
12871         } else if (Subtarget->isThumb2()) {
12872           // A constant that can be used as an immediate value in a
12873           // data-processing instruction.
12874           if (ARM_AM::getT2SOImmVal(CVal) != -1)
12875             break;
12876         } else {
12877           // A constant that can be used as an immediate value in a
12878           // data-processing instruction.
12879           if (ARM_AM::getSOImmVal(CVal) != -1)
12880             break;
12881         }
12882         return;
12883 
12884       case 'J':
12885         if (Subtarget->isThumb1Only()) {
12886           // This must be a constant between -255 and -1, for negated ADD
12887           // immediates. This can be used in GCC with an "n" modifier that
12888           // prints the negated value, for use with SUB instructions. It is
12889           // not useful otherwise but is implemented for compatibility.
12890           if (CVal >= -255 && CVal <= -1)
12891             break;
12892         } else {
12893           // This must be a constant between -4095 and 4095. It is not clear
12894           // what this constraint is intended for. Implemented for
12895           // compatibility with GCC.
12896           if (CVal >= -4095 && CVal <= 4095)
12897             break;
12898         }
12899         return;
12900 
12901       case 'K':
12902         if (Subtarget->isThumb1Only()) {
12903           // A 32-bit value where only one byte has a nonzero value. Exclude
12904           // zero to match GCC. This constraint is used by GCC internally for
12905           // constants that can be loaded with a move/shift combination.
12906           // It is not useful otherwise but is implemented for compatibility.
12907           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
12908             break;
12909         } else if (Subtarget->isThumb2()) {
12910           // A constant whose bitwise inverse can be used as an immediate
12911           // value in a data-processing instruction. This can be used in GCC
12912           // with a "B" modifier that prints the inverted value, for use with
12913           // BIC and MVN instructions. It is not useful otherwise but is
12914           // implemented for compatibility.
12915           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
12916             break;
12917         } else {
12918           // A constant whose bitwise inverse can be used as an immediate
12919           // value in a data-processing instruction. This can be used in GCC
12920           // with a "B" modifier that prints the inverted value, for use with
12921           // BIC and MVN instructions. It is not useful otherwise but is
12922           // implemented for compatibility.
12923           if (ARM_AM::getSOImmVal(~CVal) != -1)
12924             break;
12925         }
12926         return;
12927 
12928       case 'L':
12929         if (Subtarget->isThumb1Only()) {
12930           // This must be a constant between -7 and 7,
12931           // for 3-operand ADD/SUB immediate instructions.
12932           if (CVal >= -7 && CVal < 7)
12933             break;
12934         } else if (Subtarget->isThumb2()) {
12935           // A constant whose negation can be used as an immediate value in a
12936           // data-processing instruction. This can be used in GCC with an "n"
12937           // modifier that prints the negated value, for use with SUB
12938           // instructions. It is not useful otherwise but is implemented for
12939           // compatibility.
12940           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
12941             break;
12942         } else {
12943           // A constant whose negation can be used as an immediate value in a
12944           // data-processing instruction. This can be used in GCC with an "n"
12945           // modifier that prints the negated value, for use with SUB
12946           // instructions. It is not useful otherwise but is implemented for
12947           // compatibility.
12948           if (ARM_AM::getSOImmVal(-CVal) != -1)
12949             break;
12950         }
12951         return;
12952 
12953       case 'M':
12954         if (Subtarget->isThumb1Only()) {
12955           // This must be a multiple of 4 between 0 and 1020, for
12956           // ADD sp + immediate.
12957           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
12958             break;
12959         } else {
12960           // A power of two or a constant between 0 and 32.  This is used in
12961           // GCC for the shift amount on shifted register operands, but it is
12962           // useful in general for any shift amounts.
12963           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
12964             break;
12965         }
12966         return;
12967 
12968       case 'N':
12969         if (Subtarget->isThumb()) {  // FIXME thumb2
12970           // This must be a constant between 0 and 31, for shift amounts.
12971           if (CVal >= 0 && CVal <= 31)
12972             break;
12973         }
12974         return;
12975 
12976       case 'O':
12977         if (Subtarget->isThumb()) {  // FIXME thumb2
12978           // This must be a multiple of 4 between -508 and 508, for
12979           // ADD/SUB sp = sp + immediate.
12980           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
12981             break;
12982         }
12983         return;
12984     }
12985     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
12986     break;
12987   }
12988 
12989   if (Result.getNode()) {
12990     Ops.push_back(Result);
12991     return;
12992   }
12993   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
12994 }
12995 
12996 static RTLIB::Libcall getDivRemLibcall(
12997     const SDNode *N, MVT::SimpleValueType SVT) {
12998   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
12999           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13000          "Unhandled Opcode in getDivRemLibcall");
13001   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13002                   N->getOpcode() == ISD::SREM;
13003   RTLIB::Libcall LC;
13004   switch (SVT) {
13005   default: llvm_unreachable("Unexpected request for libcall!");
13006   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
13007   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
13008   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
13009   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
13010   }
13011   return LC;
13012 }
13013 
13014 static TargetLowering::ArgListTy getDivRemArgList(
13015     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
13016   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13017           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13018          "Unhandled Opcode in getDivRemArgList");
13019   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13020                   N->getOpcode() == ISD::SREM;
13021   TargetLowering::ArgListTy Args;
13022   TargetLowering::ArgListEntry Entry;
13023   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13024     EVT ArgVT = N->getOperand(i).getValueType();
13025     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
13026     Entry.Node = N->getOperand(i);
13027     Entry.Ty = ArgTy;
13028     Entry.IsSExt = isSigned;
13029     Entry.IsZExt = !isSigned;
13030     Args.push_back(Entry);
13031   }
13032   if (Subtarget->isTargetWindows() && Args.size() >= 2)
13033     std::swap(Args[0], Args[1]);
13034   return Args;
13035 }
13036 
13037 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
13038   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
13039           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
13040           Subtarget->isTargetWindows()) &&
13041          "Register-based DivRem lowering only");
13042   unsigned Opcode = Op->getOpcode();
13043   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
13044          "Invalid opcode for Div/Rem lowering");
13045   bool isSigned = (Opcode == ISD::SDIVREM);
13046   EVT VT = Op->getValueType(0);
13047   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
13048   SDLoc dl(Op);
13049 
13050   // If the target has hardware divide, use divide + multiply + subtract:
13051   //     div = a / b
13052   //     rem = a - b * div
13053   //     return {div, rem}
13054   // This should be lowered into UDIV/SDIV + MLS later on.
13055   if (Subtarget->hasDivide() && Op->getValueType(0).isSimple() &&
13056       Op->getSimpleValueType(0) == MVT::i32) {
13057     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
13058     const SDValue Dividend = Op->getOperand(0);
13059     const SDValue Divisor = Op->getOperand(1);
13060     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
13061     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
13062     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13063 
13064     SDValue Values[2] = {Div, Rem};
13065     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
13066   }
13067 
13068   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
13069                                        VT.getSimpleVT().SimpleTy);
13070   SDValue InChain = DAG.getEntryNode();
13071 
13072   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
13073                                                     DAG.getContext(),
13074                                                     Subtarget);
13075 
13076   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13077                                          getPointerTy(DAG.getDataLayout()));
13078 
13079   Type *RetTy = (Type*)StructType::get(Ty, Ty, nullptr);
13080 
13081   if (Subtarget->isTargetWindows())
13082     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
13083 
13084   TargetLowering::CallLoweringInfo CLI(DAG);
13085   CLI.setDebugLoc(dl).setChain(InChain)
13086     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
13087     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13088 
13089   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13090   return CallInfo.first;
13091 }
13092 
13093 // Lowers REM using divmod helpers
13094 // see RTABI section 4.2/4.3
13095 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
13096   // Build return types (div and rem)
13097   std::vector<Type*> RetTyParams;
13098   Type *RetTyElement;
13099 
13100   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
13101   default: llvm_unreachable("Unexpected request for libcall!");
13102   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
13103   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
13104   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
13105   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
13106   }
13107 
13108   RetTyParams.push_back(RetTyElement);
13109   RetTyParams.push_back(RetTyElement);
13110   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
13111   Type *RetTy = StructType::get(*DAG.getContext(), ret);
13112 
13113   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
13114                                                              SimpleTy);
13115   SDValue InChain = DAG.getEntryNode();
13116   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
13117                                                     Subtarget);
13118   bool isSigned = N->getOpcode() == ISD::SREM;
13119   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13120                                          getPointerTy(DAG.getDataLayout()));
13121 
13122   if (Subtarget->isTargetWindows())
13123     InChain = WinDBZCheckDenominator(DAG, N, InChain);
13124 
13125   // Lower call
13126   CallLoweringInfo CLI(DAG);
13127   CLI.setChain(InChain)
13128      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
13129      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
13130   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
13131 
13132   // Return second (rem) result operand (first contains div)
13133   SDNode *ResNode = CallResult.first.getNode();
13134   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
13135   return ResNode->getOperand(1);
13136 }
13137 
13138 SDValue
13139 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
13140   assert(Subtarget->isTargetWindows() && "unsupported target platform");
13141   SDLoc DL(Op);
13142 
13143   // Get the inputs.
13144   SDValue Chain = Op.getOperand(0);
13145   SDValue Size  = Op.getOperand(1);
13146 
13147   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
13148                               DAG.getConstant(2, DL, MVT::i32));
13149 
13150   SDValue Flag;
13151   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
13152   Flag = Chain.getValue(1);
13153 
13154   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13155   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
13156 
13157   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
13158   Chain = NewSP.getValue(1);
13159 
13160   SDValue Ops[2] = { NewSP, Chain };
13161   return DAG.getMergeValues(Ops, DL);
13162 }
13163 
13164 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
13165   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
13166          "Unexpected type for custom-lowering FP_EXTEND");
13167 
13168   RTLIB::Libcall LC;
13169   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
13170 
13171   SDValue SrcVal = Op.getOperand(0);
13172   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13173                      SDLoc(Op)).first;
13174 }
13175 
13176 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
13177   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
13178          Subtarget->isFPOnlySP() &&
13179          "Unexpected type for custom-lowering FP_ROUND");
13180 
13181   RTLIB::Libcall LC;
13182   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
13183 
13184   SDValue SrcVal = Op.getOperand(0);
13185   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13186                      SDLoc(Op)).first;
13187 }
13188 
13189 bool
13190 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13191   // The ARM target isn't yet aware of offsets.
13192   return false;
13193 }
13194 
13195 bool ARM::isBitFieldInvertedMask(unsigned v) {
13196   if (v == 0xffffffff)
13197     return false;
13198 
13199   // there can be 1's on either or both "outsides", all the "inside"
13200   // bits must be 0's
13201   return isShiftedMask_32(~v);
13202 }
13203 
13204 /// isFPImmLegal - Returns true if the target can instruction select the
13205 /// specified FP immediate natively. If false, the legalizer will
13206 /// materialize the FP immediate as a load from a constant pool.
13207 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13208   if (!Subtarget->hasVFP3())
13209     return false;
13210   if (VT == MVT::f32)
13211     return ARM_AM::getFP32Imm(Imm) != -1;
13212   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
13213     return ARM_AM::getFP64Imm(Imm) != -1;
13214   return false;
13215 }
13216 
13217 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
13218 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
13219 /// specified in the intrinsic calls.
13220 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13221                                            const CallInst &I,
13222                                            unsigned Intrinsic) const {
13223   switch (Intrinsic) {
13224   case Intrinsic::arm_neon_vld1:
13225   case Intrinsic::arm_neon_vld2:
13226   case Intrinsic::arm_neon_vld3:
13227   case Intrinsic::arm_neon_vld4:
13228   case Intrinsic::arm_neon_vld2lane:
13229   case Intrinsic::arm_neon_vld3lane:
13230   case Intrinsic::arm_neon_vld4lane: {
13231     Info.opc = ISD::INTRINSIC_W_CHAIN;
13232     // Conservatively set memVT to the entire set of vectors loaded.
13233     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13234     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
13235     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13236     Info.ptrVal = I.getArgOperand(0);
13237     Info.offset = 0;
13238     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13239     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13240     Info.vol = false; // volatile loads with NEON intrinsics not supported
13241     Info.readMem = true;
13242     Info.writeMem = false;
13243     return true;
13244   }
13245   case Intrinsic::arm_neon_vst1:
13246   case Intrinsic::arm_neon_vst2:
13247   case Intrinsic::arm_neon_vst3:
13248   case Intrinsic::arm_neon_vst4:
13249   case Intrinsic::arm_neon_vst2lane:
13250   case Intrinsic::arm_neon_vst3lane:
13251   case Intrinsic::arm_neon_vst4lane: {
13252     Info.opc = ISD::INTRINSIC_VOID;
13253     // Conservatively set memVT to the entire set of vectors stored.
13254     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13255     unsigned NumElts = 0;
13256     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
13257       Type *ArgTy = I.getArgOperand(ArgI)->getType();
13258       if (!ArgTy->isVectorTy())
13259         break;
13260       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
13261     }
13262     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13263     Info.ptrVal = I.getArgOperand(0);
13264     Info.offset = 0;
13265     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13266     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13267     Info.vol = false; // volatile stores with NEON intrinsics not supported
13268     Info.readMem = false;
13269     Info.writeMem = true;
13270     return true;
13271   }
13272   case Intrinsic::arm_ldaex:
13273   case Intrinsic::arm_ldrex: {
13274     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13275     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
13276     Info.opc = ISD::INTRINSIC_W_CHAIN;
13277     Info.memVT = MVT::getVT(PtrTy->getElementType());
13278     Info.ptrVal = I.getArgOperand(0);
13279     Info.offset = 0;
13280     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13281     Info.vol = true;
13282     Info.readMem = true;
13283     Info.writeMem = false;
13284     return true;
13285   }
13286   case Intrinsic::arm_stlex:
13287   case Intrinsic::arm_strex: {
13288     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13289     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
13290     Info.opc = ISD::INTRINSIC_W_CHAIN;
13291     Info.memVT = MVT::getVT(PtrTy->getElementType());
13292     Info.ptrVal = I.getArgOperand(1);
13293     Info.offset = 0;
13294     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13295     Info.vol = true;
13296     Info.readMem = false;
13297     Info.writeMem = true;
13298     return true;
13299   }
13300   case Intrinsic::arm_stlexd:
13301   case Intrinsic::arm_strexd:
13302     Info.opc = ISD::INTRINSIC_W_CHAIN;
13303     Info.memVT = MVT::i64;
13304     Info.ptrVal = I.getArgOperand(2);
13305     Info.offset = 0;
13306     Info.align = 8;
13307     Info.vol = true;
13308     Info.readMem = false;
13309     Info.writeMem = true;
13310     return true;
13311 
13312   case Intrinsic::arm_ldaexd:
13313   case Intrinsic::arm_ldrexd:
13314     Info.opc = ISD::INTRINSIC_W_CHAIN;
13315     Info.memVT = MVT::i64;
13316     Info.ptrVal = I.getArgOperand(0);
13317     Info.offset = 0;
13318     Info.align = 8;
13319     Info.vol = true;
13320     Info.readMem = true;
13321     Info.writeMem = false;
13322     return true;
13323 
13324   default:
13325     break;
13326   }
13327 
13328   return false;
13329 }
13330 
13331 /// \brief Returns true if it is beneficial to convert a load of a constant
13332 /// to just the constant itself.
13333 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13334                                                           Type *Ty) const {
13335   assert(Ty->isIntegerTy());
13336 
13337   unsigned Bits = Ty->getPrimitiveSizeInBits();
13338   if (Bits == 0 || Bits > 32)
13339     return false;
13340   return true;
13341 }
13342 
13343 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT,
13344                                                 unsigned Index) const {
13345   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
13346     return false;
13347 
13348   return (Index == 0 || Index == ResVT.getVectorNumElements());
13349 }
13350 
13351 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
13352                                         ARM_MB::MemBOpt Domain) const {
13353   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13354 
13355   // First, if the target has no DMB, see what fallback we can use.
13356   if (!Subtarget->hasDataBarrier()) {
13357     // Some ARMv6 cpus can support data barriers with an mcr instruction.
13358     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
13359     // here.
13360     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
13361       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
13362       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
13363                         Builder.getInt32(0), Builder.getInt32(7),
13364                         Builder.getInt32(10), Builder.getInt32(5)};
13365       return Builder.CreateCall(MCR, args);
13366     } else {
13367       // Instead of using barriers, atomic accesses on these subtargets use
13368       // libcalls.
13369       llvm_unreachable("makeDMB on a target so old that it has no barriers");
13370     }
13371   } else {
13372     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
13373     // Only a full system barrier exists in the M-class architectures.
13374     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
13375     Constant *CDomain = Builder.getInt32(Domain);
13376     return Builder.CreateCall(DMB, CDomain);
13377   }
13378 }
13379 
13380 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13381 Instruction* ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
13382                                          AtomicOrdering Ord, bool IsStore,
13383                                          bool IsLoad) const {
13384   switch (Ord) {
13385   case AtomicOrdering::NotAtomic:
13386   case AtomicOrdering::Unordered:
13387     llvm_unreachable("Invalid fence: unordered/non-atomic");
13388   case AtomicOrdering::Monotonic:
13389   case AtomicOrdering::Acquire:
13390     return nullptr; // Nothing to do
13391   case AtomicOrdering::SequentiallyConsistent:
13392     if (!IsStore)
13393       return nullptr; // Nothing to do
13394     /*FALLTHROUGH*/
13395   case AtomicOrdering::Release:
13396   case AtomicOrdering::AcquireRelease:
13397     if (Subtarget->preferISHSTBarriers())
13398       return makeDMB(Builder, ARM_MB::ISHST);
13399     // FIXME: add a comment with a link to documentation justifying this.
13400     else
13401       return makeDMB(Builder, ARM_MB::ISH);
13402   }
13403   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
13404 }
13405 
13406 Instruction* ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
13407                                           AtomicOrdering Ord, bool IsStore,
13408                                           bool IsLoad) const {
13409   switch (Ord) {
13410   case AtomicOrdering::NotAtomic:
13411   case AtomicOrdering::Unordered:
13412     llvm_unreachable("Invalid fence: unordered/not-atomic");
13413   case AtomicOrdering::Monotonic:
13414   case AtomicOrdering::Release:
13415     return nullptr; // Nothing to do
13416   case AtomicOrdering::Acquire:
13417   case AtomicOrdering::AcquireRelease:
13418   case AtomicOrdering::SequentiallyConsistent:
13419     return makeDMB(Builder, ARM_MB::ISH);
13420   }
13421   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
13422 }
13423 
13424 // Loads and stores less than 64-bits are already atomic; ones above that
13425 // are doomed anyway, so defer to the default libcall and blame the OS when
13426 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13427 // anything for those.
13428 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13429   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13430   return (Size == 64) && !Subtarget->isMClass();
13431 }
13432 
13433 // Loads and stores less than 64-bits are already atomic; ones above that
13434 // are doomed anyway, so defer to the default libcall and blame the OS when
13435 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13436 // anything for those.
13437 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
13438 // guarantee, see DDI0406C ARM architecture reference manual,
13439 // sections A8.8.72-74 LDRD)
13440 TargetLowering::AtomicExpansionKind
13441 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13442   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13443   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
13444                                                   : AtomicExpansionKind::None;
13445 }
13446 
13447 // For the real atomic operations, we have ldrex/strex up to 32 bits,
13448 // and up to 64 bits on the non-M profiles
13449 TargetLowering::AtomicExpansionKind
13450 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13451   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13452   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13453   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
13454              ? AtomicExpansionKind::LLSC
13455              : AtomicExpansionKind::None;
13456 }
13457 
13458 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
13459     AtomicCmpXchgInst *AI) const {
13460   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13461   // implement cmpxchg without spilling. If the address being exchanged is also
13462   // on the stack and close enough to the spill slot, this can lead to a
13463   // situation where the monitor always gets cleared and the atomic operation
13464   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13465   bool hasAtomicCmpXchg =
13466       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13467   return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg;
13468 }
13469 
13470 bool ARMTargetLowering::shouldInsertFencesForAtomic(
13471     const Instruction *I) const {
13472   return InsertFencesForAtomic;
13473 }
13474 
13475 // This has so far only been implemented for MachO.
13476 bool ARMTargetLowering::useLoadStackGuardNode() const {
13477   return Subtarget->isTargetMachO();
13478 }
13479 
13480 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
13481                                                   unsigned &Cost) const {
13482   // If we do not have NEON, vector types are not natively supported.
13483   if (!Subtarget->hasNEON())
13484     return false;
13485 
13486   // Floating point values and vector values map to the same register file.
13487   // Therefore, although we could do a store extract of a vector type, this is
13488   // better to leave at float as we have more freedom in the addressing mode for
13489   // those.
13490   if (VectorTy->isFPOrFPVectorTy())
13491     return false;
13492 
13493   // If the index is unknown at compile time, this is very expensive to lower
13494   // and it is not possible to combine the store with the extract.
13495   if (!isa<ConstantInt>(Idx))
13496     return false;
13497 
13498   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
13499   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
13500   // We can do a store + vector extract on any vector that fits perfectly in a D
13501   // or Q register.
13502   if (BitWidth == 64 || BitWidth == 128) {
13503     Cost = 0;
13504     return true;
13505   }
13506   return false;
13507 }
13508 
13509 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
13510   return Subtarget->hasV6T2Ops();
13511 }
13512 
13513 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
13514   return Subtarget->hasV6T2Ops();
13515 }
13516 
13517 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13518                                          AtomicOrdering Ord) const {
13519   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13520   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13521   bool IsAcquire = isAcquireOrStronger(Ord);
13522 
13523   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
13524   // intrinsic must return {i32, i32} and we have to recombine them into a
13525   // single i64 here.
13526   if (ValTy->getPrimitiveSizeInBits() == 64) {
13527     Intrinsic::ID Int =
13528         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
13529     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
13530 
13531     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13532     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
13533 
13534     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13535     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13536     if (!Subtarget->isLittle())
13537       std::swap (Lo, Hi);
13538     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13539     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13540     return Builder.CreateOr(
13541         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
13542   }
13543 
13544   Type *Tys[] = { Addr->getType() };
13545   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
13546   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
13547 
13548   return Builder.CreateTruncOrBitCast(
13549       Builder.CreateCall(Ldrex, Addr),
13550       cast<PointerType>(Addr->getType())->getElementType());
13551 }
13552 
13553 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13554     IRBuilder<> &Builder) const {
13555   if (!Subtarget->hasV7Ops())
13556     return;
13557   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13558   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
13559 }
13560 
13561 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
13562                                                Value *Addr,
13563                                                AtomicOrdering Ord) const {
13564   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13565   bool IsRelease = isReleaseOrStronger(Ord);
13566 
13567   // Since the intrinsics must have legal type, the i64 intrinsics take two
13568   // parameters: "i32, i32". We must marshal Val into the appropriate form
13569   // before the call.
13570   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
13571     Intrinsic::ID Int =
13572         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
13573     Function *Strex = Intrinsic::getDeclaration(M, Int);
13574     Type *Int32Ty = Type::getInt32Ty(M->getContext());
13575 
13576     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
13577     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
13578     if (!Subtarget->isLittle())
13579       std::swap (Lo, Hi);
13580     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13581     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
13582   }
13583 
13584   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
13585   Type *Tys[] = { Addr->getType() };
13586   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
13587 
13588   return Builder.CreateCall(
13589       Strex, {Builder.CreateZExtOrBitCast(
13590                   Val, Strex->getFunctionType()->getParamType(0)),
13591               Addr});
13592 }
13593 
13594 /// A helper function for determining the number of interleaved accesses we
13595 /// will generate when lowering accesses of the given type.
13596 unsigned
13597 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
13598                                              const DataLayout &DL) const {
13599   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
13600 }
13601 
13602 bool ARMTargetLowering::isLegalInterleavedAccessType(
13603     VectorType *VecTy, const DataLayout &DL) const {
13604 
13605   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
13606   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
13607 
13608   // Ensure the vector doesn't have f16 elements. Even though we could do an
13609   // i16 vldN, we can't hold the f16 vectors and will end up converting via
13610   // f32.
13611   if (VecTy->getElementType()->isHalfTy())
13612     return false;
13613 
13614   // Ensure the number of vector elements is greater than 1.
13615   if (VecTy->getNumElements() < 2)
13616     return false;
13617 
13618   // Ensure the element type is legal.
13619   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
13620     return false;
13621 
13622   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
13623   // 128 will be split into multiple interleaved accesses.
13624   return VecSize == 64 || VecSize % 128 == 0;
13625 }
13626 
13627 /// \brief Lower an interleaved load into a vldN intrinsic.
13628 ///
13629 /// E.g. Lower an interleaved load (Factor = 2):
13630 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
13631 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
13632 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
13633 ///
13634 ///      Into:
13635 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
13636 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
13637 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
13638 bool ARMTargetLowering::lowerInterleavedLoad(
13639     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
13640     ArrayRef<unsigned> Indices, unsigned Factor) const {
13641   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13642          "Invalid interleave factor");
13643   assert(!Shuffles.empty() && "Empty shufflevector input");
13644   assert(Shuffles.size() == Indices.size() &&
13645          "Unmatched number of shufflevectors and indices");
13646 
13647   VectorType *VecTy = Shuffles[0]->getType();
13648   Type *EltTy = VecTy->getVectorElementType();
13649 
13650   const DataLayout &DL = LI->getModule()->getDataLayout();
13651 
13652   // Skip if we do not have NEON and skip illegal vector types. We can
13653   // "legalize" wide vector types into multiple interleaved accesses as long as
13654   // the vector types are divisible by 128.
13655   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
13656     return false;
13657 
13658   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
13659 
13660   // A pointer vector can not be the return type of the ldN intrinsics. Need to
13661   // load integer vectors first and then convert to pointer vectors.
13662   if (EltTy->isPointerTy())
13663     VecTy =
13664         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
13665 
13666   IRBuilder<> Builder(LI);
13667 
13668   // The base address of the load.
13669   Value *BaseAddr = LI->getPointerOperand();
13670 
13671   if (NumLoads > 1) {
13672     // If we're going to generate more than one load, reset the sub-vector type
13673     // to something legal.
13674     VecTy = VectorType::get(VecTy->getVectorElementType(),
13675                             VecTy->getVectorNumElements() / NumLoads);
13676 
13677     // We will compute the pointer operand of each load from the original base
13678     // address using GEPs. Cast the base address to a pointer to the scalar
13679     // element type.
13680     BaseAddr = Builder.CreateBitCast(
13681         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
13682                       LI->getPointerAddressSpace()));
13683   }
13684 
13685   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
13686 
13687   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
13688   Type *Tys[] = {VecTy, Int8Ptr};
13689   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
13690                                             Intrinsic::arm_neon_vld3,
13691                                             Intrinsic::arm_neon_vld4};
13692   Function *VldnFunc =
13693       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
13694 
13695   // Holds sub-vectors extracted from the load intrinsic return values. The
13696   // sub-vectors are associated with the shufflevector instructions they will
13697   // replace.
13698   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
13699 
13700   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
13701 
13702     // If we're generating more than one load, compute the base address of
13703     // subsequent loads as an offset from the previous.
13704     if (LoadCount > 0)
13705       BaseAddr = Builder.CreateConstGEP1_32(
13706           BaseAddr, VecTy->getVectorNumElements() * Factor);
13707 
13708     SmallVector<Value *, 2> Ops;
13709     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
13710     Ops.push_back(Builder.getInt32(LI->getAlignment()));
13711 
13712     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
13713 
13714     // Replace uses of each shufflevector with the corresponding vector loaded
13715     // by ldN.
13716     for (unsigned i = 0; i < Shuffles.size(); i++) {
13717       ShuffleVectorInst *SV = Shuffles[i];
13718       unsigned Index = Indices[i];
13719 
13720       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
13721 
13722       // Convert the integer vector to pointer vector if the element is pointer.
13723       if (EltTy->isPointerTy())
13724         SubVec = Builder.CreateIntToPtr(SubVec, SV->getType());
13725 
13726       SubVecs[SV].push_back(SubVec);
13727     }
13728   }
13729 
13730   // Replace uses of the shufflevector instructions with the sub-vectors
13731   // returned by the load intrinsic. If a shufflevector instruction is
13732   // associated with more than one sub-vector, those sub-vectors will be
13733   // concatenated into a single wide vector.
13734   for (ShuffleVectorInst *SVI : Shuffles) {
13735     auto &SubVec = SubVecs[SVI];
13736     auto *WideVec =
13737         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
13738     SVI->replaceAllUsesWith(WideVec);
13739   }
13740 
13741   return true;
13742 }
13743 
13744 /// \brief Lower an interleaved store into a vstN intrinsic.
13745 ///
13746 /// E.g. Lower an interleaved store (Factor = 3):
13747 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
13748 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
13749 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
13750 ///
13751 ///      Into:
13752 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
13753 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
13754 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
13755 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
13756 ///
13757 /// Note that the new shufflevectors will be removed and we'll only generate one
13758 /// vst3 instruction in CodeGen.
13759 ///
13760 /// Example for a more general valid mask (Factor 3). Lower:
13761 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
13762 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
13763 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
13764 ///
13765 ///      Into:
13766 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
13767 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
13768 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
13769 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
13770 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
13771                                               ShuffleVectorInst *SVI,
13772                                               unsigned Factor) const {
13773   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13774          "Invalid interleave factor");
13775 
13776   VectorType *VecTy = SVI->getType();
13777   assert(VecTy->getVectorNumElements() % Factor == 0 &&
13778          "Invalid interleaved store");
13779 
13780   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
13781   Type *EltTy = VecTy->getVectorElementType();
13782   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
13783 
13784   const DataLayout &DL = SI->getModule()->getDataLayout();
13785 
13786   // Skip if we do not have NEON and skip illegal vector types. We can
13787   // "legalize" wide vector types into multiple interleaved accesses as long as
13788   // the vector types are divisible by 128.
13789   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
13790     return false;
13791 
13792   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
13793 
13794   Value *Op0 = SVI->getOperand(0);
13795   Value *Op1 = SVI->getOperand(1);
13796   IRBuilder<> Builder(SI);
13797 
13798   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
13799   // vectors to integer vectors.
13800   if (EltTy->isPointerTy()) {
13801     Type *IntTy = DL.getIntPtrType(EltTy);
13802 
13803     // Convert to the corresponding integer vector.
13804     Type *IntVecTy =
13805         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
13806     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
13807     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
13808 
13809     SubVecTy = VectorType::get(IntTy, LaneLen);
13810   }
13811 
13812   // The base address of the store.
13813   Value *BaseAddr = SI->getPointerOperand();
13814 
13815   if (NumStores > 1) {
13816     // If we're going to generate more than one store, reset the lane length
13817     // and sub-vector type to something legal.
13818     LaneLen /= NumStores;
13819     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
13820 
13821     // We will compute the pointer operand of each store from the original base
13822     // address using GEPs. Cast the base address to a pointer to the scalar
13823     // element type.
13824     BaseAddr = Builder.CreateBitCast(
13825         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
13826                       SI->getPointerAddressSpace()));
13827   }
13828 
13829   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
13830 
13831   auto Mask = SVI->getShuffleMask();
13832 
13833   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
13834   Type *Tys[] = {Int8Ptr, SubVecTy};
13835   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
13836                                              Intrinsic::arm_neon_vst3,
13837                                              Intrinsic::arm_neon_vst4};
13838 
13839   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
13840 
13841     // If we generating more than one store, we compute the base address of
13842     // subsequent stores as an offset from the previous.
13843     if (StoreCount > 0)
13844       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
13845 
13846     SmallVector<Value *, 6> Ops;
13847     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
13848 
13849     Function *VstNFunc =
13850         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
13851 
13852     // Split the shufflevector operands into sub vectors for the new vstN call.
13853     for (unsigned i = 0; i < Factor; i++) {
13854       unsigned IdxI = StoreCount * LaneLen * Factor + i;
13855       if (Mask[IdxI] >= 0) {
13856         Ops.push_back(Builder.CreateShuffleVector(
13857             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
13858       } else {
13859         unsigned StartMask = 0;
13860         for (unsigned j = 1; j < LaneLen; j++) {
13861           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
13862           if (Mask[IdxJ * Factor + IdxI] >= 0) {
13863             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
13864             break;
13865           }
13866         }
13867         // Note: If all elements in a chunk are undefs, StartMask=0!
13868         // Note: Filling undef gaps with random elements is ok, since
13869         // those elements were being written anyway (with undefs).
13870         // In the case of all undefs we're defaulting to using elems from 0
13871         // Note: StartMask cannot be negative, it's checked in
13872         // isReInterleaveMask
13873         Ops.push_back(Builder.CreateShuffleVector(
13874             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
13875       }
13876     }
13877 
13878     Ops.push_back(Builder.getInt32(SI->getAlignment()));
13879     Builder.CreateCall(VstNFunc, Ops);
13880   }
13881   return true;
13882 }
13883 
13884 enum HABaseType {
13885   HA_UNKNOWN = 0,
13886   HA_FLOAT,
13887   HA_DOUBLE,
13888   HA_VECT64,
13889   HA_VECT128
13890 };
13891 
13892 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
13893                                    uint64_t &Members) {
13894   if (auto *ST = dyn_cast<StructType>(Ty)) {
13895     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
13896       uint64_t SubMembers = 0;
13897       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
13898         return false;
13899       Members += SubMembers;
13900     }
13901   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
13902     uint64_t SubMembers = 0;
13903     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
13904       return false;
13905     Members += SubMembers * AT->getNumElements();
13906   } else if (Ty->isFloatTy()) {
13907     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
13908       return false;
13909     Members = 1;
13910     Base = HA_FLOAT;
13911   } else if (Ty->isDoubleTy()) {
13912     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
13913       return false;
13914     Members = 1;
13915     Base = HA_DOUBLE;
13916   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
13917     Members = 1;
13918     switch (Base) {
13919     case HA_FLOAT:
13920     case HA_DOUBLE:
13921       return false;
13922     case HA_VECT64:
13923       return VT->getBitWidth() == 64;
13924     case HA_VECT128:
13925       return VT->getBitWidth() == 128;
13926     case HA_UNKNOWN:
13927       switch (VT->getBitWidth()) {
13928       case 64:
13929         Base = HA_VECT64;
13930         return true;
13931       case 128:
13932         Base = HA_VECT128;
13933         return true;
13934       default:
13935         return false;
13936       }
13937     }
13938   }
13939 
13940   return (Members > 0 && Members <= 4);
13941 }
13942 
13943 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
13944 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
13945 /// passing according to AAPCS rules.
13946 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
13947     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
13948   if (getEffectiveCallingConv(CallConv, isVarArg) !=
13949       CallingConv::ARM_AAPCS_VFP)
13950     return false;
13951 
13952   HABaseType Base = HA_UNKNOWN;
13953   uint64_t Members = 0;
13954   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
13955   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
13956 
13957   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
13958   return IsHA || IsIntArray;
13959 }
13960 
13961 unsigned ARMTargetLowering::getExceptionPointerRegister(
13962     const Constant *PersonalityFn) const {
13963   // Platforms which do not use SjLj EH may return values in these registers
13964   // via the personality function.
13965   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
13966 }
13967 
13968 unsigned ARMTargetLowering::getExceptionSelectorRegister(
13969     const Constant *PersonalityFn) const {
13970   // Platforms which do not use SjLj EH may return values in these registers
13971   // via the personality function.
13972   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
13973 }
13974 
13975 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
13976   // Update IsSplitCSR in ARMFunctionInfo.
13977   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
13978   AFI->setIsSplitCSR(true);
13979 }
13980 
13981 void ARMTargetLowering::insertCopiesSplitCSR(
13982     MachineBasicBlock *Entry,
13983     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
13984   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
13985   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
13986   if (!IStart)
13987     return;
13988 
13989   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
13990   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
13991   MachineBasicBlock::iterator MBBI = Entry->begin();
13992   for (const MCPhysReg *I = IStart; *I; ++I) {
13993     const TargetRegisterClass *RC = nullptr;
13994     if (ARM::GPRRegClass.contains(*I))
13995       RC = &ARM::GPRRegClass;
13996     else if (ARM::DPRRegClass.contains(*I))
13997       RC = &ARM::DPRRegClass;
13998     else
13999       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14000 
14001     unsigned NewVR = MRI->createVirtualRegister(RC);
14002     // Create copy from CSR to a virtual register.
14003     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14004     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14005     // nounwind. If we want to generalize this later, we may need to emit
14006     // CFI pseudo-instructions.
14007     assert(Entry->getParent()->getFunction()->hasFnAttribute(
14008                Attribute::NoUnwind) &&
14009            "Function should be nounwind in insertCopiesSplitCSR!");
14010     Entry->addLiveIn(*I);
14011     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14012         .addReg(*I);
14013 
14014     // Insert the copy-back instructions right before the terminator.
14015     for (auto *Exit : Exits)
14016       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14017               TII->get(TargetOpcode::COPY), *I)
14018           .addReg(NewVR);
14019   }
14020 }
14021