1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ARMISelLowering.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.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 "Utils/ARMBaseInfo.h"
28 #include "llvm/ADT/APFloat.h"
29 #include "llvm/ADT/APInt.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/BitVector.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/StringRef.h"
39 #include "llvm/ADT/StringSwitch.h"
40 #include "llvm/ADT/Triple.h"
41 #include "llvm/ADT/Twine.h"
42 #include "llvm/Analysis/VectorUtils.h"
43 #include "llvm/CodeGen/CallingConvLower.h"
44 #include "llvm/CodeGen/ISDOpcodes.h"
45 #include "llvm/CodeGen/IntrinsicLowering.h"
46 #include "llvm/CodeGen/MachineBasicBlock.h"
47 #include "llvm/CodeGen/MachineConstantPool.h"
48 #include "llvm/CodeGen/MachineFrameInfo.h"
49 #include "llvm/CodeGen/MachineFunction.h"
50 #include "llvm/CodeGen/MachineInstr.h"
51 #include "llvm/CodeGen/MachineInstrBuilder.h"
52 #include "llvm/CodeGen/MachineJumpTableInfo.h"
53 #include "llvm/CodeGen/MachineMemOperand.h"
54 #include "llvm/CodeGen/MachineOperand.h"
55 #include "llvm/CodeGen/MachineRegisterInfo.h"
56 #include "llvm/CodeGen/MachineValueType.h"
57 #include "llvm/CodeGen/RuntimeLibcalls.h"
58 #include "llvm/CodeGen/SelectionDAG.h"
59 #include "llvm/CodeGen/SelectionDAGNodes.h"
60 #include "llvm/CodeGen/ValueTypes.h"
61 #include "llvm/IR/Attributes.h"
62 #include "llvm/IR/CallingConv.h"
63 #include "llvm/IR/Constant.h"
64 #include "llvm/IR/Constants.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/KnownBits.h"
95 #include "llvm/Support/MathExtras.h"
96 #include "llvm/Support/raw_ostream.h"
97 #include "llvm/Target/TargetInstrInfo.h"
98 #include "llvm/Target/TargetLowering.h"
99 #include "llvm/Target/TargetMachine.h"
100 #include "llvm/Target/TargetOpcodes.h"
101 #include "llvm/Target/TargetOptions.h"
102 #include "llvm/Target/TargetRegisterInfo.h"
103 #include "llvm/Target/TargetSubtargetInfo.h"
104 #include <algorithm>
105 #include <cassert>
106 #include <cstdint>
107 #include <cstdlib>
108 #include <iterator>
109 #include <limits>
110 #include <string>
111 #include <tuple>
112 #include <utility>
113 #include <vector>
114 
115 using namespace llvm;
116 
117 #define DEBUG_TYPE "arm-isel"
118 
119 STATISTIC(NumTailCalls, "Number of tail calls");
120 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
121 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
122 STATISTIC(NumConstpoolPromoted,
123   "Number of constants with their storage promoted into constant pools");
124 
125 static cl::opt<bool>
126 ARMInterworking("arm-interworking", cl::Hidden,
127   cl::desc("Enable / disable ARM interworking (for debugging only)"),
128   cl::init(true));
129 
130 static cl::opt<bool> EnableConstpoolPromotion(
131     "arm-promote-constant", cl::Hidden,
132     cl::desc("Enable / disable promotion of unnamed_addr constants into "
133              "constant pools"),
134     cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
135 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
136     "arm-promote-constant-max-size", cl::Hidden,
137     cl::desc("Maximum size of constant to promote into a constant pool"),
138     cl::init(64));
139 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
140     "arm-promote-constant-max-total", cl::Hidden,
141     cl::desc("Maximum size of ALL constants to promote into a constant pool"),
142     cl::init(128));
143 
144 // The APCS parameter registers.
145 static const MCPhysReg GPRArgRegs[] = {
146   ARM::R0, ARM::R1, ARM::R2, ARM::R3
147 };
148 
149 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
150                                        MVT PromotedBitwiseVT) {
151   if (VT != PromotedLdStVT) {
152     setOperationAction(ISD::LOAD, VT, Promote);
153     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
154 
155     setOperationAction(ISD::STORE, VT, Promote);
156     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
157   }
158 
159   MVT ElemTy = VT.getVectorElementType();
160   if (ElemTy != MVT::f64)
161     setOperationAction(ISD::SETCC, VT, Custom);
162   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
163   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
164   if (ElemTy == MVT::i32) {
165     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
166     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
167     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
168     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
169   } else {
170     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
171     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
172     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
173     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
174   }
175   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
176   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
177   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
178   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
179   setOperationAction(ISD::SELECT,            VT, Expand);
180   setOperationAction(ISD::SELECT_CC,         VT, Expand);
181   setOperationAction(ISD::VSELECT,           VT, Expand);
182   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
183   if (VT.isInteger()) {
184     setOperationAction(ISD::SHL, VT, Custom);
185     setOperationAction(ISD::SRA, VT, Custom);
186     setOperationAction(ISD::SRL, VT, Custom);
187   }
188 
189   // Promote all bit-wise operations.
190   if (VT.isInteger() && VT != PromotedBitwiseVT) {
191     setOperationAction(ISD::AND, VT, Promote);
192     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
193     setOperationAction(ISD::OR,  VT, Promote);
194     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
195     setOperationAction(ISD::XOR, VT, Promote);
196     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
197   }
198 
199   // Neon does not support vector divide/remainder operations.
200   setOperationAction(ISD::SDIV, VT, Expand);
201   setOperationAction(ISD::UDIV, VT, Expand);
202   setOperationAction(ISD::FDIV, VT, Expand);
203   setOperationAction(ISD::SREM, VT, Expand);
204   setOperationAction(ISD::UREM, VT, Expand);
205   setOperationAction(ISD::FREM, VT, Expand);
206 
207   if (!VT.isFloatingPoint() &&
208       VT != MVT::v2i64 && VT != MVT::v1i64)
209     for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
210       setOperationAction(Opcode, VT, Legal);
211 }
212 
213 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
214   addRegisterClass(VT, &ARM::DPRRegClass);
215   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
216 }
217 
218 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
219   addRegisterClass(VT, &ARM::DPairRegClass);
220   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
221 }
222 
223 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
224                                      const ARMSubtarget &STI)
225     : TargetLowering(TM), Subtarget(&STI) {
226   RegInfo = Subtarget->getRegisterInfo();
227   Itins = Subtarget->getInstrItineraryData();
228 
229   setBooleanContents(ZeroOrOneBooleanContent);
230   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
231 
232   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
233       !Subtarget->isTargetWatchOS()) {
234     const auto &E = Subtarget->getTargetTriple().getEnvironment();
235 
236     bool IsHFTarget = E == Triple::EABIHF || E == Triple::GNUEABIHF ||
237                       E == Triple::MuslEABIHF;
238     // Windows is a special case.  Technically, we will replace all of the "GNU"
239     // calls with calls to MSVCRT if appropriate and adjust the calling
240     // convention then.
241     IsHFTarget = IsHFTarget || Subtarget->isTargetWindows();
242 
243     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
244       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
245                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
246                                        : CallingConv::ARM_AAPCS);
247   }
248 
249   if (Subtarget->isTargetMachO()) {
250     // Uses VFP for Thumb libfuncs if available.
251     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
252         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
253       static const struct {
254         const RTLIB::Libcall Op;
255         const char * const Name;
256         const ISD::CondCode Cond;
257       } LibraryCalls[] = {
258         // Single-precision floating-point arithmetic.
259         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
260         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
261         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
262         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
263 
264         // Double-precision floating-point arithmetic.
265         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
266         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
267         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
268         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
269 
270         // Single-precision comparisons.
271         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
272         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
273         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
274         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
275         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
276         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
277         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
278         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
279 
280         // Double-precision comparisons.
281         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
282         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
283         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
284         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
285         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
286         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
287         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
288         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
289 
290         // Floating-point to integer conversions.
291         // i64 conversions are done via library routines even when generating VFP
292         // instructions, so use the same ones.
293         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
294         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
295         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
296         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
297 
298         // Conversions between floating types.
299         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
300         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
301 
302         // Integer to floating-point conversions.
303         // i64 conversions are done via library routines even when generating VFP
304         // instructions, so use the same ones.
305         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
306         // e.g., __floatunsidf vs. __floatunssidfvfp.
307         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
308         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
309         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
310         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
311       };
312 
313       for (const auto &LC : LibraryCalls) {
314         setLibcallName(LC.Op, LC.Name);
315         if (LC.Cond != ISD::SETCC_INVALID)
316           setCmpLibcallCC(LC.Op, LC.Cond);
317       }
318     }
319 
320     // Set the correct calling convention for ARMv7k WatchOS. It's just
321     // AAPCS_VFP for functions as simple as libcalls.
322     if (Subtarget->isTargetWatchABI()) {
323       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
324         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
325     }
326   }
327 
328   // These libcalls are not available in 32-bit.
329   setLibcallName(RTLIB::SHL_I128, nullptr);
330   setLibcallName(RTLIB::SRL_I128, nullptr);
331   setLibcallName(RTLIB::SRA_I128, nullptr);
332 
333   // RTLIB
334   if (Subtarget->isAAPCS_ABI() &&
335       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
336        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
337     static const struct {
338       const RTLIB::Libcall Op;
339       const char * const Name;
340       const CallingConv::ID CC;
341       const ISD::CondCode Cond;
342     } LibraryCalls[] = {
343       // Double-precision floating-point arithmetic helper functions
344       // RTABI chapter 4.1.2, Table 2
345       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
346       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
347       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
348       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349 
350       // Double-precision floating-point comparison helper functions
351       // RTABI chapter 4.1.2, Table 3
352       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
353       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
354       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
355       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
356       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
357       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
358       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
359       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
360 
361       // Single-precision floating-point arithmetic helper functions
362       // RTABI chapter 4.1.2, Table 4
363       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
364       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
365       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
366       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
367 
368       // Single-precision floating-point comparison helper functions
369       // RTABI chapter 4.1.2, Table 5
370       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
371       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
372       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
373       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
374       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
375       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
376       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
377       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
378 
379       // Floating-point to integer conversions.
380       // RTABI chapter 4.1.2, Table 6
381       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
382       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
383       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
384       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
385       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
386       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
387       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
388       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
389 
390       // Conversions between floating types.
391       // RTABI chapter 4.1.2, Table 7
392       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
393       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
394       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
395 
396       // Integer to floating-point conversions.
397       // RTABI chapter 4.1.2, Table 8
398       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
399       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
400       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
401       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
402       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
403       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
404       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
406 
407       // Long long helper functions
408       // RTABI chapter 4.2, Table 9
409       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
410       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
411       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
412       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
413 
414       // Integer division functions
415       // RTABI chapter 4.3.1
416       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
417       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
418       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
419       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
420       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
421       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
422       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
423       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
424     };
425 
426     for (const auto &LC : LibraryCalls) {
427       setLibcallName(LC.Op, LC.Name);
428       setLibcallCallingConv(LC.Op, LC.CC);
429       if (LC.Cond != ISD::SETCC_INVALID)
430         setCmpLibcallCC(LC.Op, LC.Cond);
431     }
432 
433     // EABI dependent RTLIB
434     if (TM.Options.EABIVersion == EABI::EABI4 ||
435         TM.Options.EABIVersion == EABI::EABI5) {
436       static const struct {
437         const RTLIB::Libcall Op;
438         const char *const Name;
439         const CallingConv::ID CC;
440         const ISD::CondCode Cond;
441       } MemOpsLibraryCalls[] = {
442         // Memory operations
443         // RTABI chapter 4.3.4
444         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
445         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
446         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
447       };
448 
449       for (const auto &LC : MemOpsLibraryCalls) {
450         setLibcallName(LC.Op, LC.Name);
451         setLibcallCallingConv(LC.Op, LC.CC);
452         if (LC.Cond != ISD::SETCC_INVALID)
453           setCmpLibcallCC(LC.Op, LC.Cond);
454       }
455     }
456   }
457 
458   if (Subtarget->isTargetWindows()) {
459     static const struct {
460       const RTLIB::Libcall Op;
461       const char * const Name;
462       const CallingConv::ID CC;
463     } LibraryCalls[] = {
464       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
465       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
466       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
467       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
468       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
469       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
470       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
471       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
472     };
473 
474     for (const auto &LC : LibraryCalls) {
475       setLibcallName(LC.Op, LC.Name);
476       setLibcallCallingConv(LC.Op, LC.CC);
477     }
478   }
479 
480   // Use divmod compiler-rt calls for iOS 5.0 and later.
481   if (Subtarget->isTargetMachO() &&
482       !(Subtarget->isTargetIOS() &&
483         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
484     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
485     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
486   }
487 
488   // The half <-> float conversion functions are always soft-float on
489   // non-watchos platforms, but are needed for some targets which use a
490   // hard-float calling convention by default.
491   if (!Subtarget->isTargetWatchABI()) {
492     if (Subtarget->isAAPCS_ABI()) {
493       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
494       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
495       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
496     } else {
497       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
498       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
499       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
500     }
501   }
502 
503   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
504   // a __gnu_ prefix (which is the default).
505   if (Subtarget->isTargetAEABI()) {
506     static const struct {
507       const RTLIB::Libcall Op;
508       const char * const Name;
509       const CallingConv::ID CC;
510     } LibraryCalls[] = {
511       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
512       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
513       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
514     };
515 
516     for (const auto &LC : LibraryCalls) {
517       setLibcallName(LC.Op, LC.Name);
518       setLibcallCallingConv(LC.Op, LC.CC);
519     }
520   }
521 
522   if (Subtarget->isThumb1Only())
523     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
524   else
525     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
526 
527   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
528       !Subtarget->isThumb1Only()) {
529     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
530     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
531   }
532 
533   for (MVT VT : MVT::vector_valuetypes()) {
534     for (MVT InnerVT : MVT::vector_valuetypes()) {
535       setTruncStoreAction(VT, InnerVT, Expand);
536       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
537       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
538       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
539     }
540 
541     setOperationAction(ISD::MULHS, VT, Expand);
542     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
543     setOperationAction(ISD::MULHU, VT, Expand);
544     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
545 
546     setOperationAction(ISD::BSWAP, VT, Expand);
547   }
548 
549   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
550   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
551 
552   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
553   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
554 
555   if (Subtarget->hasNEON()) {
556     addDRTypeForNEON(MVT::v2f32);
557     addDRTypeForNEON(MVT::v8i8);
558     addDRTypeForNEON(MVT::v4i16);
559     addDRTypeForNEON(MVT::v2i32);
560     addDRTypeForNEON(MVT::v1i64);
561 
562     addQRTypeForNEON(MVT::v4f32);
563     addQRTypeForNEON(MVT::v2f64);
564     addQRTypeForNEON(MVT::v16i8);
565     addQRTypeForNEON(MVT::v8i16);
566     addQRTypeForNEON(MVT::v4i32);
567     addQRTypeForNEON(MVT::v2i64);
568 
569     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
570     // neither Neon nor VFP support any arithmetic operations on it.
571     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
572     // supported for v4f32.
573     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
574     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
575     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
576     // FIXME: Code duplication: FDIV and FREM are expanded always, see
577     // ARMTargetLowering::addTypeForNEON method for details.
578     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
579     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
580     // FIXME: Create unittest.
581     // In another words, find a way when "copysign" appears in DAG with vector
582     // operands.
583     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
584     // FIXME: Code duplication: SETCC has custom operation action, see
585     // ARMTargetLowering::addTypeForNEON method for details.
586     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
587     // FIXME: Create unittest for FNEG and for FABS.
588     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
589     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
590     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
591     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
592     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
593     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
594     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
595     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
596     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
597     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
598     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
599     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
600     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
601     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
602     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
603     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
604     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
605     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
606 
607     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
608     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
609     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
610     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
611     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
612     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
613     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
614     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
615     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
616     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
617     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
618     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
619     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
620     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
621 
622     // Mark v2f32 intrinsics.
623     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
624     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
625     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
626     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
627     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
628     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
629     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
630     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
631     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
632     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
633     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
634     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
635     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
636     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
637 
638     // Neon does not support some operations on v1i64 and v2i64 types.
639     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
640     // Custom handling for some quad-vector types to detect VMULL.
641     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
642     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
643     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
644     // Custom handling for some vector types to avoid expensive expansions
645     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
646     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
647     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
648     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
649     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
650     // a destination type that is wider than the source, and nor does
651     // it have a FP_TO_[SU]INT instruction with a narrower destination than
652     // source.
653     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
654     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
655     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
656     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
657 
658     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
659     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
660 
661     // NEON does not have single instruction CTPOP for vectors with element
662     // types wider than 8-bits.  However, custom lowering can leverage the
663     // v8i8/v16i8 vcnt instruction.
664     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
665     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
666     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
667     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
668     setOperationAction(ISD::CTPOP,      MVT::v1i64, Expand);
669     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
670 
671     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
672     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
673 
674     // NEON does not have single instruction CTTZ for vectors.
675     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
676     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
677     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
678     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
679 
680     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
681     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
682     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
683     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
684 
685     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
686     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
687     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
688     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
689 
690     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
691     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
692     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
693     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
694 
695     // NEON only has FMA instructions as of VFP4.
696     if (!Subtarget->hasVFP4()) {
697       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
698       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
699     }
700 
701     setTargetDAGCombine(ISD::INTRINSIC_VOID);
702     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
703     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
704     setTargetDAGCombine(ISD::SHL);
705     setTargetDAGCombine(ISD::SRL);
706     setTargetDAGCombine(ISD::SRA);
707     setTargetDAGCombine(ISD::SIGN_EXTEND);
708     setTargetDAGCombine(ISD::ZERO_EXTEND);
709     setTargetDAGCombine(ISD::ANY_EXTEND);
710     setTargetDAGCombine(ISD::BUILD_VECTOR);
711     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
712     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
713     setTargetDAGCombine(ISD::STORE);
714     setTargetDAGCombine(ISD::FP_TO_SINT);
715     setTargetDAGCombine(ISD::FP_TO_UINT);
716     setTargetDAGCombine(ISD::FDIV);
717     setTargetDAGCombine(ISD::LOAD);
718 
719     // It is legal to extload from v4i8 to v4i16 or v4i32.
720     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
721                    MVT::v2i32}) {
722       for (MVT VT : MVT::integer_vector_valuetypes()) {
723         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
724         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
725         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
726       }
727     }
728   }
729 
730   if (Subtarget->isFPOnlySP()) {
731     // When targeting a floating-point unit with only single-precision
732     // operations, f64 is legal for the few double-precision instructions which
733     // are present However, no double-precision operations other than moves,
734     // loads and stores are provided by the hardware.
735     setOperationAction(ISD::FADD,       MVT::f64, Expand);
736     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
737     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
738     setOperationAction(ISD::FMA,        MVT::f64, Expand);
739     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
740     setOperationAction(ISD::FREM,       MVT::f64, Expand);
741     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
742     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
743     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
744     setOperationAction(ISD::FABS,       MVT::f64, Expand);
745     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
746     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
747     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
748     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
749     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
750     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
751     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
752     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
753     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
754     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
755     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
756     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
757     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
758     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
759     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
760     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
761     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
762     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
763     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
764     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
765     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
766     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
767   }
768 
769   computeRegisterProperties(Subtarget->getRegisterInfo());
770 
771   // ARM does not have floating-point extending loads.
772   for (MVT VT : MVT::fp_valuetypes()) {
773     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
774     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
775   }
776 
777   // ... or truncating stores
778   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
779   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
780   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
781 
782   // ARM does not have i1 sign extending load.
783   for (MVT VT : MVT::integer_valuetypes())
784     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
785 
786   // ARM supports all 4 flavors of integer indexed load / store.
787   if (!Subtarget->isThumb1Only()) {
788     for (unsigned im = (unsigned)ISD::PRE_INC;
789          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
790       setIndexedLoadAction(im,  MVT::i1,  Legal);
791       setIndexedLoadAction(im,  MVT::i8,  Legal);
792       setIndexedLoadAction(im,  MVT::i16, Legal);
793       setIndexedLoadAction(im,  MVT::i32, Legal);
794       setIndexedStoreAction(im, MVT::i1,  Legal);
795       setIndexedStoreAction(im, MVT::i8,  Legal);
796       setIndexedStoreAction(im, MVT::i16, Legal);
797       setIndexedStoreAction(im, MVT::i32, Legal);
798     }
799   } else {
800     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
801     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
802     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
803   }
804 
805   setOperationAction(ISD::SADDO, MVT::i32, Custom);
806   setOperationAction(ISD::UADDO, MVT::i32, Custom);
807   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
808   setOperationAction(ISD::USUBO, MVT::i32, Custom);
809 
810   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
811   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
812 
813   // i64 operation support.
814   setOperationAction(ISD::MUL,     MVT::i64, Expand);
815   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
816   if (Subtarget->isThumb1Only()) {
817     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
818     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
819   }
820   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
821       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
822     setOperationAction(ISD::MULHS, MVT::i32, Expand);
823 
824   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
825   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
826   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
827   setOperationAction(ISD::SRL,       MVT::i64, Custom);
828   setOperationAction(ISD::SRA,       MVT::i64, Custom);
829   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
830 
831   setOperationAction(ISD::ADDC,      MVT::i32, Custom);
832   setOperationAction(ISD::ADDE,      MVT::i32, Custom);
833   setOperationAction(ISD::SUBC,      MVT::i32, Custom);
834   setOperationAction(ISD::SUBE,      MVT::i32, Custom);
835 
836   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
837     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
838 
839   // ARM does not have ROTL.
840   setOperationAction(ISD::ROTL, MVT::i32, Expand);
841   for (MVT VT : MVT::vector_valuetypes()) {
842     setOperationAction(ISD::ROTL, VT, Expand);
843     setOperationAction(ISD::ROTR, VT, Expand);
844   }
845   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
846   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
847   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
848     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
849 
850   // @llvm.readcyclecounter requires the Performance Monitors extension.
851   // Default to the 0 expansion on unsupported platforms.
852   // FIXME: Technically there are older ARM CPUs that have
853   // implementation-specific ways of obtaining this information.
854   if (Subtarget->hasPerfMon())
855     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
856 
857   // Only ARMv6 has BSWAP.
858   if (!Subtarget->hasV6Ops())
859     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
860 
861   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
862                                         : Subtarget->hasDivideInARMMode();
863   if (!hasDivide) {
864     // These are expanded into libcalls if the cpu doesn't have HW divider.
865     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
866     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
867   }
868 
869   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
870     setOperationAction(ISD::SDIV, MVT::i32, Custom);
871     setOperationAction(ISD::UDIV, MVT::i32, Custom);
872 
873     setOperationAction(ISD::SDIV, MVT::i64, Custom);
874     setOperationAction(ISD::UDIV, MVT::i64, Custom);
875   }
876 
877   setOperationAction(ISD::SREM,  MVT::i32, Expand);
878   setOperationAction(ISD::UREM,  MVT::i32, Expand);
879 
880   // Register based DivRem for AEABI (RTABI 4.2)
881   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
882       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
883       Subtarget->isTargetWindows()) {
884     setOperationAction(ISD::SREM, MVT::i64, Custom);
885     setOperationAction(ISD::UREM, MVT::i64, Custom);
886     HasStandaloneRem = false;
887 
888     if (Subtarget->isTargetWindows()) {
889       const struct {
890         const RTLIB::Libcall Op;
891         const char * const Name;
892         const CallingConv::ID CC;
893       } LibraryCalls[] = {
894         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
895         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
896         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
897         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
898 
899         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
900         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
901         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
902         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
903       };
904 
905       for (const auto &LC : LibraryCalls) {
906         setLibcallName(LC.Op, LC.Name);
907         setLibcallCallingConv(LC.Op, LC.CC);
908       }
909     } else {
910       const struct {
911         const RTLIB::Libcall Op;
912         const char * const Name;
913         const CallingConv::ID CC;
914       } LibraryCalls[] = {
915         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
916         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
917         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
918         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
919 
920         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
921         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
922         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
923         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
924       };
925 
926       for (const auto &LC : LibraryCalls) {
927         setLibcallName(LC.Op, LC.Name);
928         setLibcallCallingConv(LC.Op, LC.CC);
929       }
930     }
931 
932     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
933     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
934     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
935     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
936   } else {
937     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
938     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
939   }
940 
941   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
942     for (auto &VT : {MVT::f32, MVT::f64})
943       setOperationAction(ISD::FPOWI, VT, Custom);
944 
945   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
946   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
947   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
948   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
949 
950   setOperationAction(ISD::TRAP, MVT::Other, Legal);
951 
952   // Use the default implementation.
953   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
954   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
955   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
956   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
957   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
958   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
959 
960   if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
961     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
962   else
963     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
964 
965   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
966   // the default expansion.
967   InsertFencesForAtomic = false;
968   if (Subtarget->hasAnyDataBarrier() &&
969       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
970     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
971     // to ldrex/strex loops already.
972     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
973     if (!Subtarget->isThumb() || !Subtarget->isMClass())
974       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
975 
976     // On v8, we have particularly efficient implementations of atomic fences
977     // if they can be combined with nearby atomic loads and stores.
978     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
979       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
980       InsertFencesForAtomic = true;
981     }
982   } else {
983     // If there's anything we can use as a barrier, go through custom lowering
984     // for ATOMIC_FENCE.
985     // If target has DMB in thumb, Fences can be inserted.
986     if (Subtarget->hasDataBarrier())
987       InsertFencesForAtomic = true;
988 
989     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
990                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
991 
992     // Set them all for expansion, which will force libcalls.
993     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
994     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
995     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
996     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
997     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
998     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
999     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1000     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1001     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1002     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1003     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1004     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1005     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1006     // Unordered/Monotonic case.
1007     if (!InsertFencesForAtomic) {
1008       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1009       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1010     }
1011   }
1012 
1013   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1014 
1015   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1016   if (!Subtarget->hasV6Ops()) {
1017     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1018     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1019   }
1020   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1021 
1022   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1023       !Subtarget->isThumb1Only()) {
1024     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1025     // iff target supports vfp2.
1026     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1027     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1028   }
1029 
1030   // We want to custom lower some of our intrinsics.
1031   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1032   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1033   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1034   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1035   if (Subtarget->useSjLjEH())
1036     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1037 
1038   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1039   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1040   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1041   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1042   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1043   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1044   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1045   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1046   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1047 
1048   // Thumb-1 cannot currently select ARMISD::SUBE.
1049   if (!Subtarget->isThumb1Only())
1050     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1051 
1052   setOperationAction(ISD::BRCOND,    MVT::Other, Expand);
1053   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1054   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1055   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1056   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1057 
1058   // We don't support sin/cos/fmod/copysign/pow
1059   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1060   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1061   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1062   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1063   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1064   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1065   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1066   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1067   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1068       !Subtarget->isThumb1Only()) {
1069     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1070     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1071   }
1072   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1073   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1074 
1075   if (!Subtarget->hasVFP4()) {
1076     setOperationAction(ISD::FMA, MVT::f64, Expand);
1077     setOperationAction(ISD::FMA, MVT::f32, Expand);
1078   }
1079 
1080   // Various VFP goodness
1081   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1082     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1083     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1084       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1085       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1086     }
1087 
1088     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1089     if (!Subtarget->hasFP16()) {
1090       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1091       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1092     }
1093   }
1094 
1095   // Combine sin / cos into one node or libcall if possible.
1096   if (Subtarget->hasSinCos()) {
1097     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1098     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1099     if (Subtarget->isTargetWatchABI()) {
1100       setLibcallCallingConv(RTLIB::SINCOS_F32, CallingConv::ARM_AAPCS_VFP);
1101       setLibcallCallingConv(RTLIB::SINCOS_F64, CallingConv::ARM_AAPCS_VFP);
1102     }
1103     if (Subtarget->isTargetIOS() || Subtarget->isTargetWatchOS()) {
1104       // For iOS, we don't want to the normal expansion of a libcall to
1105       // sincos. We want to issue a libcall to __sincos_stret.
1106       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1107       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1108     }
1109   }
1110 
1111   // FP-ARMv8 implements a lot of rounding-like FP operations.
1112   if (Subtarget->hasFPARMv8()) {
1113     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1114     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1115     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1116     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1117     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1118     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1119     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1120     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1121     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1122     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1123     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1124     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1125 
1126     if (!Subtarget->isFPOnlySP()) {
1127       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1128       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1129       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1130       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1131       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1132       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1133       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1134       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1135     }
1136   }
1137 
1138   if (Subtarget->hasNEON()) {
1139     // vmin and vmax aren't available in a scalar form, so we use
1140     // a NEON instruction with an undef lane instead.
1141     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1142     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1143     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1144     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1145     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1146     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1147   }
1148 
1149   // We have target-specific dag combine patterns for the following nodes:
1150   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1151   setTargetDAGCombine(ISD::ADD);
1152   setTargetDAGCombine(ISD::SUB);
1153   setTargetDAGCombine(ISD::MUL);
1154   setTargetDAGCombine(ISD::AND);
1155   setTargetDAGCombine(ISD::OR);
1156   setTargetDAGCombine(ISD::XOR);
1157 
1158   if (Subtarget->hasV6Ops())
1159     setTargetDAGCombine(ISD::SRL);
1160 
1161   setStackPointerRegisterToSaveRestore(ARM::SP);
1162 
1163   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1164       !Subtarget->hasVFP2())
1165     setSchedulingPreference(Sched::RegPressure);
1166   else
1167     setSchedulingPreference(Sched::Hybrid);
1168 
1169   //// temporary - rewrite interface to use type
1170   MaxStoresPerMemset = 8;
1171   MaxStoresPerMemsetOptSize = 4;
1172   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1173   MaxStoresPerMemcpyOptSize = 2;
1174   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1175   MaxStoresPerMemmoveOptSize = 2;
1176 
1177   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1178   // are at least 4 bytes aligned.
1179   setMinStackArgumentAlignment(4);
1180 
1181   // Prefer likely predicted branches to selects on out-of-order cores.
1182   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1183 
1184   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1185 }
1186 
1187 bool ARMTargetLowering::useSoftFloat() const {
1188   return Subtarget->useSoftFloat();
1189 }
1190 
1191 // FIXME: It might make sense to define the representative register class as the
1192 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1193 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1194 // SPR's representative would be DPR_VFP2. This should work well if register
1195 // pressure tracking were modified such that a register use would increment the
1196 // pressure of the register class's representative and all of it's super
1197 // classes' representatives transitively. We have not implemented this because
1198 // of the difficulty prior to coalescing of modeling operand register classes
1199 // due to the common occurrence of cross class copies and subregister insertions
1200 // and extractions.
1201 std::pair<const TargetRegisterClass *, uint8_t>
1202 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1203                                            MVT VT) const {
1204   const TargetRegisterClass *RRC = nullptr;
1205   uint8_t Cost = 1;
1206   switch (VT.SimpleTy) {
1207   default:
1208     return TargetLowering::findRepresentativeClass(TRI, VT);
1209   // Use DPR as representative register class for all floating point
1210   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1211   // the cost is 1 for both f32 and f64.
1212   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1213   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1214     RRC = &ARM::DPRRegClass;
1215     // When NEON is used for SP, only half of the register file is available
1216     // because operations that define both SP and DP results will be constrained
1217     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1218     // coalescing by double-counting the SP regs. See the FIXME above.
1219     if (Subtarget->useNEONForSinglePrecisionFP())
1220       Cost = 2;
1221     break;
1222   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1223   case MVT::v4f32: case MVT::v2f64:
1224     RRC = &ARM::DPRRegClass;
1225     Cost = 2;
1226     break;
1227   case MVT::v4i64:
1228     RRC = &ARM::DPRRegClass;
1229     Cost = 4;
1230     break;
1231   case MVT::v8i64:
1232     RRC = &ARM::DPRRegClass;
1233     Cost = 8;
1234     break;
1235   }
1236   return std::make_pair(RRC, Cost);
1237 }
1238 
1239 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1240   switch ((ARMISD::NodeType)Opcode) {
1241   case ARMISD::FIRST_NUMBER:  break;
1242   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1243   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1244   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1245   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1246   case ARMISD::CALL:          return "ARMISD::CALL";
1247   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1248   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1249   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1250   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1251   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1252   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1253   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1254   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1255   case ARMISD::CMP:           return "ARMISD::CMP";
1256   case ARMISD::CMN:           return "ARMISD::CMN";
1257   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1258   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1259   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1260   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1261   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1262 
1263   case ARMISD::CMOV:          return "ARMISD::CMOV";
1264 
1265   case ARMISD::SSAT:          return "ARMISD::SSAT";
1266 
1267   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1268   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1269   case ARMISD::RRX:           return "ARMISD::RRX";
1270 
1271   case ARMISD::ADDC:          return "ARMISD::ADDC";
1272   case ARMISD::ADDE:          return "ARMISD::ADDE";
1273   case ARMISD::SUBC:          return "ARMISD::SUBC";
1274   case ARMISD::SUBE:          return "ARMISD::SUBE";
1275 
1276   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1277   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1278 
1279   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1280   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1281   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1282 
1283   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1284 
1285   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1286 
1287   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1288 
1289   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1290 
1291   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1292 
1293   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1294   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1295 
1296   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1297   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1298   case ARMISD::VCGE:          return "ARMISD::VCGE";
1299   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1300   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1301   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1302   case ARMISD::VCGT:          return "ARMISD::VCGT";
1303   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1304   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1305   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1306   case ARMISD::VTST:          return "ARMISD::VTST";
1307 
1308   case ARMISD::VSHL:          return "ARMISD::VSHL";
1309   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1310   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1311   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1312   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1313   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1314   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1315   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1316   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1317   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1318   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1319   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1320   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1321   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1322   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1323   case ARMISD::VSLI:          return "ARMISD::VSLI";
1324   case ARMISD::VSRI:          return "ARMISD::VSRI";
1325   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1326   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1327   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1328   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1329   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1330   case ARMISD::VDUP:          return "ARMISD::VDUP";
1331   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1332   case ARMISD::VEXT:          return "ARMISD::VEXT";
1333   case ARMISD::VREV64:        return "ARMISD::VREV64";
1334   case ARMISD::VREV32:        return "ARMISD::VREV32";
1335   case ARMISD::VREV16:        return "ARMISD::VREV16";
1336   case ARMISD::VZIP:          return "ARMISD::VZIP";
1337   case ARMISD::VUZP:          return "ARMISD::VUZP";
1338   case ARMISD::VTRN:          return "ARMISD::VTRN";
1339   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1340   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1341   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1342   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1343   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1344   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1345   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1346   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1347   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1348   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1349   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1350   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1351   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1352   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1353   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1354   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1355   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1356   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1357   case ARMISD::BFI:           return "ARMISD::BFI";
1358   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1359   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1360   case ARMISD::VBSL:          return "ARMISD::VBSL";
1361   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1362   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1363   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1364   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1365   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1366   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1367   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1368   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1369   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1370   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1371   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1372   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1373   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1374   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1375   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1376   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1377   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1378   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1379   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1380   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1381   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1382   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1383   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1384   }
1385   return nullptr;
1386 }
1387 
1388 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1389                                           EVT VT) const {
1390   if (!VT.isVector())
1391     return getPointerTy(DL);
1392   return VT.changeVectorElementTypeToInteger();
1393 }
1394 
1395 /// getRegClassFor - Return the register class that should be used for the
1396 /// specified value type.
1397 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1398   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1399   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1400   // load / store 4 to 8 consecutive D registers.
1401   if (Subtarget->hasNEON()) {
1402     if (VT == MVT::v4i64)
1403       return &ARM::QQPRRegClass;
1404     if (VT == MVT::v8i64)
1405       return &ARM::QQQQPRRegClass;
1406   }
1407   return TargetLowering::getRegClassFor(VT);
1408 }
1409 
1410 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1411 // source/dest is aligned and the copy size is large enough. We therefore want
1412 // to align such objects passed to memory intrinsics.
1413 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1414                                                unsigned &PrefAlign) const {
1415   if (!isa<MemIntrinsic>(CI))
1416     return false;
1417   MinSize = 8;
1418   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1419   // cycle faster than 4-byte aligned LDM.
1420   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1421   return true;
1422 }
1423 
1424 // Create a fast isel object.
1425 FastISel *
1426 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1427                                   const TargetLibraryInfo *libInfo) const {
1428   return ARM::createFastISel(funcInfo, libInfo);
1429 }
1430 
1431 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1432   unsigned NumVals = N->getNumValues();
1433   if (!NumVals)
1434     return Sched::RegPressure;
1435 
1436   for (unsigned i = 0; i != NumVals; ++i) {
1437     EVT VT = N->getValueType(i);
1438     if (VT == MVT::Glue || VT == MVT::Other)
1439       continue;
1440     if (VT.isFloatingPoint() || VT.isVector())
1441       return Sched::ILP;
1442   }
1443 
1444   if (!N->isMachineOpcode())
1445     return Sched::RegPressure;
1446 
1447   // Load are scheduled for latency even if there instruction itinerary
1448   // is not available.
1449   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1450   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1451 
1452   if (MCID.getNumDefs() == 0)
1453     return Sched::RegPressure;
1454   if (!Itins->isEmpty() &&
1455       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1456     return Sched::ILP;
1457 
1458   return Sched::RegPressure;
1459 }
1460 
1461 //===----------------------------------------------------------------------===//
1462 // Lowering Code
1463 //===----------------------------------------------------------------------===//
1464 
1465 static bool isSRL16(const SDValue &Op) {
1466   if (Op.getOpcode() != ISD::SRL)
1467     return false;
1468   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1469     return Const->getZExtValue() == 16;
1470   return false;
1471 }
1472 
1473 static bool isSRA16(const SDValue &Op) {
1474   if (Op.getOpcode() != ISD::SRA)
1475     return false;
1476   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1477     return Const->getZExtValue() == 16;
1478   return false;
1479 }
1480 
1481 static bool isSHL16(const SDValue &Op) {
1482   if (Op.getOpcode() != ISD::SHL)
1483     return false;
1484   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1485     return Const->getZExtValue() == 16;
1486   return false;
1487 }
1488 
1489 // Check for a signed 16-bit value. We special case SRA because it makes it
1490 // more simple when also looking for SRAs that aren't sign extending a
1491 // smaller value. Without the check, we'd need to take extra care with
1492 // checking order for some operations.
1493 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1494   if (isSRA16(Op))
1495     return isSHL16(Op.getOperand(0));
1496   return DAG.ComputeNumSignBits(Op) == 17;
1497 }
1498 
1499 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1500 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1501   switch (CC) {
1502   default: llvm_unreachable("Unknown condition code!");
1503   case ISD::SETNE:  return ARMCC::NE;
1504   case ISD::SETEQ:  return ARMCC::EQ;
1505   case ISD::SETGT:  return ARMCC::GT;
1506   case ISD::SETGE:  return ARMCC::GE;
1507   case ISD::SETLT:  return ARMCC::LT;
1508   case ISD::SETLE:  return ARMCC::LE;
1509   case ISD::SETUGT: return ARMCC::HI;
1510   case ISD::SETUGE: return ARMCC::HS;
1511   case ISD::SETULT: return ARMCC::LO;
1512   case ISD::SETULE: return ARMCC::LS;
1513   }
1514 }
1515 
1516 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1517 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1518                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1519   CondCode2 = ARMCC::AL;
1520   InvalidOnQNaN = true;
1521   switch (CC) {
1522   default: llvm_unreachable("Unknown FP condition!");
1523   case ISD::SETEQ:
1524   case ISD::SETOEQ:
1525     CondCode = ARMCC::EQ;
1526     InvalidOnQNaN = false;
1527     break;
1528   case ISD::SETGT:
1529   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1530   case ISD::SETGE:
1531   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1532   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1533   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1534   case ISD::SETONE:
1535     CondCode = ARMCC::MI;
1536     CondCode2 = ARMCC::GT;
1537     InvalidOnQNaN = false;
1538     break;
1539   case ISD::SETO:   CondCode = ARMCC::VC; break;
1540   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1541   case ISD::SETUEQ:
1542     CondCode = ARMCC::EQ;
1543     CondCode2 = ARMCC::VS;
1544     InvalidOnQNaN = false;
1545     break;
1546   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1547   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1548   case ISD::SETLT:
1549   case ISD::SETULT: CondCode = ARMCC::LT; break;
1550   case ISD::SETLE:
1551   case ISD::SETULE: CondCode = ARMCC::LE; break;
1552   case ISD::SETNE:
1553   case ISD::SETUNE:
1554     CondCode = ARMCC::NE;
1555     InvalidOnQNaN = false;
1556     break;
1557   }
1558 }
1559 
1560 //===----------------------------------------------------------------------===//
1561 //                      Calling Convention Implementation
1562 //===----------------------------------------------------------------------===//
1563 
1564 #include "ARMGenCallingConv.inc"
1565 
1566 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1567 /// account presence of floating point hardware and calling convention
1568 /// limitations, such as support for variadic functions.
1569 CallingConv::ID
1570 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1571                                            bool isVarArg) const {
1572   switch (CC) {
1573   default:
1574     report_fatal_error("Unsupported calling convention");
1575   case CallingConv::ARM_AAPCS:
1576   case CallingConv::ARM_APCS:
1577   case CallingConv::GHC:
1578     return CC;
1579   case CallingConv::PreserveMost:
1580     return CallingConv::PreserveMost;
1581   case CallingConv::ARM_AAPCS_VFP:
1582   case CallingConv::Swift:
1583     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1584   case CallingConv::C:
1585     if (!Subtarget->isAAPCS_ABI())
1586       return CallingConv::ARM_APCS;
1587     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1588              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1589              !isVarArg)
1590       return CallingConv::ARM_AAPCS_VFP;
1591     else
1592       return CallingConv::ARM_AAPCS;
1593   case CallingConv::Fast:
1594   case CallingConv::CXX_FAST_TLS:
1595     if (!Subtarget->isAAPCS_ABI()) {
1596       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1597         return CallingConv::Fast;
1598       return CallingConv::ARM_APCS;
1599     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1600       return CallingConv::ARM_AAPCS_VFP;
1601     else
1602       return CallingConv::ARM_AAPCS;
1603   }
1604 }
1605 
1606 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1607                                                  bool isVarArg) const {
1608   return CCAssignFnForNode(CC, false, isVarArg);
1609 }
1610 
1611 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1612                                                    bool isVarArg) const {
1613   return CCAssignFnForNode(CC, true, isVarArg);
1614 }
1615 
1616 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1617 /// CallingConvention.
1618 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1619                                                  bool Return,
1620                                                  bool isVarArg) const {
1621   switch (getEffectiveCallingConv(CC, isVarArg)) {
1622   default:
1623     report_fatal_error("Unsupported calling convention");
1624   case CallingConv::ARM_APCS:
1625     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1626   case CallingConv::ARM_AAPCS:
1627     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1628   case CallingConv::ARM_AAPCS_VFP:
1629     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1630   case CallingConv::Fast:
1631     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1632   case CallingConv::GHC:
1633     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1634   case CallingConv::PreserveMost:
1635     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1636   }
1637 }
1638 
1639 /// LowerCallResult - Lower the result values of a call into the
1640 /// appropriate copies out of appropriate physical registers.
1641 SDValue ARMTargetLowering::LowerCallResult(
1642     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1643     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1644     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1645     SDValue ThisVal) const {
1646   // Assign locations to each value returned by this call.
1647   SmallVector<CCValAssign, 16> RVLocs;
1648   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1649                  *DAG.getContext());
1650   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1651 
1652   // Copy all of the result registers out of their specified physreg.
1653   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1654     CCValAssign VA = RVLocs[i];
1655 
1656     // Pass 'this' value directly from the argument to return value, to avoid
1657     // reg unit interference
1658     if (i == 0 && isThisReturn) {
1659       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1660              "unexpected return calling convention register assignment");
1661       InVals.push_back(ThisVal);
1662       continue;
1663     }
1664 
1665     SDValue Val;
1666     if (VA.needsCustom()) {
1667       // Handle f64 or half of a v2f64.
1668       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1669                                       InFlag);
1670       Chain = Lo.getValue(1);
1671       InFlag = Lo.getValue(2);
1672       VA = RVLocs[++i]; // skip ahead to next loc
1673       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1674                                       InFlag);
1675       Chain = Hi.getValue(1);
1676       InFlag = Hi.getValue(2);
1677       if (!Subtarget->isLittle())
1678         std::swap (Lo, Hi);
1679       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1680 
1681       if (VA.getLocVT() == MVT::v2f64) {
1682         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1683         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1684                           DAG.getConstant(0, dl, MVT::i32));
1685 
1686         VA = RVLocs[++i]; // skip ahead to next loc
1687         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1688         Chain = Lo.getValue(1);
1689         InFlag = Lo.getValue(2);
1690         VA = RVLocs[++i]; // skip ahead to next loc
1691         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1692         Chain = Hi.getValue(1);
1693         InFlag = Hi.getValue(2);
1694         if (!Subtarget->isLittle())
1695           std::swap (Lo, Hi);
1696         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1697         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1698                           DAG.getConstant(1, dl, MVT::i32));
1699       }
1700     } else {
1701       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1702                                InFlag);
1703       Chain = Val.getValue(1);
1704       InFlag = Val.getValue(2);
1705     }
1706 
1707     switch (VA.getLocInfo()) {
1708     default: llvm_unreachable("Unknown loc info!");
1709     case CCValAssign::Full: break;
1710     case CCValAssign::BCvt:
1711       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1712       break;
1713     }
1714 
1715     InVals.push_back(Val);
1716   }
1717 
1718   return Chain;
1719 }
1720 
1721 /// LowerMemOpCallTo - Store the argument to the stack.
1722 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1723                                             SDValue Arg, const SDLoc &dl,
1724                                             SelectionDAG &DAG,
1725                                             const CCValAssign &VA,
1726                                             ISD::ArgFlagsTy Flags) const {
1727   unsigned LocMemOffset = VA.getLocMemOffset();
1728   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1729   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1730                        StackPtr, PtrOff);
1731   return DAG.getStore(
1732       Chain, dl, Arg, PtrOff,
1733       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1734 }
1735 
1736 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1737                                          SDValue Chain, SDValue &Arg,
1738                                          RegsToPassVector &RegsToPass,
1739                                          CCValAssign &VA, CCValAssign &NextVA,
1740                                          SDValue &StackPtr,
1741                                          SmallVectorImpl<SDValue> &MemOpChains,
1742                                          ISD::ArgFlagsTy Flags) const {
1743   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1744                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1745   unsigned id = Subtarget->isLittle() ? 0 : 1;
1746   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1747 
1748   if (NextVA.isRegLoc())
1749     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1750   else {
1751     assert(NextVA.isMemLoc());
1752     if (!StackPtr.getNode())
1753       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1754                                     getPointerTy(DAG.getDataLayout()));
1755 
1756     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1757                                            dl, DAG, NextVA,
1758                                            Flags));
1759   }
1760 }
1761 
1762 /// LowerCall - Lowering a call into a callseq_start <-
1763 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1764 /// nodes.
1765 SDValue
1766 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1767                              SmallVectorImpl<SDValue> &InVals) const {
1768   SelectionDAG &DAG                     = CLI.DAG;
1769   SDLoc &dl                             = CLI.DL;
1770   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1771   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1772   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1773   SDValue Chain                         = CLI.Chain;
1774   SDValue Callee                        = CLI.Callee;
1775   bool &isTailCall                      = CLI.IsTailCall;
1776   CallingConv::ID CallConv              = CLI.CallConv;
1777   bool doesNotRet                       = CLI.DoesNotReturn;
1778   bool isVarArg                         = CLI.IsVarArg;
1779 
1780   MachineFunction &MF = DAG.getMachineFunction();
1781   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1782   bool isThisReturn   = false;
1783   bool isSibCall      = false;
1784   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
1785 
1786   // Disable tail calls if they're not supported.
1787   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1788     isTailCall = false;
1789 
1790   if (isTailCall) {
1791     // Check if it's really possible to do a tail call.
1792     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1793                     isVarArg, isStructRet, MF.getFunction()->hasStructRetAttr(),
1794                                                    Outs, OutVals, Ins, DAG);
1795     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1796       report_fatal_error("failed to perform tail call elimination on a call "
1797                          "site marked musttail");
1798     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1799     // detected sibcalls.
1800     if (isTailCall) {
1801       ++NumTailCalls;
1802       isSibCall = true;
1803     }
1804   }
1805 
1806   // Analyze operands of the call, assigning locations to each operand.
1807   SmallVector<CCValAssign, 16> ArgLocs;
1808   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1809                  *DAG.getContext());
1810   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1811 
1812   // Get a count of how many bytes are to be pushed on the stack.
1813   unsigned NumBytes = CCInfo.getNextStackOffset();
1814 
1815   // For tail calls, memory operands are available in our caller's stack.
1816   if (isSibCall)
1817     NumBytes = 0;
1818 
1819   // Adjust the stack pointer for the new arguments...
1820   // These operations are automatically eliminated by the prolog/epilog pass
1821   if (!isSibCall)
1822     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1823 
1824   SDValue StackPtr =
1825       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1826 
1827   RegsToPassVector RegsToPass;
1828   SmallVector<SDValue, 8> MemOpChains;
1829 
1830   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1831   // of tail call optimization, arguments are handled later.
1832   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1833        i != e;
1834        ++i, ++realArgIdx) {
1835     CCValAssign &VA = ArgLocs[i];
1836     SDValue Arg = OutVals[realArgIdx];
1837     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1838     bool isByVal = Flags.isByVal();
1839 
1840     // Promote the value if needed.
1841     switch (VA.getLocInfo()) {
1842     default: llvm_unreachable("Unknown loc info!");
1843     case CCValAssign::Full: break;
1844     case CCValAssign::SExt:
1845       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1846       break;
1847     case CCValAssign::ZExt:
1848       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1849       break;
1850     case CCValAssign::AExt:
1851       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1852       break;
1853     case CCValAssign::BCvt:
1854       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1855       break;
1856     }
1857 
1858     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1859     if (VA.needsCustom()) {
1860       if (VA.getLocVT() == MVT::v2f64) {
1861         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1862                                   DAG.getConstant(0, dl, MVT::i32));
1863         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1864                                   DAG.getConstant(1, dl, MVT::i32));
1865 
1866         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1867                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1868 
1869         VA = ArgLocs[++i]; // skip ahead to next loc
1870         if (VA.isRegLoc()) {
1871           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1872                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1873         } else {
1874           assert(VA.isMemLoc());
1875 
1876           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1877                                                  dl, DAG, VA, Flags));
1878         }
1879       } else {
1880         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1881                          StackPtr, MemOpChains, Flags);
1882       }
1883     } else if (VA.isRegLoc()) {
1884       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1885           Outs[0].VT == MVT::i32) {
1886         assert(VA.getLocVT() == MVT::i32 &&
1887                "unexpected calling convention register assignment");
1888         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1889                "unexpected use of 'returned'");
1890         isThisReturn = true;
1891       }
1892       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1893     } else if (isByVal) {
1894       assert(VA.isMemLoc());
1895       unsigned offset = 0;
1896 
1897       // True if this byval aggregate will be split between registers
1898       // and memory.
1899       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1900       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1901 
1902       if (CurByValIdx < ByValArgsCount) {
1903 
1904         unsigned RegBegin, RegEnd;
1905         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1906 
1907         EVT PtrVT =
1908             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1909         unsigned int i, j;
1910         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1911           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1912           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1913           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1914                                      MachinePointerInfo(),
1915                                      DAG.InferPtrAlignment(AddArg));
1916           MemOpChains.push_back(Load.getValue(1));
1917           RegsToPass.push_back(std::make_pair(j, Load));
1918         }
1919 
1920         // If parameter size outsides register area, "offset" value
1921         // helps us to calculate stack slot for remained part properly.
1922         offset = RegEnd - RegBegin;
1923 
1924         CCInfo.nextInRegsParam();
1925       }
1926 
1927       if (Flags.getByValSize() > 4*offset) {
1928         auto PtrVT = getPointerTy(DAG.getDataLayout());
1929         unsigned LocMemOffset = VA.getLocMemOffset();
1930         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1931         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1932         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1933         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1934         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1935                                            MVT::i32);
1936         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1937                                             MVT::i32);
1938 
1939         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1940         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1941         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1942                                           Ops));
1943       }
1944     } else if (!isSibCall) {
1945       assert(VA.isMemLoc());
1946 
1947       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1948                                              dl, DAG, VA, Flags));
1949     }
1950   }
1951 
1952   if (!MemOpChains.empty())
1953     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1954 
1955   // Build a sequence of copy-to-reg nodes chained together with token chain
1956   // and flag operands which copy the outgoing args into the appropriate regs.
1957   SDValue InFlag;
1958   // Tail call byval lowering might overwrite argument registers so in case of
1959   // tail call optimization the copies to registers are lowered later.
1960   if (!isTailCall)
1961     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1962       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1963                                RegsToPass[i].second, InFlag);
1964       InFlag = Chain.getValue(1);
1965     }
1966 
1967   // For tail calls lower the arguments to the 'real' stack slot.
1968   if (isTailCall) {
1969     // Force all the incoming stack arguments to be loaded from the stack
1970     // before any new outgoing arguments are stored to the stack, because the
1971     // outgoing stack slots may alias the incoming argument stack slots, and
1972     // the alias isn't otherwise explicit. This is slightly more conservative
1973     // than necessary, because it means that each store effectively depends
1974     // on every argument instead of just those arguments it would clobber.
1975 
1976     // Do not flag preceding copytoreg stuff together with the following stuff.
1977     InFlag = SDValue();
1978     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1979       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1980                                RegsToPass[i].second, InFlag);
1981       InFlag = Chain.getValue(1);
1982     }
1983     InFlag = SDValue();
1984   }
1985 
1986   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1987   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1988   // node so that legalize doesn't hack it.
1989   bool isDirect = false;
1990 
1991   const TargetMachine &TM = getTargetMachine();
1992   const Module *Mod = MF.getFunction()->getParent();
1993   const GlobalValue *GV = nullptr;
1994   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1995     GV = G->getGlobal();
1996   bool isStub =
1997       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1998 
1999   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2000   bool isLocalARMFunc = false;
2001   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2002   auto PtrVt = getPointerTy(DAG.getDataLayout());
2003 
2004   if (Subtarget->genLongCalls()) {
2005     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2006            "long-calls codegen is not position independent!");
2007     // Handle a global address or an external symbol. If it's not one of
2008     // those, the target's already in a register, so we don't need to do
2009     // anything extra.
2010     if (isa<GlobalAddressSDNode>(Callee)) {
2011       // Create a constant pool entry for the callee address
2012       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2013       ARMConstantPoolValue *CPV =
2014         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2015 
2016       // Get the address of the callee into a register
2017       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2018       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2019       Callee = DAG.getLoad(
2020           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2021           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2022     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2023       const char *Sym = S->getSymbol();
2024 
2025       // Create a constant pool entry for the callee address
2026       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2027       ARMConstantPoolValue *CPV =
2028         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2029                                       ARMPCLabelIndex, 0);
2030       // Get the address of the callee into a register
2031       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2032       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2033       Callee = DAG.getLoad(
2034           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2035           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2036     }
2037   } else if (isa<GlobalAddressSDNode>(Callee)) {
2038     // If we're optimizing for minimum size and the function is called three or
2039     // more times in this block, we can improve codesize by calling indirectly
2040     // as BLXr has a 16-bit encoding.
2041     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2042     auto *BB = CLI.CS.getParent();
2043     bool PreferIndirect =
2044         Subtarget->isThumb() && MF.getFunction()->optForMinSize() &&
2045         count_if(GV->users(), [&BB](const User *U) {
2046           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2047         }) > 2;
2048 
2049     if (!PreferIndirect) {
2050       isDirect = true;
2051       bool isDef = GV->isStrongDefinitionForLinker();
2052 
2053       // ARM call to a local ARM function is predicable.
2054       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2055       // tBX takes a register source operand.
2056       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2057         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2058         Callee = DAG.getNode(
2059             ARMISD::WrapperPIC, dl, PtrVt,
2060             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2061         Callee = DAG.getLoad(
2062             PtrVt, dl, DAG.getEntryNode(), Callee,
2063             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2064             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2065                                      MachineMemOperand::MOInvariant);
2066       } else if (Subtarget->isTargetCOFF()) {
2067         assert(Subtarget->isTargetWindows() &&
2068                "Windows is the only supported COFF target");
2069         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2070                                    ? ARMII::MO_DLLIMPORT
2071                                    : ARMII::MO_NO_FLAG;
2072         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2073                                             TargetFlags);
2074         if (GV->hasDLLImportStorageClass())
2075           Callee =
2076               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2077                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2078                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2079       } else {
2080         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2081       }
2082     }
2083   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2084     isDirect = true;
2085     // tBX takes a register source operand.
2086     const char *Sym = S->getSymbol();
2087     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2088       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2089       ARMConstantPoolValue *CPV =
2090         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2091                                       ARMPCLabelIndex, 4);
2092       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2093       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2094       Callee = DAG.getLoad(
2095           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2096           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2097       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2098       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2099     } else {
2100       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2101     }
2102   }
2103 
2104   // FIXME: handle tail calls differently.
2105   unsigned CallOpc;
2106   if (Subtarget->isThumb()) {
2107     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2108       CallOpc = ARMISD::CALL_NOLINK;
2109     else
2110       CallOpc = ARMISD::CALL;
2111   } else {
2112     if (!isDirect && !Subtarget->hasV5TOps())
2113       CallOpc = ARMISD::CALL_NOLINK;
2114     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2115              // Emit regular call when code size is the priority
2116              !MF.getFunction()->optForMinSize())
2117       // "mov lr, pc; b _foo" to avoid confusing the RSP
2118       CallOpc = ARMISD::CALL_NOLINK;
2119     else
2120       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2121   }
2122 
2123   std::vector<SDValue> Ops;
2124   Ops.push_back(Chain);
2125   Ops.push_back(Callee);
2126 
2127   // Add argument registers to the end of the list so that they are known live
2128   // into the call.
2129   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2130     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2131                                   RegsToPass[i].second.getValueType()));
2132 
2133   // Add a register mask operand representing the call-preserved registers.
2134   if (!isTailCall) {
2135     const uint32_t *Mask;
2136     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2137     if (isThisReturn) {
2138       // For 'this' returns, use the R0-preserving mask if applicable
2139       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2140       if (!Mask) {
2141         // Set isThisReturn to false if the calling convention is not one that
2142         // allows 'returned' to be modeled in this way, so LowerCallResult does
2143         // not try to pass 'this' straight through
2144         isThisReturn = false;
2145         Mask = ARI->getCallPreservedMask(MF, CallConv);
2146       }
2147     } else
2148       Mask = ARI->getCallPreservedMask(MF, CallConv);
2149 
2150     assert(Mask && "Missing call preserved mask for calling convention");
2151     Ops.push_back(DAG.getRegisterMask(Mask));
2152   }
2153 
2154   if (InFlag.getNode())
2155     Ops.push_back(InFlag);
2156 
2157   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2158   if (isTailCall) {
2159     MF.getFrameInfo().setHasTailCall();
2160     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2161   }
2162 
2163   // Returns a chain and a flag for retval copy to use.
2164   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2165   InFlag = Chain.getValue(1);
2166 
2167   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2168                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2169   if (!Ins.empty())
2170     InFlag = Chain.getValue(1);
2171 
2172   // Handle result values, copying them out of physregs into vregs that we
2173   // return.
2174   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2175                          InVals, isThisReturn,
2176                          isThisReturn ? OutVals[0] : SDValue());
2177 }
2178 
2179 /// HandleByVal - Every parameter *after* a byval parameter is passed
2180 /// on the stack.  Remember the next parameter register to allocate,
2181 /// and then confiscate the rest of the parameter registers to insure
2182 /// this.
2183 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2184                                     unsigned Align) const {
2185   // Byval (as with any stack) slots are always at least 4 byte aligned.
2186   Align = std::max(Align, 4U);
2187 
2188   unsigned Reg = State->AllocateReg(GPRArgRegs);
2189   if (!Reg)
2190     return;
2191 
2192   unsigned AlignInRegs = Align / 4;
2193   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2194   for (unsigned i = 0; i < Waste; ++i)
2195     Reg = State->AllocateReg(GPRArgRegs);
2196 
2197   if (!Reg)
2198     return;
2199 
2200   unsigned Excess = 4 * (ARM::R4 - Reg);
2201 
2202   // Special case when NSAA != SP and parameter size greater than size of
2203   // all remained GPR regs. In that case we can't split parameter, we must
2204   // send it to stack. We also must set NCRN to R4, so waste all
2205   // remained registers.
2206   const unsigned NSAAOffset = State->getNextStackOffset();
2207   if (NSAAOffset != 0 && Size > Excess) {
2208     while (State->AllocateReg(GPRArgRegs))
2209       ;
2210     return;
2211   }
2212 
2213   // First register for byval parameter is the first register that wasn't
2214   // allocated before this method call, so it would be "reg".
2215   // If parameter is small enough to be saved in range [reg, r4), then
2216   // the end (first after last) register would be reg + param-size-in-regs,
2217   // else parameter would be splitted between registers and stack,
2218   // end register would be r4 in this case.
2219   unsigned ByValRegBegin = Reg;
2220   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2221   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2222   // Note, first register is allocated in the beginning of function already,
2223   // allocate remained amount of registers we need.
2224   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2225     State->AllocateReg(GPRArgRegs);
2226   // A byval parameter that is split between registers and memory needs its
2227   // size truncated here.
2228   // In the case where the entire structure fits in registers, we set the
2229   // size in memory to zero.
2230   Size = std::max<int>(Size - Excess, 0);
2231 }
2232 
2233 /// MatchingStackOffset - Return true if the given stack call argument is
2234 /// already available in the same position (relatively) of the caller's
2235 /// incoming argument stack.
2236 static
2237 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2238                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2239                          const TargetInstrInfo *TII) {
2240   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2241   int FI = std::numeric_limits<int>::max();
2242   if (Arg.getOpcode() == ISD::CopyFromReg) {
2243     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2244     if (!TargetRegisterInfo::isVirtualRegister(VR))
2245       return false;
2246     MachineInstr *Def = MRI->getVRegDef(VR);
2247     if (!Def)
2248       return false;
2249     if (!Flags.isByVal()) {
2250       if (!TII->isLoadFromStackSlot(*Def, FI))
2251         return false;
2252     } else {
2253       return false;
2254     }
2255   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2256     if (Flags.isByVal())
2257       // ByVal argument is passed in as a pointer but it's now being
2258       // dereferenced. e.g.
2259       // define @foo(%struct.X* %A) {
2260       //   tail call @bar(%struct.X* byval %A)
2261       // }
2262       return false;
2263     SDValue Ptr = Ld->getBasePtr();
2264     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2265     if (!FINode)
2266       return false;
2267     FI = FINode->getIndex();
2268   } else
2269     return false;
2270 
2271   assert(FI != std::numeric_limits<int>::max());
2272   if (!MFI.isFixedObjectIndex(FI))
2273     return false;
2274   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2275 }
2276 
2277 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2278 /// for tail call optimization. Targets which want to do tail call
2279 /// optimization should implement this function.
2280 bool
2281 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2282                                                      CallingConv::ID CalleeCC,
2283                                                      bool isVarArg,
2284                                                      bool isCalleeStructRet,
2285                                                      bool isCallerStructRet,
2286                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2287                                     const SmallVectorImpl<SDValue> &OutVals,
2288                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2289                                                      SelectionDAG& DAG) const {
2290   MachineFunction &MF = DAG.getMachineFunction();
2291   const Function *CallerF = MF.getFunction();
2292   CallingConv::ID CallerCC = CallerF->getCallingConv();
2293 
2294   assert(Subtarget->supportsTailCall());
2295 
2296   // Look for obvious safe cases to perform tail call optimization that do not
2297   // require ABI changes. This is what gcc calls sibcall.
2298 
2299   // Exception-handling functions need a special set of instructions to indicate
2300   // a return to the hardware. Tail-calling another function would probably
2301   // break this.
2302   if (CallerF->hasFnAttribute("interrupt"))
2303     return false;
2304 
2305   // Also avoid sibcall optimization if either caller or callee uses struct
2306   // return semantics.
2307   if (isCalleeStructRet || isCallerStructRet)
2308     return false;
2309 
2310   // Externally-defined functions with weak linkage should not be
2311   // tail-called on ARM when the OS does not support dynamic
2312   // pre-emption of symbols, as the AAELF spec requires normal calls
2313   // to undefined weak functions to be replaced with a NOP or jump to the
2314   // next instruction. The behaviour of branch instructions in this
2315   // situation (as used for tail calls) is implementation-defined, so we
2316   // cannot rely on the linker replacing the tail call with a return.
2317   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2318     const GlobalValue *GV = G->getGlobal();
2319     const Triple &TT = getTargetMachine().getTargetTriple();
2320     if (GV->hasExternalWeakLinkage() &&
2321         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2322       return false;
2323   }
2324 
2325   // Check that the call results are passed in the same way.
2326   LLVMContext &C = *DAG.getContext();
2327   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2328                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2329                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2330     return false;
2331   // The callee has to preserve all registers the caller needs to preserve.
2332   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2333   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2334   if (CalleeCC != CallerCC) {
2335     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2336     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2337       return false;
2338   }
2339 
2340   // If Caller's vararg or byval argument has been split between registers and
2341   // stack, do not perform tail call, since part of the argument is in caller's
2342   // local frame.
2343   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2344   if (AFI_Caller->getArgRegsSaveSize())
2345     return false;
2346 
2347   // If the callee takes no arguments then go on to check the results of the
2348   // call.
2349   if (!Outs.empty()) {
2350     // Check if stack adjustment is needed. For now, do not do this if any
2351     // argument is passed on the stack.
2352     SmallVector<CCValAssign, 16> ArgLocs;
2353     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2354     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2355     if (CCInfo.getNextStackOffset()) {
2356       // Check if the arguments are already laid out in the right way as
2357       // the caller's fixed stack objects.
2358       MachineFrameInfo &MFI = MF.getFrameInfo();
2359       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2360       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2361       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2362            i != e;
2363            ++i, ++realArgIdx) {
2364         CCValAssign &VA = ArgLocs[i];
2365         EVT RegVT = VA.getLocVT();
2366         SDValue Arg = OutVals[realArgIdx];
2367         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2368         if (VA.getLocInfo() == CCValAssign::Indirect)
2369           return false;
2370         if (VA.needsCustom()) {
2371           // f64 and vector types are split into multiple registers or
2372           // register/stack-slot combinations.  The types will not match
2373           // the registers; give up on memory f64 refs until we figure
2374           // out what to do about this.
2375           if (!VA.isRegLoc())
2376             return false;
2377           if (!ArgLocs[++i].isRegLoc())
2378             return false;
2379           if (RegVT == MVT::v2f64) {
2380             if (!ArgLocs[++i].isRegLoc())
2381               return false;
2382             if (!ArgLocs[++i].isRegLoc())
2383               return false;
2384           }
2385         } else if (!VA.isRegLoc()) {
2386           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2387                                    MFI, MRI, TII))
2388             return false;
2389         }
2390       }
2391     }
2392 
2393     const MachineRegisterInfo &MRI = MF.getRegInfo();
2394     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2395       return false;
2396   }
2397 
2398   return true;
2399 }
2400 
2401 bool
2402 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2403                                   MachineFunction &MF, bool isVarArg,
2404                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2405                                   LLVMContext &Context) const {
2406   SmallVector<CCValAssign, 16> RVLocs;
2407   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2408   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2409 }
2410 
2411 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2412                                     const SDLoc &DL, SelectionDAG &DAG) {
2413   const MachineFunction &MF = DAG.getMachineFunction();
2414   const Function *F = MF.getFunction();
2415 
2416   StringRef IntKind = F->getFnAttribute("interrupt").getValueAsString();
2417 
2418   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2419   // version of the "preferred return address". These offsets affect the return
2420   // instruction if this is a return from PL1 without hypervisor extensions.
2421   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2422   //    SWI:     0      "subs pc, lr, #0"
2423   //    ABORT:   +4     "subs pc, lr, #4"
2424   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2425   // UNDEF varies depending on where the exception came from ARM or Thumb
2426   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2427 
2428   int64_t LROffset;
2429   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2430       IntKind == "ABORT")
2431     LROffset = 4;
2432   else if (IntKind == "SWI" || IntKind == "UNDEF")
2433     LROffset = 0;
2434   else
2435     report_fatal_error("Unsupported interrupt attribute. If present, value "
2436                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2437 
2438   RetOps.insert(RetOps.begin() + 1,
2439                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2440 
2441   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2442 }
2443 
2444 SDValue
2445 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2446                                bool isVarArg,
2447                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2448                                const SmallVectorImpl<SDValue> &OutVals,
2449                                const SDLoc &dl, SelectionDAG &DAG) const {
2450   // CCValAssign - represent the assignment of the return value to a location.
2451   SmallVector<CCValAssign, 16> RVLocs;
2452 
2453   // CCState - Info about the registers and stack slots.
2454   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2455                  *DAG.getContext());
2456 
2457   // Analyze outgoing return values.
2458   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2459 
2460   SDValue Flag;
2461   SmallVector<SDValue, 4> RetOps;
2462   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2463   bool isLittleEndian = Subtarget->isLittle();
2464 
2465   MachineFunction &MF = DAG.getMachineFunction();
2466   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2467   AFI->setReturnRegsCount(RVLocs.size());
2468 
2469   // Copy the result values into the output registers.
2470   for (unsigned i = 0, realRVLocIdx = 0;
2471        i != RVLocs.size();
2472        ++i, ++realRVLocIdx) {
2473     CCValAssign &VA = RVLocs[i];
2474     assert(VA.isRegLoc() && "Can only return in registers!");
2475 
2476     SDValue Arg = OutVals[realRVLocIdx];
2477 
2478     switch (VA.getLocInfo()) {
2479     default: llvm_unreachable("Unknown loc info!");
2480     case CCValAssign::Full: break;
2481     case CCValAssign::BCvt:
2482       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2483       break;
2484     }
2485 
2486     if (VA.needsCustom()) {
2487       if (VA.getLocVT() == MVT::v2f64) {
2488         // Extract the first half and return it in two registers.
2489         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2490                                    DAG.getConstant(0, dl, MVT::i32));
2491         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2492                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2493 
2494         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2495                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
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         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2501                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2502                                  Flag);
2503         Flag = Chain.getValue(1);
2504         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2505         VA = RVLocs[++i]; // skip ahead to next loc
2506 
2507         // Extract the 2nd half and fall through to handle it as an f64 value.
2508         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2509                           DAG.getConstant(1, dl, MVT::i32));
2510       }
2511       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2512       // available.
2513       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2514                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2515       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2516                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2517                                Flag);
2518       Flag = Chain.getValue(1);
2519       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2520       VA = RVLocs[++i]; // skip ahead to next loc
2521       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2522                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2523                                Flag);
2524     } else
2525       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2526 
2527     // Guarantee that all emitted copies are
2528     // stuck together, avoiding something bad.
2529     Flag = Chain.getValue(1);
2530     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2531   }
2532   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2533   const MCPhysReg *I =
2534       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2535   if (I) {
2536     for (; *I; ++I) {
2537       if (ARM::GPRRegClass.contains(*I))
2538         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2539       else if (ARM::DPRRegClass.contains(*I))
2540         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2541       else
2542         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2543     }
2544   }
2545 
2546   // Update chain and glue.
2547   RetOps[0] = Chain;
2548   if (Flag.getNode())
2549     RetOps.push_back(Flag);
2550 
2551   // CPUs which aren't M-class use a special sequence to return from
2552   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2553   // though we use "subs pc, lr, #N").
2554   //
2555   // M-class CPUs actually use a normal return sequence with a special
2556   // (hardware-provided) value in LR, so the normal code path works.
2557   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt") &&
2558       !Subtarget->isMClass()) {
2559     if (Subtarget->isThumb1Only())
2560       report_fatal_error("interrupt attribute is not supported in Thumb1");
2561     return LowerInterruptReturn(RetOps, dl, DAG);
2562   }
2563 
2564   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2565 }
2566 
2567 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2568   if (N->getNumValues() != 1)
2569     return false;
2570   if (!N->hasNUsesOfValue(1, 0))
2571     return false;
2572 
2573   SDValue TCChain = Chain;
2574   SDNode *Copy = *N->use_begin();
2575   if (Copy->getOpcode() == ISD::CopyToReg) {
2576     // If the copy has a glue operand, we conservatively assume it isn't safe to
2577     // perform a tail call.
2578     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2579       return false;
2580     TCChain = Copy->getOperand(0);
2581   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2582     SDNode *VMov = Copy;
2583     // f64 returned in a pair of GPRs.
2584     SmallPtrSet<SDNode*, 2> Copies;
2585     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2586          UI != UE; ++UI) {
2587       if (UI->getOpcode() != ISD::CopyToReg)
2588         return false;
2589       Copies.insert(*UI);
2590     }
2591     if (Copies.size() > 2)
2592       return false;
2593 
2594     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2595          UI != UE; ++UI) {
2596       SDValue UseChain = UI->getOperand(0);
2597       if (Copies.count(UseChain.getNode()))
2598         // Second CopyToReg
2599         Copy = *UI;
2600       else {
2601         // We are at the top of this chain.
2602         // If the copy has a glue operand, we conservatively assume it
2603         // isn't safe to perform a tail call.
2604         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2605           return false;
2606         // First CopyToReg
2607         TCChain = UseChain;
2608       }
2609     }
2610   } else if (Copy->getOpcode() == ISD::BITCAST) {
2611     // f32 returned in a single GPR.
2612     if (!Copy->hasOneUse())
2613       return false;
2614     Copy = *Copy->use_begin();
2615     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2616       return false;
2617     // If the copy has a glue operand, we conservatively assume it isn't safe to
2618     // perform a tail call.
2619     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2620       return false;
2621     TCChain = Copy->getOperand(0);
2622   } else {
2623     return false;
2624   }
2625 
2626   bool HasRet = false;
2627   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2628        UI != UE; ++UI) {
2629     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2630         UI->getOpcode() != ARMISD::INTRET_FLAG)
2631       return false;
2632     HasRet = true;
2633   }
2634 
2635   if (!HasRet)
2636     return false;
2637 
2638   Chain = TCChain;
2639   return true;
2640 }
2641 
2642 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2643   if (!Subtarget->supportsTailCall())
2644     return false;
2645 
2646   auto Attr =
2647       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2648   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2649     return false;
2650 
2651   return true;
2652 }
2653 
2654 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2655 // and pass the lower and high parts through.
2656 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2657   SDLoc DL(Op);
2658   SDValue WriteValue = Op->getOperand(2);
2659 
2660   // This function is only supposed to be called for i64 type argument.
2661   assert(WriteValue.getValueType() == MVT::i64
2662           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2663 
2664   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2665                            DAG.getConstant(0, DL, MVT::i32));
2666   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2667                            DAG.getConstant(1, DL, MVT::i32));
2668   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2669   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2670 }
2671 
2672 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2673 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2674 // one of the above mentioned nodes. It has to be wrapped because otherwise
2675 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2676 // be used to form addressing mode. These wrapped nodes will be selected
2677 // into MOVi.
2678 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2679                                              SelectionDAG &DAG) const {
2680   EVT PtrVT = Op.getValueType();
2681   // FIXME there is no actual debug info here
2682   SDLoc dl(Op);
2683   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2684   SDValue Res;
2685 
2686   // When generating execute-only code Constant Pools must be promoted to the
2687   // global data section. It's a bit ugly that we can't share them across basic
2688   // blocks, but this way we guarantee that execute-only behaves correct with
2689   // position-independent addressing modes.
2690   if (Subtarget->genExecuteOnly()) {
2691     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2692     auto T = const_cast<Type*>(CP->getType());
2693     auto C = const_cast<Constant*>(CP->getConstVal());
2694     auto M = const_cast<Module*>(DAG.getMachineFunction().
2695                                  getFunction()->getParent());
2696     auto GV = new GlobalVariable(
2697                     *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2698                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2699                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2700                     Twine(AFI->createPICLabelUId())
2701                   );
2702     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2703                                             dl, PtrVT);
2704     return LowerGlobalAddress(GA, DAG);
2705   }
2706 
2707   if (CP->isMachineConstantPoolEntry())
2708     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2709                                     CP->getAlignment());
2710   else
2711     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2712                                     CP->getAlignment());
2713   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2714 }
2715 
2716 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2717   return MachineJumpTableInfo::EK_Inline;
2718 }
2719 
2720 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2721                                              SelectionDAG &DAG) const {
2722   MachineFunction &MF = DAG.getMachineFunction();
2723   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2724   unsigned ARMPCLabelIndex = 0;
2725   SDLoc DL(Op);
2726   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2727   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2728   SDValue CPAddr;
2729   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2730   if (!IsPositionIndependent) {
2731     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2732   } else {
2733     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2734     ARMPCLabelIndex = AFI->createPICLabelUId();
2735     ARMConstantPoolValue *CPV =
2736       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2737                                       ARMCP::CPBlockAddress, PCAdj);
2738     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2739   }
2740   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2741   SDValue Result = DAG.getLoad(
2742       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2743       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2744   if (!IsPositionIndependent)
2745     return Result;
2746   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2747   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2748 }
2749 
2750 /// \brief Convert a TLS address reference into the correct sequence of loads
2751 /// and calls to compute the variable's address for Darwin, and return an
2752 /// SDValue containing the final node.
2753 
2754 /// Darwin only has one TLS scheme which must be capable of dealing with the
2755 /// fully general situation, in the worst case. This means:
2756 ///     + "extern __thread" declaration.
2757 ///     + Defined in a possibly unknown dynamic library.
2758 ///
2759 /// The general system is that each __thread variable has a [3 x i32] descriptor
2760 /// which contains information used by the runtime to calculate the address. The
2761 /// only part of this the compiler needs to know about is the first word, which
2762 /// contains a function pointer that must be called with the address of the
2763 /// entire descriptor in "r0".
2764 ///
2765 /// Since this descriptor may be in a different unit, in general access must
2766 /// proceed along the usual ARM rules. A common sequence to produce is:
2767 ///
2768 ///     movw rT1, :lower16:_var$non_lazy_ptr
2769 ///     movt rT1, :upper16:_var$non_lazy_ptr
2770 ///     ldr r0, [rT1]
2771 ///     ldr rT2, [r0]
2772 ///     blx rT2
2773 ///     [...address now in r0...]
2774 SDValue
2775 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2776                                                SelectionDAG &DAG) const {
2777   assert(Subtarget->isTargetDarwin() && "TLS only supported on Darwin");
2778   SDLoc DL(Op);
2779 
2780   // First step is to get the address of the actua global symbol. This is where
2781   // the TLS descriptor lives.
2782   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2783 
2784   // The first entry in the descriptor is a function pointer that we must call
2785   // to obtain the address of the variable.
2786   SDValue Chain = DAG.getEntryNode();
2787   SDValue FuncTLVGet = DAG.getLoad(
2788       MVT::i32, DL, Chain, DescAddr,
2789       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2790       /* Alignment = */ 4,
2791       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2792           MachineMemOperand::MOInvariant);
2793   Chain = FuncTLVGet.getValue(1);
2794 
2795   MachineFunction &F = DAG.getMachineFunction();
2796   MachineFrameInfo &MFI = F.getFrameInfo();
2797   MFI.setAdjustsStack(true);
2798 
2799   // TLS calls preserve all registers except those that absolutely must be
2800   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2801   // silly).
2802   auto TRI =
2803       getTargetMachine().getSubtargetImpl(*F.getFunction())->getRegisterInfo();
2804   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2805   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2806 
2807   // Finally, we can make the call. This is just a degenerate version of a
2808   // normal AArch64 call node: r0 takes the address of the descriptor, and
2809   // returns the address of the variable in this thread.
2810   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2811   Chain =
2812       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2813                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2814                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2815   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2816 }
2817 
2818 SDValue
2819 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2820                                                 SelectionDAG &DAG) const {
2821   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2822 
2823   SDValue Chain = DAG.getEntryNode();
2824   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2825   SDLoc DL(Op);
2826 
2827   // Load the current TEB (thread environment block)
2828   SDValue Ops[] = {Chain,
2829                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2830                    DAG.getConstant(15, DL, MVT::i32),
2831                    DAG.getConstant(0, DL, MVT::i32),
2832                    DAG.getConstant(13, DL, MVT::i32),
2833                    DAG.getConstant(0, DL, MVT::i32),
2834                    DAG.getConstant(2, DL, MVT::i32)};
2835   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2836                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2837 
2838   SDValue TEB = CurrentTEB.getValue(0);
2839   Chain = CurrentTEB.getValue(1);
2840 
2841   // Load the ThreadLocalStoragePointer from the TEB
2842   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2843   SDValue TLSArray =
2844       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2845   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2846 
2847   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2848   // offset into the TLSArray.
2849 
2850   // Load the TLS index from the C runtime
2851   SDValue TLSIndex =
2852       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2853   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2854   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2855 
2856   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2857                               DAG.getConstant(2, DL, MVT::i32));
2858   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2859                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2860                             MachinePointerInfo());
2861 
2862   // Get the offset of the start of the .tls section (section base)
2863   const auto *GA = cast<GlobalAddressSDNode>(Op);
2864   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2865   SDValue Offset = DAG.getLoad(
2866       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2867                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2868       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2869 
2870   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2871 }
2872 
2873 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2874 SDValue
2875 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2876                                                  SelectionDAG &DAG) const {
2877   SDLoc dl(GA);
2878   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2879   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2880   MachineFunction &MF = DAG.getMachineFunction();
2881   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2882   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2883   ARMConstantPoolValue *CPV =
2884     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2885                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2886   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2887   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2888   Argument = DAG.getLoad(
2889       PtrVT, dl, DAG.getEntryNode(), Argument,
2890       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2891   SDValue Chain = Argument.getValue(1);
2892 
2893   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2894   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2895 
2896   // call __tls_get_addr.
2897   ArgListTy Args;
2898   ArgListEntry Entry;
2899   Entry.Node = Argument;
2900   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2901   Args.push_back(Entry);
2902 
2903   // FIXME: is there useful debug info available here?
2904   TargetLowering::CallLoweringInfo CLI(DAG);
2905   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2906       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2907       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2908 
2909   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2910   return CallResult.first;
2911 }
2912 
2913 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2914 // "local exec" model.
2915 SDValue
2916 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2917                                         SelectionDAG &DAG,
2918                                         TLSModel::Model model) const {
2919   const GlobalValue *GV = GA->getGlobal();
2920   SDLoc dl(GA);
2921   SDValue Offset;
2922   SDValue Chain = DAG.getEntryNode();
2923   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2924   // Get the Thread Pointer
2925   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2926 
2927   if (model == TLSModel::InitialExec) {
2928     MachineFunction &MF = DAG.getMachineFunction();
2929     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2930     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2931     // Initial exec model.
2932     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2933     ARMConstantPoolValue *CPV =
2934       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2935                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2936                                       true);
2937     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2938     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2939     Offset = DAG.getLoad(
2940         PtrVT, dl, Chain, Offset,
2941         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2942     Chain = Offset.getValue(1);
2943 
2944     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2945     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2946 
2947     Offset = DAG.getLoad(
2948         PtrVT, dl, Chain, Offset,
2949         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2950   } else {
2951     // local exec model
2952     assert(model == TLSModel::LocalExec);
2953     ARMConstantPoolValue *CPV =
2954       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2955     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2956     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2957     Offset = DAG.getLoad(
2958         PtrVT, dl, Chain, Offset,
2959         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2960   }
2961 
2962   // The address of the thread local variable is the add of the thread
2963   // pointer with the offset of the variable.
2964   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2965 }
2966 
2967 SDValue
2968 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2969   if (Subtarget->isTargetDarwin())
2970     return LowerGlobalTLSAddressDarwin(Op, DAG);
2971 
2972   if (Subtarget->isTargetWindows())
2973     return LowerGlobalTLSAddressWindows(Op, DAG);
2974 
2975   // TODO: implement the "local dynamic" model
2976   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2977   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2978   if (DAG.getTarget().Options.EmulatedTLS)
2979     return LowerToTLSEmulatedModel(GA, DAG);
2980 
2981   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2982 
2983   switch (model) {
2984     case TLSModel::GeneralDynamic:
2985     case TLSModel::LocalDynamic:
2986       return LowerToTLSGeneralDynamicModel(GA, DAG);
2987     case TLSModel::InitialExec:
2988     case TLSModel::LocalExec:
2989       return LowerToTLSExecModels(GA, DAG, model);
2990   }
2991   llvm_unreachable("bogus TLS model");
2992 }
2993 
2994 /// Return true if all users of V are within function F, looking through
2995 /// ConstantExprs.
2996 static bool allUsersAreInFunction(const Value *V, const Function *F) {
2997   SmallVector<const User*,4> Worklist;
2998   for (auto *U : V->users())
2999     Worklist.push_back(U);
3000   while (!Worklist.empty()) {
3001     auto *U = Worklist.pop_back_val();
3002     if (isa<ConstantExpr>(U)) {
3003       for (auto *UU : U->users())
3004         Worklist.push_back(UU);
3005       continue;
3006     }
3007 
3008     auto *I = dyn_cast<Instruction>(U);
3009     if (!I || I->getParent()->getParent() != F)
3010       return false;
3011   }
3012   return true;
3013 }
3014 
3015 /// Return true if all users of V are within some (any) function, looking through
3016 /// ConstantExprs. In other words, are there any global constant users?
3017 static bool allUsersAreInFunctions(const Value *V) {
3018   SmallVector<const User*,4> Worklist;
3019   for (auto *U : V->users())
3020     Worklist.push_back(U);
3021   while (!Worklist.empty()) {
3022     auto *U = Worklist.pop_back_val();
3023     if (isa<ConstantExpr>(U)) {
3024       for (auto *UU : U->users())
3025         Worklist.push_back(UU);
3026       continue;
3027     }
3028 
3029     if (!isa<Instruction>(U))
3030       return false;
3031   }
3032   return true;
3033 }
3034 
3035 // Return true if T is an integer, float or an array/vector of either.
3036 static bool isSimpleType(Type *T) {
3037   if (T->isIntegerTy() || T->isFloatingPointTy())
3038     return true;
3039   Type *SubT = nullptr;
3040   if (T->isArrayTy())
3041     SubT = T->getArrayElementType();
3042   else if (T->isVectorTy())
3043     SubT = T->getVectorElementType();
3044   else
3045     return false;
3046   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3047 }
3048 
3049 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3050                                      EVT PtrVT, const SDLoc &dl) {
3051   // If we're creating a pool entry for a constant global with unnamed address,
3052   // and the global is small enough, we can emit it inline into the constant pool
3053   // to save ourselves an indirection.
3054   //
3055   // This is a win if the constant is only used in one function (so it doesn't
3056   // need to be duplicated) or duplicating the constant wouldn't increase code
3057   // size (implying the constant is no larger than 4 bytes).
3058   const Function *F = DAG.getMachineFunction().getFunction();
3059 
3060   // We rely on this decision to inline being idemopotent and unrelated to the
3061   // use-site. We know that if we inline a variable at one use site, we'll
3062   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3063   // doesn't know about this optimization, so bail out if it's enabled else
3064   // we could decide to inline here (and thus never emit the GV) but require
3065   // the GV from fast-isel generated code.
3066   if (!EnableConstpoolPromotion ||
3067       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3068       return SDValue();
3069 
3070   auto *GVar = dyn_cast<GlobalVariable>(GV);
3071   if (!GVar || !GVar->hasInitializer() ||
3072       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3073       !GVar->hasLocalLinkage())
3074     return SDValue();
3075 
3076   // Ensure that we don't try and inline any type that contains pointers. If
3077   // we inline a value that contains relocations, we move the relocations from
3078   // .data to .text which is not ideal.
3079   auto *Init = GVar->getInitializer();
3080   if (!isSimpleType(Init->getType()))
3081     return SDValue();
3082 
3083   // The constant islands pass can only really deal with alignment requests
3084   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3085   // any type wanting greater alignment requirements than 4 bytes. We also
3086   // can only promote constants that are multiples of 4 bytes in size or
3087   // are paddable to a multiple of 4. Currently we only try and pad constants
3088   // that are strings for simplicity.
3089   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3090   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3091   unsigned Align = GVar->getAlignment();
3092   unsigned RequiredPadding = 4 - (Size % 4);
3093   bool PaddingPossible =
3094     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3095   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3096       Size == 0)
3097     return SDValue();
3098 
3099   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3100   MachineFunction &MF = DAG.getMachineFunction();
3101   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3102 
3103   // We can't bloat the constant pool too much, else the ConstantIslands pass
3104   // may fail to converge. If we haven't promoted this global yet (it may have
3105   // multiple uses), and promoting it would increase the constant pool size (Sz
3106   // > 4), ensure we have space to do so up to MaxTotal.
3107   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3108     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3109         ConstpoolPromotionMaxTotal)
3110       return SDValue();
3111 
3112   // This is only valid if all users are in a single function OR it has users
3113   // in multiple functions but it no larger than a pointer. We also check if
3114   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3115   // address taken.
3116   if (!allUsersAreInFunction(GVar, F) &&
3117       !(Size <= 4 && allUsersAreInFunctions(GVar)))
3118     return SDValue();
3119 
3120   // We're going to inline this global. Pad it out if needed.
3121   if (RequiredPadding != 4) {
3122     StringRef S = CDAInit->getAsString();
3123 
3124     SmallVector<uint8_t,16> V(S.size());
3125     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3126     while (RequiredPadding--)
3127       V.push_back(0);
3128     Init = ConstantDataArray::get(*DAG.getContext(), V);
3129   }
3130 
3131   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3132   SDValue CPAddr =
3133     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3134   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3135     AFI->markGlobalAsPromotedToConstantPool(GVar);
3136     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3137                                       PaddedSize - 4);
3138   }
3139   ++NumConstpoolPromoted;
3140   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3141 }
3142 
3143 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3144   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3145     GV = GA->getBaseObject();
3146   return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3147          isa<Function>(GV);
3148 }
3149 
3150 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3151                                               SelectionDAG &DAG) const {
3152   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3153   default: llvm_unreachable("unknown object format");
3154   case Triple::COFF:
3155     return LowerGlobalAddressWindows(Op, DAG);
3156   case Triple::ELF:
3157     return LowerGlobalAddressELF(Op, DAG);
3158   case Triple::MachO:
3159     return LowerGlobalAddressDarwin(Op, DAG);
3160   }
3161 }
3162 
3163 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3164                                                  SelectionDAG &DAG) const {
3165   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3166   SDLoc dl(Op);
3167   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3168   const TargetMachine &TM = getTargetMachine();
3169   bool IsRO = isReadOnly(GV);
3170 
3171   // promoteToConstantPool only if not generating XO text section
3172   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3173     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3174       return V;
3175 
3176   if (isPositionIndependent()) {
3177     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3178 
3179     MachineFunction &MF = DAG.getMachineFunction();
3180     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3181     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3182     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3183     SDLoc dl(Op);
3184     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
3185     ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
3186         GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
3187         UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
3188         /*AddCurrentAddress=*/UseGOT_PREL);
3189     SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3190     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3191     SDValue Result = DAG.getLoad(
3192         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3193         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3194     SDValue Chain = Result.getValue(1);
3195     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3196     Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3197     if (UseGOT_PREL)
3198       Result =
3199           DAG.getLoad(PtrVT, dl, Chain, Result,
3200                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3201     return Result;
3202   } else if (Subtarget->isROPI() && IsRO) {
3203     // PC-relative.
3204     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3205     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3206     return Result;
3207   } else if (Subtarget->isRWPI() && !IsRO) {
3208     // SB-relative.
3209     SDValue RelAddr;
3210     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3211       ++NumMovwMovt;
3212       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3213       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3214     } else { // use literal pool for address constant
3215       ARMConstantPoolValue *CPV =
3216         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3217       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3218       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3219       RelAddr = DAG.getLoad(
3220           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3221           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3222     }
3223     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3224     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3225     return Result;
3226   }
3227 
3228   // If we have T2 ops, we can materialize the address directly via movt/movw
3229   // pair. This is always cheaper.
3230   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3231     ++NumMovwMovt;
3232     // FIXME: Once remat is capable of dealing with instructions with register
3233     // operands, expand this into two nodes.
3234     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3235                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3236   } else {
3237     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3238     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3239     return DAG.getLoad(
3240         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3241         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3242   }
3243 }
3244 
3245 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3246                                                     SelectionDAG &DAG) const {
3247   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3248          "ROPI/RWPI not currently supported for Darwin");
3249   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3250   SDLoc dl(Op);
3251   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3252 
3253   if (Subtarget->useMovt(DAG.getMachineFunction()))
3254     ++NumMovwMovt;
3255 
3256   // FIXME: Once remat is capable of dealing with instructions with register
3257   // operands, expand this into multiple nodes
3258   unsigned Wrapper =
3259       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3260 
3261   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3262   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3263 
3264   if (Subtarget->isGVIndirectSymbol(GV))
3265     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3266                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3267   return Result;
3268 }
3269 
3270 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3271                                                      SelectionDAG &DAG) const {
3272   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3273   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3274          "Windows on ARM expects to use movw/movt");
3275   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3276          "ROPI/RWPI not currently supported for Windows");
3277 
3278   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3279   const ARMII::TOF TargetFlags =
3280     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3281   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3282   SDValue Result;
3283   SDLoc DL(Op);
3284 
3285   ++NumMovwMovt;
3286 
3287   // FIXME: Once remat is capable of dealing with instructions with register
3288   // operands, expand this into two nodes.
3289   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3290                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3291                                                   TargetFlags));
3292   if (GV->hasDLLImportStorageClass())
3293     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3294                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3295   return Result;
3296 }
3297 
3298 SDValue
3299 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3300   SDLoc dl(Op);
3301   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3302   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3303                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3304                      Op.getOperand(1), Val);
3305 }
3306 
3307 SDValue
3308 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3309   SDLoc dl(Op);
3310   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3311                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3312 }
3313 
3314 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3315                                                       SelectionDAG &DAG) const {
3316   SDLoc dl(Op);
3317   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3318                      Op.getOperand(0));
3319 }
3320 
3321 SDValue
3322 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3323                                           const ARMSubtarget *Subtarget) const {
3324   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3325   SDLoc dl(Op);
3326   switch (IntNo) {
3327   default: return SDValue();    // Don't custom lower most intrinsics.
3328   case Intrinsic::thread_pointer: {
3329     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3330     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3331   }
3332   case Intrinsic::eh_sjlj_lsda: {
3333     MachineFunction &MF = DAG.getMachineFunction();
3334     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3335     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3336     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3337     SDValue CPAddr;
3338     bool IsPositionIndependent = isPositionIndependent();
3339     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3340     ARMConstantPoolValue *CPV =
3341       ARMConstantPoolConstant::Create(MF.getFunction(), ARMPCLabelIndex,
3342                                       ARMCP::CPLSDA, PCAdj);
3343     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3344     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3345     SDValue Result = DAG.getLoad(
3346         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3347         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3348 
3349     if (IsPositionIndependent) {
3350       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3351       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3352     }
3353     return Result;
3354   }
3355   case Intrinsic::arm_neon_vabs:
3356     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3357                         Op.getOperand(1));
3358   case Intrinsic::arm_neon_vmulls:
3359   case Intrinsic::arm_neon_vmullu: {
3360     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3361       ? ARMISD::VMULLs : ARMISD::VMULLu;
3362     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3363                        Op.getOperand(1), Op.getOperand(2));
3364   }
3365   case Intrinsic::arm_neon_vminnm:
3366   case Intrinsic::arm_neon_vmaxnm: {
3367     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3368       ? ISD::FMINNUM : ISD::FMAXNUM;
3369     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3370                        Op.getOperand(1), Op.getOperand(2));
3371   }
3372   case Intrinsic::arm_neon_vminu:
3373   case Intrinsic::arm_neon_vmaxu: {
3374     if (Op.getValueType().isFloatingPoint())
3375       return SDValue();
3376     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3377       ? ISD::UMIN : ISD::UMAX;
3378     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3379                          Op.getOperand(1), Op.getOperand(2));
3380   }
3381   case Intrinsic::arm_neon_vmins:
3382   case Intrinsic::arm_neon_vmaxs: {
3383     // v{min,max}s is overloaded between signed integers and floats.
3384     if (!Op.getValueType().isFloatingPoint()) {
3385       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3386         ? ISD::SMIN : ISD::SMAX;
3387       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3388                          Op.getOperand(1), Op.getOperand(2));
3389     }
3390     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3391       ? ISD::FMINNAN : ISD::FMAXNAN;
3392     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3393                        Op.getOperand(1), Op.getOperand(2));
3394   }
3395   case Intrinsic::arm_neon_vtbl1:
3396     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3397                        Op.getOperand(1), Op.getOperand(2));
3398   case Intrinsic::arm_neon_vtbl2:
3399     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3400                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3401   }
3402 }
3403 
3404 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3405                                  const ARMSubtarget *Subtarget) {
3406   SDLoc dl(Op);
3407   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3408   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3409   if (SSID == SyncScope::SingleThread)
3410     return Op;
3411 
3412   if (!Subtarget->hasDataBarrier()) {
3413     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3414     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3415     // here.
3416     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3417            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3418     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3419                        DAG.getConstant(0, dl, MVT::i32));
3420   }
3421 
3422   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3423   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3424   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3425   if (Subtarget->isMClass()) {
3426     // Only a full system barrier exists in the M-class architectures.
3427     Domain = ARM_MB::SY;
3428   } else if (Subtarget->preferISHSTBarriers() &&
3429              Ord == AtomicOrdering::Release) {
3430     // Swift happens to implement ISHST barriers in a way that's compatible with
3431     // Release semantics but weaker than ISH so we'd be fools not to use
3432     // it. Beware: other processors probably don't!
3433     Domain = ARM_MB::ISHST;
3434   }
3435 
3436   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3437                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3438                      DAG.getConstant(Domain, dl, MVT::i32));
3439 }
3440 
3441 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3442                              const ARMSubtarget *Subtarget) {
3443   // ARM pre v5TE and Thumb1 does not have preload instructions.
3444   if (!(Subtarget->isThumb2() ||
3445         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3446     // Just preserve the chain.
3447     return Op.getOperand(0);
3448 
3449   SDLoc dl(Op);
3450   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3451   if (!isRead &&
3452       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3453     // ARMv7 with MP extension has PLDW.
3454     return Op.getOperand(0);
3455 
3456   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3457   if (Subtarget->isThumb()) {
3458     // Invert the bits.
3459     isRead = ~isRead & 1;
3460     isData = ~isData & 1;
3461   }
3462 
3463   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3464                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3465                      DAG.getConstant(isData, dl, MVT::i32));
3466 }
3467 
3468 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3469   MachineFunction &MF = DAG.getMachineFunction();
3470   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3471 
3472   // vastart just stores the address of the VarArgsFrameIndex slot into the
3473   // memory location argument.
3474   SDLoc dl(Op);
3475   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3476   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3477   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3478   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3479                       MachinePointerInfo(SV));
3480 }
3481 
3482 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3483                                                 CCValAssign &NextVA,
3484                                                 SDValue &Root,
3485                                                 SelectionDAG &DAG,
3486                                                 const SDLoc &dl) const {
3487   MachineFunction &MF = DAG.getMachineFunction();
3488   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3489 
3490   const TargetRegisterClass *RC;
3491   if (AFI->isThumb1OnlyFunction())
3492     RC = &ARM::tGPRRegClass;
3493   else
3494     RC = &ARM::GPRRegClass;
3495 
3496   // Transform the arguments stored in physical registers into virtual ones.
3497   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3498   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3499 
3500   SDValue ArgValue2;
3501   if (NextVA.isMemLoc()) {
3502     MachineFrameInfo &MFI = MF.getFrameInfo();
3503     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3504 
3505     // Create load node to retrieve arguments from the stack.
3506     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3507     ArgValue2 = DAG.getLoad(
3508         MVT::i32, dl, Root, FIN,
3509         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3510   } else {
3511     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3512     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3513   }
3514   if (!Subtarget->isLittle())
3515     std::swap (ArgValue, ArgValue2);
3516   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3517 }
3518 
3519 // The remaining GPRs hold either the beginning of variable-argument
3520 // data, or the beginning of an aggregate passed by value (usually
3521 // byval).  Either way, we allocate stack slots adjacent to the data
3522 // provided by our caller, and store the unallocated registers there.
3523 // If this is a variadic function, the va_list pointer will begin with
3524 // these values; otherwise, this reassembles a (byval) structure that
3525 // was split between registers and memory.
3526 // Return: The frame index registers were stored into.
3527 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3528                                       const SDLoc &dl, SDValue &Chain,
3529                                       const Value *OrigArg,
3530                                       unsigned InRegsParamRecordIdx,
3531                                       int ArgOffset, unsigned ArgSize) const {
3532   // Currently, two use-cases possible:
3533   // Case #1. Non-var-args function, and we meet first byval parameter.
3534   //          Setup first unallocated register as first byval register;
3535   //          eat all remained registers
3536   //          (these two actions are performed by HandleByVal method).
3537   //          Then, here, we initialize stack frame with
3538   //          "store-reg" instructions.
3539   // Case #2. Var-args function, that doesn't contain byval parameters.
3540   //          The same: eat all remained unallocated registers,
3541   //          initialize stack frame.
3542 
3543   MachineFunction &MF = DAG.getMachineFunction();
3544   MachineFrameInfo &MFI = MF.getFrameInfo();
3545   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3546   unsigned RBegin, REnd;
3547   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3548     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3549   } else {
3550     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3551     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3552     REnd = ARM::R4;
3553   }
3554 
3555   if (REnd != RBegin)
3556     ArgOffset = -4 * (ARM::R4 - RBegin);
3557 
3558   auto PtrVT = getPointerTy(DAG.getDataLayout());
3559   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3560   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3561 
3562   SmallVector<SDValue, 4> MemOps;
3563   const TargetRegisterClass *RC =
3564       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3565 
3566   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3567     unsigned VReg = MF.addLiveIn(Reg, RC);
3568     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3569     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3570                                  MachinePointerInfo(OrigArg, 4 * i));
3571     MemOps.push_back(Store);
3572     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3573   }
3574 
3575   if (!MemOps.empty())
3576     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3577   return FrameIndex;
3578 }
3579 
3580 // Setup stack frame, the va_list pointer will start from.
3581 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3582                                              const SDLoc &dl, SDValue &Chain,
3583                                              unsigned ArgOffset,
3584                                              unsigned TotalArgRegsSaveSize,
3585                                              bool ForceMutable) const {
3586   MachineFunction &MF = DAG.getMachineFunction();
3587   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3588 
3589   // Try to store any remaining integer argument regs
3590   // to their spots on the stack so that they may be loaded by dereferencing
3591   // the result of va_next.
3592   // If there is no regs to be stored, just point address after last
3593   // argument passed via stack.
3594   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3595                                   CCInfo.getInRegsParamsCount(),
3596                                   CCInfo.getNextStackOffset(), 4);
3597   AFI->setVarArgsFrameIndex(FrameIndex);
3598 }
3599 
3600 SDValue ARMTargetLowering::LowerFormalArguments(
3601     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3602     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3603     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3604   MachineFunction &MF = DAG.getMachineFunction();
3605   MachineFrameInfo &MFI = MF.getFrameInfo();
3606 
3607   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3608 
3609   // Assign locations to all of the incoming arguments.
3610   SmallVector<CCValAssign, 16> ArgLocs;
3611   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3612                  *DAG.getContext());
3613   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3614 
3615   SmallVector<SDValue, 16> ArgValues;
3616   SDValue ArgValue;
3617   Function::const_arg_iterator CurOrigArg = MF.getFunction()->arg_begin();
3618   unsigned CurArgIdx = 0;
3619 
3620   // Initially ArgRegsSaveSize is zero.
3621   // Then we increase this value each time we meet byval parameter.
3622   // We also increase this value in case of varargs function.
3623   AFI->setArgRegsSaveSize(0);
3624 
3625   // Calculate the amount of stack space that we need to allocate to store
3626   // byval and variadic arguments that are passed in registers.
3627   // We need to know this before we allocate the first byval or variadic
3628   // argument, as they will be allocated a stack slot below the CFA (Canonical
3629   // Frame Address, the stack pointer at entry to the function).
3630   unsigned ArgRegBegin = ARM::R4;
3631   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3632     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3633       break;
3634 
3635     CCValAssign &VA = ArgLocs[i];
3636     unsigned Index = VA.getValNo();
3637     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3638     if (!Flags.isByVal())
3639       continue;
3640 
3641     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3642     unsigned RBegin, REnd;
3643     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3644     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3645 
3646     CCInfo.nextInRegsParam();
3647   }
3648   CCInfo.rewindByValRegsInfo();
3649 
3650   int lastInsIndex = -1;
3651   if (isVarArg && MFI.hasVAStart()) {
3652     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3653     if (RegIdx != array_lengthof(GPRArgRegs))
3654       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3655   }
3656 
3657   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3658   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3659   auto PtrVT = getPointerTy(DAG.getDataLayout());
3660 
3661   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3662     CCValAssign &VA = ArgLocs[i];
3663     if (Ins[VA.getValNo()].isOrigArg()) {
3664       std::advance(CurOrigArg,
3665                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3666       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3667     }
3668     // Arguments stored in registers.
3669     if (VA.isRegLoc()) {
3670       EVT RegVT = VA.getLocVT();
3671 
3672       if (VA.needsCustom()) {
3673         // f64 and vector types are split up into multiple registers or
3674         // combinations of registers and stack slots.
3675         if (VA.getLocVT() == MVT::v2f64) {
3676           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3677                                                    Chain, DAG, dl);
3678           VA = ArgLocs[++i]; // skip ahead to next loc
3679           SDValue ArgValue2;
3680           if (VA.isMemLoc()) {
3681             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3682             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3683             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3684                                     MachinePointerInfo::getFixedStack(
3685                                         DAG.getMachineFunction(), FI));
3686           } else {
3687             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3688                                              Chain, DAG, dl);
3689           }
3690           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3691           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3692                                  ArgValue, ArgValue1,
3693                                  DAG.getIntPtrConstant(0, dl));
3694           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3695                                  ArgValue, ArgValue2,
3696                                  DAG.getIntPtrConstant(1, dl));
3697         } else
3698           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3699       } else {
3700         const TargetRegisterClass *RC;
3701 
3702         if (RegVT == MVT::f32)
3703           RC = &ARM::SPRRegClass;
3704         else if (RegVT == MVT::f64)
3705           RC = &ARM::DPRRegClass;
3706         else if (RegVT == MVT::v2f64)
3707           RC = &ARM::QPRRegClass;
3708         else if (RegVT == MVT::i32)
3709           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3710                                            : &ARM::GPRRegClass;
3711         else
3712           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3713 
3714         // Transform the arguments in physical registers into virtual ones.
3715         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3716         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3717       }
3718 
3719       // If this is an 8 or 16-bit value, it is really passed promoted
3720       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3721       // truncate to the right size.
3722       switch (VA.getLocInfo()) {
3723       default: llvm_unreachable("Unknown loc info!");
3724       case CCValAssign::Full: break;
3725       case CCValAssign::BCvt:
3726         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3727         break;
3728       case CCValAssign::SExt:
3729         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3730                                DAG.getValueType(VA.getValVT()));
3731         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3732         break;
3733       case CCValAssign::ZExt:
3734         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3735                                DAG.getValueType(VA.getValVT()));
3736         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3737         break;
3738       }
3739 
3740       InVals.push_back(ArgValue);
3741     } else { // VA.isRegLoc()
3742       // sanity check
3743       assert(VA.isMemLoc());
3744       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3745 
3746       int index = VA.getValNo();
3747 
3748       // Some Ins[] entries become multiple ArgLoc[] entries.
3749       // Process them only once.
3750       if (index != lastInsIndex)
3751         {
3752           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3753           // FIXME: For now, all byval parameter objects are marked mutable.
3754           // This can be changed with more analysis.
3755           // In case of tail call optimization mark all arguments mutable.
3756           // Since they could be overwritten by lowering of arguments in case of
3757           // a tail call.
3758           if (Flags.isByVal()) {
3759             assert(Ins[index].isOrigArg() &&
3760                    "Byval arguments cannot be implicit");
3761             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3762 
3763             int FrameIndex = StoreByValRegs(
3764                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3765                 VA.getLocMemOffset(), Flags.getByValSize());
3766             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3767             CCInfo.nextInRegsParam();
3768           } else {
3769             unsigned FIOffset = VA.getLocMemOffset();
3770             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3771                                            FIOffset, true);
3772 
3773             // Create load nodes to retrieve arguments from the stack.
3774             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3775             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3776                                          MachinePointerInfo::getFixedStack(
3777                                              DAG.getMachineFunction(), FI)));
3778           }
3779           lastInsIndex = index;
3780         }
3781     }
3782   }
3783 
3784   // varargs
3785   if (isVarArg && MFI.hasVAStart())
3786     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3787                          CCInfo.getNextStackOffset(),
3788                          TotalArgRegsSaveSize);
3789 
3790   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3791 
3792   return Chain;
3793 }
3794 
3795 /// isFloatingPointZero - Return true if this is +0.0.
3796 static bool isFloatingPointZero(SDValue Op) {
3797   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3798     return CFP->getValueAPF().isPosZero();
3799   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3800     // Maybe this has already been legalized into the constant pool?
3801     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3802       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3803       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3804         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3805           return CFP->getValueAPF().isPosZero();
3806     }
3807   } else if (Op->getOpcode() == ISD::BITCAST &&
3808              Op->getValueType(0) == MVT::f64) {
3809     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3810     // created by LowerConstantFP().
3811     SDValue BitcastOp = Op->getOperand(0);
3812     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3813         isNullConstant(BitcastOp->getOperand(0)))
3814       return true;
3815   }
3816   return false;
3817 }
3818 
3819 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3820 /// the given operands.
3821 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3822                                      SDValue &ARMcc, SelectionDAG &DAG,
3823                                      const SDLoc &dl) const {
3824   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3825     unsigned C = RHSC->getZExtValue();
3826     if (!isLegalICmpImmediate(C)) {
3827       // Constant does not fit, try adjusting it by one?
3828       switch (CC) {
3829       default: break;
3830       case ISD::SETLT:
3831       case ISD::SETGE:
3832         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3833           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3834           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3835         }
3836         break;
3837       case ISD::SETULT:
3838       case ISD::SETUGE:
3839         if (C != 0 && isLegalICmpImmediate(C-1)) {
3840           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3841           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3842         }
3843         break;
3844       case ISD::SETLE:
3845       case ISD::SETGT:
3846         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3847           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3848           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3849         }
3850         break;
3851       case ISD::SETULE:
3852       case ISD::SETUGT:
3853         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3854           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3855           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3856         }
3857         break;
3858       }
3859     }
3860   }
3861 
3862   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3863   ARMISD::NodeType CompareType;
3864   switch (CondCode) {
3865   default:
3866     CompareType = ARMISD::CMP;
3867     break;
3868   case ARMCC::EQ:
3869   case ARMCC::NE:
3870     // Uses only Z Flag
3871     CompareType = ARMISD::CMPZ;
3872     break;
3873   }
3874   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3875   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3876 }
3877 
3878 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3879 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3880                                      SelectionDAG &DAG, const SDLoc &dl,
3881                                      bool InvalidOnQNaN) const {
3882   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3883   SDValue Cmp;
3884   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3885   if (!isFloatingPointZero(RHS))
3886     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3887   else
3888     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3889   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3890 }
3891 
3892 /// duplicateCmp - Glue values can have only one use, so this function
3893 /// duplicates a comparison node.
3894 SDValue
3895 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3896   unsigned Opc = Cmp.getOpcode();
3897   SDLoc DL(Cmp);
3898   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3899     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3900 
3901   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3902   Cmp = Cmp.getOperand(0);
3903   Opc = Cmp.getOpcode();
3904   if (Opc == ARMISD::CMPFP)
3905     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3906                       Cmp.getOperand(1), Cmp.getOperand(2));
3907   else {
3908     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3909     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3910                       Cmp.getOperand(1));
3911   }
3912   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3913 }
3914 
3915 std::pair<SDValue, SDValue>
3916 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3917                                  SDValue &ARMcc) const {
3918   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3919 
3920   SDValue Value, OverflowCmp;
3921   SDValue LHS = Op.getOperand(0);
3922   SDValue RHS = Op.getOperand(1);
3923   SDLoc dl(Op);
3924 
3925   // FIXME: We are currently always generating CMPs because we don't support
3926   // generating CMN through the backend. This is not as good as the natural
3927   // CMP case because it causes a register dependency and cannot be folded
3928   // later.
3929 
3930   switch (Op.getOpcode()) {
3931   default:
3932     llvm_unreachable("Unknown overflow instruction!");
3933   case ISD::SADDO:
3934     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3935     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3936     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3937     break;
3938   case ISD::UADDO:
3939     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3940     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3941     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3942     break;
3943   case ISD::SSUBO:
3944     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3945     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3946     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3947     break;
3948   case ISD::USUBO:
3949     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3950     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3951     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3952     break;
3953   } // switch (...)
3954 
3955   return std::make_pair(Value, OverflowCmp);
3956 }
3957 
3958 SDValue
3959 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
3960   // Let legalize expand this if it isn't a legal type yet.
3961   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3962     return SDValue();
3963 
3964   SDValue Value, OverflowCmp;
3965   SDValue ARMcc;
3966   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3967   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3968   SDLoc dl(Op);
3969   // We use 0 and 1 as false and true values.
3970   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3971   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3972   EVT VT = Op.getValueType();
3973 
3974   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3975                                  ARMcc, CCR, OverflowCmp);
3976 
3977   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
3978   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
3979 }
3980 
3981 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
3982                                               SelectionDAG &DAG) {
3983   SDLoc DL(BoolCarry);
3984   EVT CarryVT = BoolCarry.getValueType();
3985 
3986   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
3987   // This converts the boolean value carry into the carry flag by doing
3988   // ARMISD::ADDC Carry, ~0
3989   return DAG.getNode(ARMISD::ADDC, DL, DAG.getVTList(CarryVT, MVT::i32),
3990                      BoolCarry, DAG.getConstant(NegOne, DL, CarryVT));
3991 }
3992 
3993 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
3994                                               SelectionDAG &DAG) {
3995   SDLoc DL(Flags);
3996 
3997   // Now convert the carry flag into a boolean carry. We do this
3998   // using ARMISD:ADDE 0, 0, Carry
3999   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4000                      DAG.getConstant(0, DL, MVT::i32),
4001                      DAG.getConstant(0, DL, MVT::i32), Flags);
4002 }
4003 
4004 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4005                                              SelectionDAG &DAG) const {
4006   // Let legalize expand this if it isn't a legal type yet.
4007   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4008     return SDValue();
4009 
4010   SDValue LHS = Op.getOperand(0);
4011   SDValue RHS = Op.getOperand(1);
4012   SDLoc dl(Op);
4013 
4014   EVT VT = Op.getValueType();
4015   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4016   SDValue Value;
4017   SDValue Overflow;
4018   switch (Op.getOpcode()) {
4019   default:
4020     llvm_unreachable("Unknown overflow instruction!");
4021   case ISD::UADDO:
4022     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4023     // Convert the carry flag into a boolean value.
4024     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4025     break;
4026   case ISD::USUBO:
4027     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4028     // Convert the carry flag into a boolean value.
4029     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4030     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4031     // value. So compute 1 - C.
4032     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4033                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4034     break;
4035   }
4036 
4037   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4038 }
4039 
4040 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4041   SDValue Cond = Op.getOperand(0);
4042   SDValue SelectTrue = Op.getOperand(1);
4043   SDValue SelectFalse = Op.getOperand(2);
4044   SDLoc dl(Op);
4045   unsigned Opc = Cond.getOpcode();
4046 
4047   if (Cond.getResNo() == 1 &&
4048       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4049        Opc == ISD::USUBO)) {
4050     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4051       return SDValue();
4052 
4053     SDValue Value, OverflowCmp;
4054     SDValue ARMcc;
4055     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4056     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4057     EVT VT = Op.getValueType();
4058 
4059     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4060                    OverflowCmp, DAG);
4061   }
4062 
4063   // Convert:
4064   //
4065   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4066   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4067   //
4068   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4069     const ConstantSDNode *CMOVTrue =
4070       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4071     const ConstantSDNode *CMOVFalse =
4072       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4073 
4074     if (CMOVTrue && CMOVFalse) {
4075       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4076       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4077 
4078       SDValue True;
4079       SDValue False;
4080       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4081         True = SelectTrue;
4082         False = SelectFalse;
4083       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4084         True = SelectFalse;
4085         False = SelectTrue;
4086       }
4087 
4088       if (True.getNode() && False.getNode()) {
4089         EVT VT = Op.getValueType();
4090         SDValue ARMcc = Cond.getOperand(2);
4091         SDValue CCR = Cond.getOperand(3);
4092         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4093         assert(True.getValueType() == VT);
4094         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4095       }
4096     }
4097   }
4098 
4099   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4100   // undefined bits before doing a full-word comparison with zero.
4101   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4102                      DAG.getConstant(1, dl, Cond.getValueType()));
4103 
4104   return DAG.getSelectCC(dl, Cond,
4105                          DAG.getConstant(0, dl, Cond.getValueType()),
4106                          SelectTrue, SelectFalse, ISD::SETNE);
4107 }
4108 
4109 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4110                                  bool &swpCmpOps, bool &swpVselOps) {
4111   // Start by selecting the GE condition code for opcodes that return true for
4112   // 'equality'
4113   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4114       CC == ISD::SETULE)
4115     CondCode = ARMCC::GE;
4116 
4117   // and GT for opcodes that return false for 'equality'.
4118   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4119            CC == ISD::SETULT)
4120     CondCode = ARMCC::GT;
4121 
4122   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4123   // to swap the compare operands.
4124   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4125       CC == ISD::SETULT)
4126     swpCmpOps = true;
4127 
4128   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4129   // If we have an unordered opcode, we need to swap the operands to the VSEL
4130   // instruction (effectively negating the condition).
4131   //
4132   // This also has the effect of swapping which one of 'less' or 'greater'
4133   // returns true, so we also swap the compare operands. It also switches
4134   // whether we return true for 'equality', so we compensate by picking the
4135   // opposite condition code to our original choice.
4136   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4137       CC == ISD::SETUGT) {
4138     swpCmpOps = !swpCmpOps;
4139     swpVselOps = !swpVselOps;
4140     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4141   }
4142 
4143   // 'ordered' is 'anything but unordered', so use the VS condition code and
4144   // swap the VSEL operands.
4145   if (CC == ISD::SETO) {
4146     CondCode = ARMCC::VS;
4147     swpVselOps = true;
4148   }
4149 
4150   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4151   // code and swap the VSEL operands.
4152   if (CC == ISD::SETUNE) {
4153     CondCode = ARMCC::EQ;
4154     swpVselOps = true;
4155   }
4156 }
4157 
4158 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4159                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4160                                    SDValue Cmp, SelectionDAG &DAG) const {
4161   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4162     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4163                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4164     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4165                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4166 
4167     SDValue TrueLow = TrueVal.getValue(0);
4168     SDValue TrueHigh = TrueVal.getValue(1);
4169     SDValue FalseLow = FalseVal.getValue(0);
4170     SDValue FalseHigh = FalseVal.getValue(1);
4171 
4172     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4173                               ARMcc, CCR, Cmp);
4174     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4175                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4176 
4177     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4178   } else {
4179     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4180                        Cmp);
4181   }
4182 }
4183 
4184 static bool isGTorGE(ISD::CondCode CC) {
4185   return CC == ISD::SETGT || CC == ISD::SETGE;
4186 }
4187 
4188 static bool isLTorLE(ISD::CondCode CC) {
4189   return CC == ISD::SETLT || CC == ISD::SETLE;
4190 }
4191 
4192 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4193 // All of these conditions (and their <= and >= counterparts) will do:
4194 //          x < k ? k : x
4195 //          x > k ? x : k
4196 //          k < x ? x : k
4197 //          k > x ? k : x
4198 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4199                             const SDValue TrueVal, const SDValue FalseVal,
4200                             const ISD::CondCode CC, const SDValue K) {
4201   return (isGTorGE(CC) &&
4202           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4203          (isLTorLE(CC) &&
4204           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4205 }
4206 
4207 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4208 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4209                             const SDValue TrueVal, const SDValue FalseVal,
4210                             const ISD::CondCode CC, const SDValue K) {
4211   return (isGTorGE(CC) &&
4212           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4213          (isLTorLE(CC) &&
4214           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4215 }
4216 
4217 // Check if two chained conditionals could be converted into SSAT.
4218 //
4219 // SSAT can replace a set of two conditional selectors that bound a number to an
4220 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4221 //
4222 //     x < -k ? -k : (x > k ? k : x)
4223 //     x < -k ? -k : (x < k ? x : k)
4224 //     x > -k ? (x > k ? k : x) : -k
4225 //     x < k ? (x < -k ? -k : x) : k
4226 //     etc.
4227 //
4228 // It returns true if the conversion can be done, false otherwise.
4229 // Additionally, the variable is returned in parameter V and the constant in K.
4230 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4231                                     uint64_t &K) {
4232   SDValue LHS1 = Op.getOperand(0);
4233   SDValue RHS1 = Op.getOperand(1);
4234   SDValue TrueVal1 = Op.getOperand(2);
4235   SDValue FalseVal1 = Op.getOperand(3);
4236   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4237 
4238   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4239   if (Op2.getOpcode() != ISD::SELECT_CC)
4240     return false;
4241 
4242   SDValue LHS2 = Op2.getOperand(0);
4243   SDValue RHS2 = Op2.getOperand(1);
4244   SDValue TrueVal2 = Op2.getOperand(2);
4245   SDValue FalseVal2 = Op2.getOperand(3);
4246   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4247 
4248   // Find out which are the constants and which are the variables
4249   // in each conditional
4250   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4251                                                         ? &RHS1
4252                                                         : nullptr;
4253   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4254                                                         ? &RHS2
4255                                                         : nullptr;
4256   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4257   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4258   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4259   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4260 
4261   // We must detect cases where the original operations worked with 16- or
4262   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4263   // must work with sign-extended values but the select operations return
4264   // the original non-extended value.
4265   SDValue V2TmpReg = V2Tmp;
4266   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4267     V2TmpReg = V2Tmp->getOperand(0);
4268 
4269   // Check that the registers and the constants have the correct values
4270   // in both conditionals
4271   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4272       V2TmpReg != V2)
4273     return false;
4274 
4275   // Figure out which conditional is saturating the lower/upper bound.
4276   const SDValue *LowerCheckOp =
4277       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4278           ? &Op
4279           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4280                 ? &Op2
4281                 : nullptr;
4282   const SDValue *UpperCheckOp =
4283       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4284           ? &Op
4285           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4286                 ? &Op2
4287                 : nullptr;
4288 
4289   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4290     return false;
4291 
4292   // Check that the constant in the lower-bound check is
4293   // the opposite of the constant in the upper-bound check
4294   // in 1's complement.
4295   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4296   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4297   int64_t PosVal = std::max(Val1, Val2);
4298 
4299   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4300        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4301       Val1 == ~Val2 && isPowerOf2_64(PosVal + 1)) {
4302 
4303     V = V2;
4304     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4305     return true;
4306   }
4307 
4308   return false;
4309 }
4310 
4311 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4312   EVT VT = Op.getValueType();
4313   SDLoc dl(Op);
4314 
4315   // Try to convert two saturating conditional selects into a single SSAT
4316   SDValue SatValue;
4317   uint64_t SatConstant;
4318   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4319       isSaturatingConditional(Op, SatValue, SatConstant))
4320     return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4321                        DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4322 
4323   SDValue LHS = Op.getOperand(0);
4324   SDValue RHS = Op.getOperand(1);
4325   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4326   SDValue TrueVal = Op.getOperand(2);
4327   SDValue FalseVal = Op.getOperand(3);
4328 
4329   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4330     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4331                                                     dl);
4332 
4333     // If softenSetCCOperands only returned one value, we should compare it to
4334     // zero.
4335     if (!RHS.getNode()) {
4336       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4337       CC = ISD::SETNE;
4338     }
4339   }
4340 
4341   if (LHS.getValueType() == MVT::i32) {
4342     // Try to generate VSEL on ARMv8.
4343     // The VSEL instruction can't use all the usual ARM condition
4344     // codes: it only has two bits to select the condition code, so it's
4345     // constrained to use only GE, GT, VS and EQ.
4346     //
4347     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4348     // swap the operands of the previous compare instruction (effectively
4349     // inverting the compare condition, swapping 'less' and 'greater') and
4350     // sometimes need to swap the operands to the VSEL (which inverts the
4351     // condition in the sense of firing whenever the previous condition didn't)
4352     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4353                                     TrueVal.getValueType() == MVT::f64)) {
4354       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4355       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4356           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4357         CC = ISD::getSetCCInverse(CC, true);
4358         std::swap(TrueVal, FalseVal);
4359       }
4360     }
4361 
4362     SDValue ARMcc;
4363     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4364     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4365     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4366   }
4367 
4368   ARMCC::CondCodes CondCode, CondCode2;
4369   bool InvalidOnQNaN;
4370   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4371 
4372   // Try to generate VMAXNM/VMINNM on ARMv8.
4373   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4374                                   TrueVal.getValueType() == MVT::f64)) {
4375     bool swpCmpOps = false;
4376     bool swpVselOps = false;
4377     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4378 
4379     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4380         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4381       if (swpCmpOps)
4382         std::swap(LHS, RHS);
4383       if (swpVselOps)
4384         std::swap(TrueVal, FalseVal);
4385     }
4386   }
4387 
4388   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4389   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4390   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4391   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4392   if (CondCode2 != ARMCC::AL) {
4393     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4394     // FIXME: Needs another CMP because flag can have but one use.
4395     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4396     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4397   }
4398   return Result;
4399 }
4400 
4401 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4402 /// to morph to an integer compare sequence.
4403 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4404                            const ARMSubtarget *Subtarget) {
4405   SDNode *N = Op.getNode();
4406   if (!N->hasOneUse())
4407     // Otherwise it requires moving the value from fp to integer registers.
4408     return false;
4409   if (!N->getNumValues())
4410     return false;
4411   EVT VT = Op.getValueType();
4412   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4413     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4414     // vmrs are very slow, e.g. cortex-a8.
4415     return false;
4416 
4417   if (isFloatingPointZero(Op)) {
4418     SeenZero = true;
4419     return true;
4420   }
4421   return ISD::isNormalLoad(N);
4422 }
4423 
4424 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4425   if (isFloatingPointZero(Op))
4426     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4427 
4428   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4429     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4430                        Ld->getPointerInfo(), Ld->getAlignment(),
4431                        Ld->getMemOperand()->getFlags());
4432 
4433   llvm_unreachable("Unknown VFP cmp argument!");
4434 }
4435 
4436 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4437                            SDValue &RetVal1, SDValue &RetVal2) {
4438   SDLoc dl(Op);
4439 
4440   if (isFloatingPointZero(Op)) {
4441     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4442     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4443     return;
4444   }
4445 
4446   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4447     SDValue Ptr = Ld->getBasePtr();
4448     RetVal1 =
4449         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4450                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4451 
4452     EVT PtrType = Ptr.getValueType();
4453     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4454     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4455                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4456     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4457                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4458                           Ld->getMemOperand()->getFlags());
4459     return;
4460   }
4461 
4462   llvm_unreachable("Unknown VFP cmp argument!");
4463 }
4464 
4465 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4466 /// f32 and even f64 comparisons to integer ones.
4467 SDValue
4468 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4469   SDValue Chain = Op.getOperand(0);
4470   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4471   SDValue LHS = Op.getOperand(2);
4472   SDValue RHS = Op.getOperand(3);
4473   SDValue Dest = Op.getOperand(4);
4474   SDLoc dl(Op);
4475 
4476   bool LHSSeenZero = false;
4477   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4478   bool RHSSeenZero = false;
4479   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4480   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4481     // If unsafe fp math optimization is enabled and there are no other uses of
4482     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4483     // to an integer comparison.
4484     if (CC == ISD::SETOEQ)
4485       CC = ISD::SETEQ;
4486     else if (CC == ISD::SETUNE)
4487       CC = ISD::SETNE;
4488 
4489     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4490     SDValue ARMcc;
4491     if (LHS.getValueType() == MVT::f32) {
4492       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4493                         bitcastf32Toi32(LHS, DAG), Mask);
4494       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4495                         bitcastf32Toi32(RHS, DAG), Mask);
4496       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4497       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4498       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4499                          Chain, Dest, ARMcc, CCR, Cmp);
4500     }
4501 
4502     SDValue LHS1, LHS2;
4503     SDValue RHS1, RHS2;
4504     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4505     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4506     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4507     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4508     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4509     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4510     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4511     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4512     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4513   }
4514 
4515   return SDValue();
4516 }
4517 
4518 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4519   SDValue Chain = Op.getOperand(0);
4520   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4521   SDValue LHS = Op.getOperand(2);
4522   SDValue RHS = Op.getOperand(3);
4523   SDValue Dest = Op.getOperand(4);
4524   SDLoc dl(Op);
4525 
4526   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4527     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4528                                                     dl);
4529 
4530     // If softenSetCCOperands only returned one value, we should compare it to
4531     // zero.
4532     if (!RHS.getNode()) {
4533       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4534       CC = ISD::SETNE;
4535     }
4536   }
4537 
4538   if (LHS.getValueType() == MVT::i32) {
4539     SDValue ARMcc;
4540     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4541     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4542     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4543                        Chain, Dest, ARMcc, CCR, Cmp);
4544   }
4545 
4546   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4547 
4548   if (getTargetMachine().Options.UnsafeFPMath &&
4549       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4550        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4551     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4552       return Result;
4553   }
4554 
4555   ARMCC::CondCodes CondCode, CondCode2;
4556   bool InvalidOnQNaN;
4557   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4558 
4559   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4560   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4561   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4562   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4563   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4564   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4565   if (CondCode2 != ARMCC::AL) {
4566     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4567     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4568     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4569   }
4570   return Res;
4571 }
4572 
4573 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4574   SDValue Chain = Op.getOperand(0);
4575   SDValue Table = Op.getOperand(1);
4576   SDValue Index = Op.getOperand(2);
4577   SDLoc dl(Op);
4578 
4579   EVT PTy = getPointerTy(DAG.getDataLayout());
4580   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4581   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4582   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4583   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4584   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
4585   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4586     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4587     // which does another jump to the destination. This also makes it easier
4588     // to translate it to TBB / TBH later (Thumb2 only).
4589     // FIXME: This might not work if the function is extremely large.
4590     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4591                        Addr, Op.getOperand(2), JTI);
4592   }
4593   if (isPositionIndependent() || Subtarget->isROPI()) {
4594     Addr =
4595         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4596                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4597     Chain = Addr.getValue(1);
4598     Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr, Table);
4599     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4600   } else {
4601     Addr =
4602         DAG.getLoad(PTy, dl, Chain, Addr,
4603                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4604     Chain = Addr.getValue(1);
4605     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4606   }
4607 }
4608 
4609 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4610   EVT VT = Op.getValueType();
4611   SDLoc dl(Op);
4612 
4613   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4614     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4615       return Op;
4616     return DAG.UnrollVectorOp(Op.getNode());
4617   }
4618 
4619   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4620          "Invalid type for custom lowering!");
4621   if (VT != MVT::v4i16)
4622     return DAG.UnrollVectorOp(Op.getNode());
4623 
4624   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4625   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4626 }
4627 
4628 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4629   EVT VT = Op.getValueType();
4630   if (VT.isVector())
4631     return LowerVectorFP_TO_INT(Op, DAG);
4632   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4633     RTLIB::Libcall LC;
4634     if (Op.getOpcode() == ISD::FP_TO_SINT)
4635       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4636                               Op.getValueType());
4637     else
4638       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4639                               Op.getValueType());
4640     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4641                        /*isSigned*/ false, SDLoc(Op)).first;
4642   }
4643 
4644   return Op;
4645 }
4646 
4647 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4648   EVT VT = Op.getValueType();
4649   SDLoc dl(Op);
4650 
4651   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4652     if (VT.getVectorElementType() == MVT::f32)
4653       return Op;
4654     return DAG.UnrollVectorOp(Op.getNode());
4655   }
4656 
4657   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4658          "Invalid type for custom lowering!");
4659   if (VT != MVT::v4f32)
4660     return DAG.UnrollVectorOp(Op.getNode());
4661 
4662   unsigned CastOpc;
4663   unsigned Opc;
4664   switch (Op.getOpcode()) {
4665   default: llvm_unreachable("Invalid opcode!");
4666   case ISD::SINT_TO_FP:
4667     CastOpc = ISD::SIGN_EXTEND;
4668     Opc = ISD::SINT_TO_FP;
4669     break;
4670   case ISD::UINT_TO_FP:
4671     CastOpc = ISD::ZERO_EXTEND;
4672     Opc = ISD::UINT_TO_FP;
4673     break;
4674   }
4675 
4676   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4677   return DAG.getNode(Opc, dl, VT, Op);
4678 }
4679 
4680 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4681   EVT VT = Op.getValueType();
4682   if (VT.isVector())
4683     return LowerVectorINT_TO_FP(Op, DAG);
4684   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4685     RTLIB::Libcall LC;
4686     if (Op.getOpcode() == ISD::SINT_TO_FP)
4687       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4688                               Op.getValueType());
4689     else
4690       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4691                               Op.getValueType());
4692     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4693                        /*isSigned*/ false, SDLoc(Op)).first;
4694   }
4695 
4696   return Op;
4697 }
4698 
4699 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4700   // Implement fcopysign with a fabs and a conditional fneg.
4701   SDValue Tmp0 = Op.getOperand(0);
4702   SDValue Tmp1 = Op.getOperand(1);
4703   SDLoc dl(Op);
4704   EVT VT = Op.getValueType();
4705   EVT SrcVT = Tmp1.getValueType();
4706   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4707     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4708   bool UseNEON = !InGPR && Subtarget->hasNEON();
4709 
4710   if (UseNEON) {
4711     // Use VBSL to copy the sign bit.
4712     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4713     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4714                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4715     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4716     if (VT == MVT::f64)
4717       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4718                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4719                          DAG.getConstant(32, dl, MVT::i32));
4720     else /*if (VT == MVT::f32)*/
4721       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4722     if (SrcVT == MVT::f32) {
4723       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4724       if (VT == MVT::f64)
4725         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4726                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4727                            DAG.getConstant(32, dl, MVT::i32));
4728     } else if (VT == MVT::f32)
4729       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4730                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4731                          DAG.getConstant(32, dl, MVT::i32));
4732     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4733     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4734 
4735     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4736                                             dl, MVT::i32);
4737     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4738     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4739                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4740 
4741     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4742                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4743                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4744     if (VT == MVT::f32) {
4745       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4746       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4747                         DAG.getConstant(0, dl, MVT::i32));
4748     } else {
4749       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4750     }
4751 
4752     return Res;
4753   }
4754 
4755   // Bitcast operand 1 to i32.
4756   if (SrcVT == MVT::f64)
4757     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4758                        Tmp1).getValue(1);
4759   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4760 
4761   // Or in the signbit with integer operations.
4762   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4763   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4764   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4765   if (VT == MVT::f32) {
4766     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4767                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4768     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4769                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4770   }
4771 
4772   // f64: Or the high part with signbit and then combine two parts.
4773   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4774                      Tmp0);
4775   SDValue Lo = Tmp0.getValue(0);
4776   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4777   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4778   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4779 }
4780 
4781 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4782   MachineFunction &MF = DAG.getMachineFunction();
4783   MachineFrameInfo &MFI = MF.getFrameInfo();
4784   MFI.setReturnAddressIsTaken(true);
4785 
4786   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4787     return SDValue();
4788 
4789   EVT VT = Op.getValueType();
4790   SDLoc dl(Op);
4791   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4792   if (Depth) {
4793     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4794     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4795     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4796                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4797                        MachinePointerInfo());
4798   }
4799 
4800   // Return LR, which contains the return address. Mark it an implicit live-in.
4801   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4802   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4803 }
4804 
4805 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4806   const ARMBaseRegisterInfo &ARI =
4807     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4808   MachineFunction &MF = DAG.getMachineFunction();
4809   MachineFrameInfo &MFI = MF.getFrameInfo();
4810   MFI.setFrameAddressIsTaken(true);
4811 
4812   EVT VT = Op.getValueType();
4813   SDLoc dl(Op);  // FIXME probably not meaningful
4814   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4815   unsigned FrameReg = ARI.getFrameRegister(MF);
4816   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4817   while (Depth--)
4818     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4819                             MachinePointerInfo());
4820   return FrameAddr;
4821 }
4822 
4823 // FIXME? Maybe this could be a TableGen attribute on some registers and
4824 // this table could be generated automatically from RegInfo.
4825 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4826                                               SelectionDAG &DAG) const {
4827   unsigned Reg = StringSwitch<unsigned>(RegName)
4828                        .Case("sp", ARM::SP)
4829                        .Default(0);
4830   if (Reg)
4831     return Reg;
4832   report_fatal_error(Twine("Invalid register name \""
4833                               + StringRef(RegName)  + "\"."));
4834 }
4835 
4836 // Result is 64 bit value so split into two 32 bit values and return as a
4837 // pair of values.
4838 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4839                                 SelectionDAG &DAG) {
4840   SDLoc DL(N);
4841 
4842   // This function is only supposed to be called for i64 type destination.
4843   assert(N->getValueType(0) == MVT::i64
4844           && "ExpandREAD_REGISTER called for non-i64 type result.");
4845 
4846   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4847                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4848                              N->getOperand(0),
4849                              N->getOperand(1));
4850 
4851   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4852                     Read.getValue(1)));
4853   Results.push_back(Read.getOperand(0));
4854 }
4855 
4856 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4857 /// When \p DstVT, the destination type of \p BC, is on the vector
4858 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4859 /// it might be possible to combine them, such that everything stays on the
4860 /// vector register bank.
4861 /// \p return The node that would replace \p BT, if the combine
4862 /// is possible.
4863 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4864                                                 SelectionDAG &DAG) {
4865   SDValue Op = BC->getOperand(0);
4866   EVT DstVT = BC->getValueType(0);
4867 
4868   // The only vector instruction that can produce a scalar (remember,
4869   // since the bitcast was about to be turned into VMOVDRR, the source
4870   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4871   // Moreover, we can do this combine only if there is one use.
4872   // Finally, if the destination type is not a vector, there is not
4873   // much point on forcing everything on the vector bank.
4874   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4875       !Op.hasOneUse())
4876     return SDValue();
4877 
4878   // If the index is not constant, we will introduce an additional
4879   // multiply that will stick.
4880   // Give up in that case.
4881   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4882   if (!Index)
4883     return SDValue();
4884   unsigned DstNumElt = DstVT.getVectorNumElements();
4885 
4886   // Compute the new index.
4887   const APInt &APIntIndex = Index->getAPIntValue();
4888   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4889   NewIndex *= APIntIndex;
4890   // Check if the new constant index fits into i32.
4891   if (NewIndex.getBitWidth() > 32)
4892     return SDValue();
4893 
4894   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
4895   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
4896   SDLoc dl(Op);
4897   SDValue ExtractSrc = Op.getOperand(0);
4898   EVT VecVT = EVT::getVectorVT(
4899       *DAG.getContext(), DstVT.getScalarType(),
4900       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
4901   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
4902   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
4903                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
4904 }
4905 
4906 /// ExpandBITCAST - If the target supports VFP, this function is called to
4907 /// expand a bit convert where either the source or destination type is i64 to
4908 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
4909 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
4910 /// vectors), since the legalizer won't know what to do with that.
4911 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
4912   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
4913   SDLoc dl(N);
4914   SDValue Op = N->getOperand(0);
4915 
4916   // This function is only supposed to be called for i64 types, either as the
4917   // source or destination of the bit convert.
4918   EVT SrcVT = Op.getValueType();
4919   EVT DstVT = N->getValueType(0);
4920   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
4921          "ExpandBITCAST called for non-i64 type");
4922 
4923   // Turn i64->f64 into VMOVDRR.
4924   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
4925     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
4926     // if we can combine the bitcast with its source.
4927     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
4928       return Val;
4929 
4930     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4931                              DAG.getConstant(0, dl, MVT::i32));
4932     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
4933                              DAG.getConstant(1, dl, MVT::i32));
4934     return DAG.getNode(ISD::BITCAST, dl, DstVT,
4935                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
4936   }
4937 
4938   // Turn f64->i64 into VMOVRRD.
4939   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
4940     SDValue Cvt;
4941     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
4942         SrcVT.getVectorNumElements() > 1)
4943       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4944                         DAG.getVTList(MVT::i32, MVT::i32),
4945                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
4946     else
4947       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
4948                         DAG.getVTList(MVT::i32, MVT::i32), Op);
4949     // Merge the pieces into a single i64 value.
4950     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
4951   }
4952 
4953   return SDValue();
4954 }
4955 
4956 /// getZeroVector - Returns a vector of specified type with all zero elements.
4957 /// Zero vectors are used to represent vector negation and in those cases
4958 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
4959 /// not support i64 elements, so sometimes the zero vectors will need to be
4960 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
4961 /// zero vector.
4962 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
4963   assert(VT.isVector() && "Expected a vector type");
4964   // The canonical modified immediate encoding of a zero vector is....0!
4965   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
4966   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
4967   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
4968   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
4969 }
4970 
4971 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
4972 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
4973 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
4974                                                 SelectionDAG &DAG) const {
4975   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
4976   EVT VT = Op.getValueType();
4977   unsigned VTBits = VT.getSizeInBits();
4978   SDLoc dl(Op);
4979   SDValue ShOpLo = Op.getOperand(0);
4980   SDValue ShOpHi = Op.getOperand(1);
4981   SDValue ShAmt  = Op.getOperand(2);
4982   SDValue ARMcc;
4983   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4984   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
4985 
4986   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
4987 
4988   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
4989                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
4990   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
4991   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
4992                                    DAG.getConstant(VTBits, dl, MVT::i32));
4993   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
4994   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
4995   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
4996   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
4997                             ISD::SETGE, ARMcc, DAG, dl);
4998   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
4999                            ARMcc, CCR, CmpLo);
5000 
5001   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5002   SDValue HiBigShift = Opc == ISD::SRA
5003                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5004                                          DAG.getConstant(VTBits - 1, dl, VT))
5005                            : DAG.getConstant(0, dl, VT);
5006   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5007                             ISD::SETGE, ARMcc, DAG, dl);
5008   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5009                            ARMcc, CCR, CmpHi);
5010 
5011   SDValue Ops[2] = { Lo, Hi };
5012   return DAG.getMergeValues(Ops, dl);
5013 }
5014 
5015 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5016 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5017 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5018                                                SelectionDAG &DAG) const {
5019   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5020   EVT VT = Op.getValueType();
5021   unsigned VTBits = VT.getSizeInBits();
5022   SDLoc dl(Op);
5023   SDValue ShOpLo = Op.getOperand(0);
5024   SDValue ShOpHi = Op.getOperand(1);
5025   SDValue ShAmt  = Op.getOperand(2);
5026   SDValue ARMcc;
5027   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5028 
5029   assert(Op.getOpcode() == ISD::SHL_PARTS);
5030   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5031                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5032   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5033   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5034   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5035 
5036   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5037                                    DAG.getConstant(VTBits, dl, MVT::i32));
5038   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5039   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5040                             ISD::SETGE, ARMcc, DAG, dl);
5041   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5042                            ARMcc, CCR, CmpHi);
5043 
5044   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5045                           ISD::SETGE, ARMcc, DAG, dl);
5046   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5047   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5048                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5049 
5050   SDValue Ops[2] = { Lo, Hi };
5051   return DAG.getMergeValues(Ops, dl);
5052 }
5053 
5054 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5055                                             SelectionDAG &DAG) const {
5056   // The rounding mode is in bits 23:22 of the FPSCR.
5057   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5058   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5059   // so that the shift + and get folded into a bitfield extract.
5060   SDLoc dl(Op);
5061   SDValue Ops[] = { DAG.getEntryNode(),
5062                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5063 
5064   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5065   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5066                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5067   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5068                               DAG.getConstant(22, dl, MVT::i32));
5069   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5070                      DAG.getConstant(3, dl, MVT::i32));
5071 }
5072 
5073 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5074                          const ARMSubtarget *ST) {
5075   SDLoc dl(N);
5076   EVT VT = N->getValueType(0);
5077   if (VT.isVector()) {
5078     assert(ST->hasNEON());
5079 
5080     // Compute the least significant set bit: LSB = X & -X
5081     SDValue X = N->getOperand(0);
5082     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5083     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5084 
5085     EVT ElemTy = VT.getVectorElementType();
5086 
5087     if (ElemTy == MVT::i8) {
5088       // Compute with: cttz(x) = ctpop(lsb - 1)
5089       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5090                                 DAG.getTargetConstant(1, dl, ElemTy));
5091       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5092       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5093     }
5094 
5095     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5096         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5097       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5098       unsigned NumBits = ElemTy.getSizeInBits();
5099       SDValue WidthMinus1 =
5100           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5101                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5102       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5103       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5104     }
5105 
5106     // Compute with: cttz(x) = ctpop(lsb - 1)
5107 
5108     // Since we can only compute the number of bits in a byte with vcnt.8, we
5109     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
5110     // and i64.
5111 
5112     // Compute LSB - 1.
5113     SDValue Bits;
5114     if (ElemTy == MVT::i64) {
5115       // Load constant 0xffff'ffff'ffff'ffff to register.
5116       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5117                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5118       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5119     } else {
5120       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5121                                 DAG.getTargetConstant(1, dl, ElemTy));
5122       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5123     }
5124 
5125     // Count #bits with vcnt.8.
5126     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5127     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5128     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5129 
5130     // Gather the #bits with vpaddl (pairwise add.)
5131     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5132     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5133         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5134         Cnt8);
5135     if (ElemTy == MVT::i16)
5136       return Cnt16;
5137 
5138     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5139     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5140         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5141         Cnt16);
5142     if (ElemTy == MVT::i32)
5143       return Cnt32;
5144 
5145     assert(ElemTy == MVT::i64);
5146     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5147         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5148         Cnt32);
5149     return Cnt64;
5150   }
5151 
5152   if (!ST->hasV6T2Ops())
5153     return SDValue();
5154 
5155   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5156   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5157 }
5158 
5159 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5160 /// for each 16-bit element from operand, repeated.  The basic idea is to
5161 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5162 ///
5163 /// Trace for v4i16:
5164 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
5165 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5166 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5167 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5168 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
5169 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
5170 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5171 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
5172 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5173   EVT VT = N->getValueType(0);
5174   SDLoc DL(N);
5175 
5176   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5177   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5178   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5179   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5180   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5181   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5182 }
5183 
5184 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5185 /// bit-count for each 16-bit element from the operand.  We need slightly
5186 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5187 /// 64/128-bit registers.
5188 ///
5189 /// Trace for v4i16:
5190 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
5191 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5192 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
5193 /// v4i16:Extracted = [k0    k1    k2    k3    ]
5194 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5195   EVT VT = N->getValueType(0);
5196   SDLoc DL(N);
5197 
5198   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5199   if (VT.is64BitVector()) {
5200     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5201     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5202                        DAG.getIntPtrConstant(0, DL));
5203   } else {
5204     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5205                                     BitCounts, DAG.getIntPtrConstant(0, DL));
5206     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5207   }
5208 }
5209 
5210 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5211 /// bit-count for each 32-bit element from the operand.  The idea here is
5212 /// to split the vector into 16-bit elements, leverage the 16-bit count
5213 /// routine, and then combine the results.
5214 ///
5215 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5216 /// input    = [v0    v1    ] (vi: 32-bit elements)
5217 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5218 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5219 /// vrev: N0 = [k1 k0 k3 k2 ]
5220 ///            [k0 k1 k2 k3 ]
5221 ///       N1 =+[k1 k0 k3 k2 ]
5222 ///            [k0 k2 k1 k3 ]
5223 ///       N2 =+[k1 k3 k0 k2 ]
5224 ///            [k0    k2    k1    k3    ]
5225 /// Extended =+[k1    k3    k0    k2    ]
5226 ///            [k0    k2    ]
5227 /// Extracted=+[k1    k3    ]
5228 ///
5229 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5230   EVT VT = N->getValueType(0);
5231   SDLoc DL(N);
5232 
5233   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5234 
5235   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5236   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5237   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5238   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5239   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5240 
5241   if (VT.is64BitVector()) {
5242     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5243     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5244                        DAG.getIntPtrConstant(0, DL));
5245   } else {
5246     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5247                                     DAG.getIntPtrConstant(0, DL));
5248     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5249   }
5250 }
5251 
5252 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5253                           const ARMSubtarget *ST) {
5254   EVT VT = N->getValueType(0);
5255 
5256   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5257   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5258           VT == MVT::v4i16 || VT == MVT::v8i16) &&
5259          "Unexpected type for custom ctpop lowering");
5260 
5261   if (VT.getVectorElementType() == MVT::i32)
5262     return lowerCTPOP32BitElements(N, DAG);
5263   else
5264     return lowerCTPOP16BitElements(N, DAG);
5265 }
5266 
5267 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5268                           const ARMSubtarget *ST) {
5269   EVT VT = N->getValueType(0);
5270   SDLoc dl(N);
5271 
5272   if (!VT.isVector())
5273     return SDValue();
5274 
5275   // Lower vector shifts on NEON to use VSHL.
5276   assert(ST->hasNEON() && "unexpected vector shift");
5277 
5278   // Left shifts translate directly to the vshiftu intrinsic.
5279   if (N->getOpcode() == ISD::SHL)
5280     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5281                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5282                                        MVT::i32),
5283                        N->getOperand(0), N->getOperand(1));
5284 
5285   assert((N->getOpcode() == ISD::SRA ||
5286           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5287 
5288   // NEON uses the same intrinsics for both left and right shifts.  For
5289   // right shifts, the shift amounts are negative, so negate the vector of
5290   // shift amounts.
5291   EVT ShiftVT = N->getOperand(1).getValueType();
5292   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5293                                      getZeroVector(ShiftVT, DAG, dl),
5294                                      N->getOperand(1));
5295   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5296                              Intrinsic::arm_neon_vshifts :
5297                              Intrinsic::arm_neon_vshiftu);
5298   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5299                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5300                      N->getOperand(0), NegatedCount);
5301 }
5302 
5303 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5304                                 const ARMSubtarget *ST) {
5305   EVT VT = N->getValueType(0);
5306   SDLoc dl(N);
5307 
5308   // We can get here for a node like i32 = ISD::SHL i32, i64
5309   if (VT != MVT::i64)
5310     return SDValue();
5311 
5312   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5313          "Unknown shift to lower!");
5314 
5315   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5316   if (!isOneConstant(N->getOperand(1)))
5317     return SDValue();
5318 
5319   // If we are in thumb mode, we don't have RRX.
5320   if (ST->isThumb1Only()) return SDValue();
5321 
5322   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5323   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5324                            DAG.getConstant(0, dl, MVT::i32));
5325   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5326                            DAG.getConstant(1, dl, MVT::i32));
5327 
5328   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5329   // captures the result into a carry flag.
5330   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5331   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5332 
5333   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5334   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5335 
5336   // Merge the pieces into a single i64 value.
5337  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5338 }
5339 
5340 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5341   SDValue TmpOp0, TmpOp1;
5342   bool Invert = false;
5343   bool Swap = false;
5344   unsigned Opc = 0;
5345 
5346   SDValue Op0 = Op.getOperand(0);
5347   SDValue Op1 = Op.getOperand(1);
5348   SDValue CC = Op.getOperand(2);
5349   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5350   EVT VT = Op.getValueType();
5351   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5352   SDLoc dl(Op);
5353 
5354   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5355       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5356     // Special-case integer 64-bit equality comparisons. They aren't legal,
5357     // but they can be lowered with a few vector instructions.
5358     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5359     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5360     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5361     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5362     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5363                               DAG.getCondCode(ISD::SETEQ));
5364     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5365     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5366     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5367     if (SetCCOpcode == ISD::SETNE)
5368       Merged = DAG.getNOT(dl, Merged, CmpVT);
5369     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5370     return Merged;
5371   }
5372 
5373   if (CmpVT.getVectorElementType() == MVT::i64)
5374     // 64-bit comparisons are not legal in general.
5375     return SDValue();
5376 
5377   if (Op1.getValueType().isFloatingPoint()) {
5378     switch (SetCCOpcode) {
5379     default: llvm_unreachable("Illegal FP comparison");
5380     case ISD::SETUNE:
5381     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5382     case ISD::SETOEQ:
5383     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5384     case ISD::SETOLT:
5385     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5386     case ISD::SETOGT:
5387     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5388     case ISD::SETOLE:
5389     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5390     case ISD::SETOGE:
5391     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5392     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5393     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5394     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5395     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5396     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5397     case ISD::SETONE:
5398       // Expand this to (OLT | OGT).
5399       TmpOp0 = Op0;
5400       TmpOp1 = Op1;
5401       Opc = ISD::OR;
5402       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5403       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5404       break;
5405     case ISD::SETUO:
5406       Invert = true;
5407       LLVM_FALLTHROUGH;
5408     case ISD::SETO:
5409       // Expand this to (OLT | OGE).
5410       TmpOp0 = Op0;
5411       TmpOp1 = Op1;
5412       Opc = ISD::OR;
5413       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5414       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5415       break;
5416     }
5417   } else {
5418     // Integer comparisons.
5419     switch (SetCCOpcode) {
5420     default: llvm_unreachable("Illegal integer comparison");
5421     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5422     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5423     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
5424     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5425     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5426     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5427     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5428     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5429     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5430     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5431     }
5432 
5433     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5434     if (Opc == ARMISD::VCEQ) {
5435       SDValue AndOp;
5436       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5437         AndOp = Op0;
5438       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5439         AndOp = Op1;
5440 
5441       // Ignore bitconvert.
5442       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5443         AndOp = AndOp.getOperand(0);
5444 
5445       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5446         Opc = ARMISD::VTST;
5447         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5448         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5449         Invert = !Invert;
5450       }
5451     }
5452   }
5453 
5454   if (Swap)
5455     std::swap(Op0, Op1);
5456 
5457   // If one of the operands is a constant vector zero, attempt to fold the
5458   // comparison to a specialized compare-against-zero form.
5459   SDValue SingleOp;
5460   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5461     SingleOp = Op0;
5462   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5463     if (Opc == ARMISD::VCGE)
5464       Opc = ARMISD::VCLEZ;
5465     else if (Opc == ARMISD::VCGT)
5466       Opc = ARMISD::VCLTZ;
5467     SingleOp = Op1;
5468   }
5469 
5470   SDValue Result;
5471   if (SingleOp.getNode()) {
5472     switch (Opc) {
5473     case ARMISD::VCEQ:
5474       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5475     case ARMISD::VCGE:
5476       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5477     case ARMISD::VCLEZ:
5478       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5479     case ARMISD::VCGT:
5480       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5481     case ARMISD::VCLTZ:
5482       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5483     default:
5484       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5485     }
5486   } else {
5487      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5488   }
5489 
5490   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5491 
5492   if (Invert)
5493     Result = DAG.getNOT(dl, Result, VT);
5494 
5495   return Result;
5496 }
5497 
5498 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5499   SDValue LHS = Op.getOperand(0);
5500   SDValue RHS = Op.getOperand(1);
5501   SDValue Carry = Op.getOperand(2);
5502   SDValue Cond = Op.getOperand(3);
5503   SDLoc DL(Op);
5504 
5505   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5506 
5507   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5508   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5509   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5510 
5511   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5512   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5513   SDValue ARMcc = DAG.getConstant(
5514       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5515   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5516   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5517                                    Cmp.getValue(1), SDValue());
5518   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5519                      CCR, Chain.getValue(1));
5520 }
5521 
5522 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5523 /// valid vector constant for a NEON instruction with a "modified immediate"
5524 /// operand (e.g., VMOV).  If so, return the encoded value.
5525 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5526                                  unsigned SplatBitSize, SelectionDAG &DAG,
5527                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5528                                  NEONModImmType type) {
5529   unsigned OpCmode, Imm;
5530 
5531   // SplatBitSize is set to the smallest size that splats the vector, so a
5532   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5533   // immediate instructions others than VMOV do not support the 8-bit encoding
5534   // of a zero vector, and the default encoding of zero is supposed to be the
5535   // 32-bit version.
5536   if (SplatBits == 0)
5537     SplatBitSize = 32;
5538 
5539   switch (SplatBitSize) {
5540   case 8:
5541     if (type != VMOVModImm)
5542       return SDValue();
5543     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5544     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5545     OpCmode = 0xe;
5546     Imm = SplatBits;
5547     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5548     break;
5549 
5550   case 16:
5551     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5552     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5553     if ((SplatBits & ~0xff) == 0) {
5554       // Value = 0x00nn: Op=x, Cmode=100x.
5555       OpCmode = 0x8;
5556       Imm = SplatBits;
5557       break;
5558     }
5559     if ((SplatBits & ~0xff00) == 0) {
5560       // Value = 0xnn00: Op=x, Cmode=101x.
5561       OpCmode = 0xa;
5562       Imm = SplatBits >> 8;
5563       break;
5564     }
5565     return SDValue();
5566 
5567   case 32:
5568     // NEON's 32-bit VMOV supports splat values where:
5569     // * only one byte is nonzero, or
5570     // * the least significant byte is 0xff and the second byte is nonzero, or
5571     // * the least significant 2 bytes are 0xff and the third is nonzero.
5572     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5573     if ((SplatBits & ~0xff) == 0) {
5574       // Value = 0x000000nn: Op=x, Cmode=000x.
5575       OpCmode = 0;
5576       Imm = SplatBits;
5577       break;
5578     }
5579     if ((SplatBits & ~0xff00) == 0) {
5580       // Value = 0x0000nn00: Op=x, Cmode=001x.
5581       OpCmode = 0x2;
5582       Imm = SplatBits >> 8;
5583       break;
5584     }
5585     if ((SplatBits & ~0xff0000) == 0) {
5586       // Value = 0x00nn0000: Op=x, Cmode=010x.
5587       OpCmode = 0x4;
5588       Imm = SplatBits >> 16;
5589       break;
5590     }
5591     if ((SplatBits & ~0xff000000) == 0) {
5592       // Value = 0xnn000000: Op=x, Cmode=011x.
5593       OpCmode = 0x6;
5594       Imm = SplatBits >> 24;
5595       break;
5596     }
5597 
5598     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5599     if (type == OtherModImm) return SDValue();
5600 
5601     if ((SplatBits & ~0xffff) == 0 &&
5602         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5603       // Value = 0x0000nnff: Op=x, Cmode=1100.
5604       OpCmode = 0xc;
5605       Imm = SplatBits >> 8;
5606       break;
5607     }
5608 
5609     if ((SplatBits & ~0xffffff) == 0 &&
5610         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5611       // Value = 0x00nnffff: Op=x, Cmode=1101.
5612       OpCmode = 0xd;
5613       Imm = SplatBits >> 16;
5614       break;
5615     }
5616 
5617     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5618     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5619     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5620     // and fall through here to test for a valid 64-bit splat.  But, then the
5621     // caller would also need to check and handle the change in size.
5622     return SDValue();
5623 
5624   case 64: {
5625     if (type != VMOVModImm)
5626       return SDValue();
5627     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5628     uint64_t BitMask = 0xff;
5629     uint64_t Val = 0;
5630     unsigned ImmMask = 1;
5631     Imm = 0;
5632     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5633       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5634         Val |= BitMask;
5635         Imm |= ImmMask;
5636       } else if ((SplatBits & BitMask) != 0) {
5637         return SDValue();
5638       }
5639       BitMask <<= 8;
5640       ImmMask <<= 1;
5641     }
5642 
5643     if (DAG.getDataLayout().isBigEndian())
5644       // swap higher and lower 32 bit word
5645       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5646 
5647     // Op=1, Cmode=1110.
5648     OpCmode = 0x1e;
5649     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5650     break;
5651   }
5652 
5653   default:
5654     llvm_unreachable("unexpected size for isNEONModifiedImm");
5655   }
5656 
5657   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5658   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5659 }
5660 
5661 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5662                                            const ARMSubtarget *ST) const {
5663   bool IsDouble = Op.getValueType() == MVT::f64;
5664   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5665   const APFloat &FPVal = CFP->getValueAPF();
5666 
5667   // Prevent floating-point constants from using literal loads
5668   // when execute-only is enabled.
5669   if (ST->genExecuteOnly()) {
5670     APInt INTVal = FPVal.bitcastToAPInt();
5671     SDLoc DL(CFP);
5672     if (IsDouble) {
5673       SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5674       SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5675       if (!ST->isLittle())
5676         std::swap(Lo, Hi);
5677       return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5678     } else {
5679       return DAG.getConstant(INTVal, DL, MVT::i32);
5680     }
5681   }
5682 
5683   if (!ST->hasVFP3())
5684     return SDValue();
5685 
5686   // Use the default (constant pool) lowering for double constants when we have
5687   // an SP-only FPU
5688   if (IsDouble && Subtarget->isFPOnlySP())
5689     return SDValue();
5690 
5691   // Try splatting with a VMOV.f32...
5692   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5693 
5694   if (ImmVal != -1) {
5695     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5696       // We have code in place to select a valid ConstantFP already, no need to
5697       // do any mangling.
5698       return Op;
5699     }
5700 
5701     // It's a float and we are trying to use NEON operations where
5702     // possible. Lower it to a splat followed by an extract.
5703     SDLoc DL(Op);
5704     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5705     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5706                                       NewVal);
5707     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5708                        DAG.getConstant(0, DL, MVT::i32));
5709   }
5710 
5711   // The rest of our options are NEON only, make sure that's allowed before
5712   // proceeding..
5713   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5714     return SDValue();
5715 
5716   EVT VMovVT;
5717   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5718 
5719   // It wouldn't really be worth bothering for doubles except for one very
5720   // important value, which does happen to match: 0.0. So make sure we don't do
5721   // anything stupid.
5722   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5723     return SDValue();
5724 
5725   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5726   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5727                                      VMovVT, false, VMOVModImm);
5728   if (NewVal != SDValue()) {
5729     SDLoc DL(Op);
5730     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5731                                       NewVal);
5732     if (IsDouble)
5733       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5734 
5735     // It's a float: cast and extract a vector element.
5736     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5737                                        VecConstant);
5738     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5739                        DAG.getConstant(0, DL, MVT::i32));
5740   }
5741 
5742   // Finally, try a VMVN.i32
5743   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5744                              false, VMVNModImm);
5745   if (NewVal != SDValue()) {
5746     SDLoc DL(Op);
5747     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5748 
5749     if (IsDouble)
5750       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5751 
5752     // It's a float: cast and extract a vector element.
5753     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5754                                        VecConstant);
5755     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5756                        DAG.getConstant(0, DL, MVT::i32));
5757   }
5758 
5759   return SDValue();
5760 }
5761 
5762 // check if an VEXT instruction can handle the shuffle mask when the
5763 // vector sources of the shuffle are the same.
5764 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5765   unsigned NumElts = VT.getVectorNumElements();
5766 
5767   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5768   if (M[0] < 0)
5769     return false;
5770 
5771   Imm = M[0];
5772 
5773   // If this is a VEXT shuffle, the immediate value is the index of the first
5774   // element.  The other shuffle indices must be the successive elements after
5775   // the first one.
5776   unsigned ExpectedElt = Imm;
5777   for (unsigned i = 1; i < NumElts; ++i) {
5778     // Increment the expected index.  If it wraps around, just follow it
5779     // back to index zero and keep going.
5780     ++ExpectedElt;
5781     if (ExpectedElt == NumElts)
5782       ExpectedElt = 0;
5783 
5784     if (M[i] < 0) continue; // ignore UNDEF indices
5785     if (ExpectedElt != static_cast<unsigned>(M[i]))
5786       return false;
5787   }
5788 
5789   return true;
5790 }
5791 
5792 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5793                        bool &ReverseVEXT, unsigned &Imm) {
5794   unsigned NumElts = VT.getVectorNumElements();
5795   ReverseVEXT = false;
5796 
5797   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5798   if (M[0] < 0)
5799     return false;
5800 
5801   Imm = M[0];
5802 
5803   // If this is a VEXT shuffle, the immediate value is the index of the first
5804   // element.  The other shuffle indices must be the successive elements after
5805   // the first one.
5806   unsigned ExpectedElt = Imm;
5807   for (unsigned i = 1; i < NumElts; ++i) {
5808     // Increment the expected index.  If it wraps around, it may still be
5809     // a VEXT but the source vectors must be swapped.
5810     ExpectedElt += 1;
5811     if (ExpectedElt == NumElts * 2) {
5812       ExpectedElt = 0;
5813       ReverseVEXT = true;
5814     }
5815 
5816     if (M[i] < 0) continue; // ignore UNDEF indices
5817     if (ExpectedElt != static_cast<unsigned>(M[i]))
5818       return false;
5819   }
5820 
5821   // Adjust the index value if the source operands will be swapped.
5822   if (ReverseVEXT)
5823     Imm -= NumElts;
5824 
5825   return true;
5826 }
5827 
5828 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5829 /// instruction with the specified blocksize.  (The order of the elements
5830 /// within each block of the vector is reversed.)
5831 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5832   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5833          "Only possible block sizes for VREV are: 16, 32, 64");
5834 
5835   unsigned EltSz = VT.getScalarSizeInBits();
5836   if (EltSz == 64)
5837     return false;
5838 
5839   unsigned NumElts = VT.getVectorNumElements();
5840   unsigned BlockElts = M[0] + 1;
5841   // If the first shuffle index is UNDEF, be optimistic.
5842   if (M[0] < 0)
5843     BlockElts = BlockSize / EltSz;
5844 
5845   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5846     return false;
5847 
5848   for (unsigned i = 0; i < NumElts; ++i) {
5849     if (M[i] < 0) continue; // ignore UNDEF indices
5850     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5851       return false;
5852   }
5853 
5854   return true;
5855 }
5856 
5857 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5858   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5859   // range, then 0 is placed into the resulting vector. So pretty much any mask
5860   // of 8 elements can work here.
5861   return VT == MVT::v8i8 && M.size() == 8;
5862 }
5863 
5864 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
5865                                unsigned Index) {
5866   if (Mask.size() == Elements * 2)
5867     return Index / Elements;
5868   return Mask[Index] == 0 ? 0 : 1;
5869 }
5870 
5871 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5872 // checking that pairs of elements in the shuffle mask represent the same index
5873 // in each vector, incrementing the expected index by 2 at each step.
5874 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5875 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5876 //  v2={e,f,g,h}
5877 // WhichResult gives the offset for each element in the mask based on which
5878 // of the two results it belongs to.
5879 //
5880 // The transpose can be represented either as:
5881 // result1 = shufflevector v1, v2, result1_shuffle_mask
5882 // result2 = shufflevector v1, v2, result2_shuffle_mask
5883 // where v1/v2 and the shuffle masks have the same number of elements
5884 // (here WhichResult (see below) indicates which result is being checked)
5885 //
5886 // or as:
5887 // results = shufflevector v1, v2, shuffle_mask
5888 // where both results are returned in one vector and the shuffle mask has twice
5889 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5890 // want to check the low half and high half of the shuffle mask as if it were
5891 // the other case
5892 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5893   unsigned EltSz = VT.getScalarSizeInBits();
5894   if (EltSz == 64)
5895     return false;
5896 
5897   unsigned NumElts = VT.getVectorNumElements();
5898   if (M.size() != NumElts && M.size() != NumElts*2)
5899     return false;
5900 
5901   // If the mask is twice as long as the input vector then we need to check the
5902   // upper and lower parts of the mask with a matching value for WhichResult
5903   // FIXME: A mask with only even values will be rejected in case the first
5904   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
5905   // M[0] is used to determine WhichResult
5906   for (unsigned i = 0; i < M.size(); i += NumElts) {
5907     WhichResult = SelectPairHalf(NumElts, M, i);
5908     for (unsigned j = 0; j < NumElts; j += 2) {
5909       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5910           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
5911         return false;
5912     }
5913   }
5914 
5915   if (M.size() == NumElts*2)
5916     WhichResult = 0;
5917 
5918   return true;
5919 }
5920 
5921 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
5922 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5923 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
5924 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5925   unsigned EltSz = VT.getScalarSizeInBits();
5926   if (EltSz == 64)
5927     return false;
5928 
5929   unsigned NumElts = VT.getVectorNumElements();
5930   if (M.size() != NumElts && M.size() != NumElts*2)
5931     return false;
5932 
5933   for (unsigned i = 0; i < M.size(); i += NumElts) {
5934     WhichResult = SelectPairHalf(NumElts, M, i);
5935     for (unsigned j = 0; j < NumElts; j += 2) {
5936       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
5937           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
5938         return false;
5939     }
5940   }
5941 
5942   if (M.size() == NumElts*2)
5943     WhichResult = 0;
5944 
5945   return true;
5946 }
5947 
5948 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
5949 // that the mask elements are either all even and in steps of size 2 or all odd
5950 // and in steps of size 2.
5951 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
5952 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
5953 //  v2={e,f,g,h}
5954 // Requires similar checks to that of isVTRNMask with
5955 // respect the how results are returned.
5956 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
5957   unsigned EltSz = VT.getScalarSizeInBits();
5958   if (EltSz == 64)
5959     return false;
5960 
5961   unsigned NumElts = VT.getVectorNumElements();
5962   if (M.size() != NumElts && M.size() != NumElts*2)
5963     return false;
5964 
5965   for (unsigned i = 0; i < M.size(); i += NumElts) {
5966     WhichResult = SelectPairHalf(NumElts, M, i);
5967     for (unsigned j = 0; j < NumElts; ++j) {
5968       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
5969         return false;
5970     }
5971   }
5972 
5973   if (M.size() == NumElts*2)
5974     WhichResult = 0;
5975 
5976   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
5977   if (VT.is64BitVector() && EltSz == 32)
5978     return false;
5979 
5980   return true;
5981 }
5982 
5983 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
5984 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
5985 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
5986 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
5987   unsigned EltSz = VT.getScalarSizeInBits();
5988   if (EltSz == 64)
5989     return false;
5990 
5991   unsigned NumElts = VT.getVectorNumElements();
5992   if (M.size() != NumElts && M.size() != NumElts*2)
5993     return false;
5994 
5995   unsigned Half = NumElts / 2;
5996   for (unsigned i = 0; i < M.size(); i += NumElts) {
5997     WhichResult = SelectPairHalf(NumElts, M, i);
5998     for (unsigned j = 0; j < NumElts; j += Half) {
5999       unsigned Idx = WhichResult;
6000       for (unsigned k = 0; k < Half; ++k) {
6001         int MIdx = M[i + j + k];
6002         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6003           return false;
6004         Idx += 2;
6005       }
6006     }
6007   }
6008 
6009   if (M.size() == NumElts*2)
6010     WhichResult = 0;
6011 
6012   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6013   if (VT.is64BitVector() && EltSz == 32)
6014     return false;
6015 
6016   return true;
6017 }
6018 
6019 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6020 // that pairs of elements of the shufflemask represent the same index in each
6021 // vector incrementing sequentially through the vectors.
6022 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6023 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6024 //  v2={e,f,g,h}
6025 // Requires similar checks to that of isVTRNMask with respect the how results
6026 // are returned.
6027 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6028   unsigned EltSz = VT.getScalarSizeInBits();
6029   if (EltSz == 64)
6030     return false;
6031 
6032   unsigned NumElts = VT.getVectorNumElements();
6033   if (M.size() != NumElts && M.size() != NumElts*2)
6034     return false;
6035 
6036   for (unsigned i = 0; i < M.size(); i += NumElts) {
6037     WhichResult = SelectPairHalf(NumElts, M, i);
6038     unsigned Idx = WhichResult * NumElts / 2;
6039     for (unsigned j = 0; j < NumElts; j += 2) {
6040       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6041           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6042         return false;
6043       Idx += 1;
6044     }
6045   }
6046 
6047   if (M.size() == NumElts*2)
6048     WhichResult = 0;
6049 
6050   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6051   if (VT.is64BitVector() && EltSz == 32)
6052     return false;
6053 
6054   return true;
6055 }
6056 
6057 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6058 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6059 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6060 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6061   unsigned EltSz = VT.getScalarSizeInBits();
6062   if (EltSz == 64)
6063     return false;
6064 
6065   unsigned NumElts = VT.getVectorNumElements();
6066   if (M.size() != NumElts && M.size() != NumElts*2)
6067     return false;
6068 
6069   for (unsigned i = 0; i < M.size(); i += NumElts) {
6070     WhichResult = SelectPairHalf(NumElts, M, i);
6071     unsigned Idx = WhichResult * NumElts / 2;
6072     for (unsigned j = 0; j < NumElts; j += 2) {
6073       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6074           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6075         return false;
6076       Idx += 1;
6077     }
6078   }
6079 
6080   if (M.size() == NumElts*2)
6081     WhichResult = 0;
6082 
6083   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6084   if (VT.is64BitVector() && EltSz == 32)
6085     return false;
6086 
6087   return true;
6088 }
6089 
6090 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6091 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6092 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6093                                            unsigned &WhichResult,
6094                                            bool &isV_UNDEF) {
6095   isV_UNDEF = false;
6096   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6097     return ARMISD::VTRN;
6098   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6099     return ARMISD::VUZP;
6100   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6101     return ARMISD::VZIP;
6102 
6103   isV_UNDEF = true;
6104   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6105     return ARMISD::VTRN;
6106   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6107     return ARMISD::VUZP;
6108   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6109     return ARMISD::VZIP;
6110 
6111   return 0;
6112 }
6113 
6114 /// \return true if this is a reverse operation on an vector.
6115 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6116   unsigned NumElts = VT.getVectorNumElements();
6117   // Make sure the mask has the right size.
6118   if (NumElts != M.size())
6119       return false;
6120 
6121   // Look for <15, ..., 3, -1, 1, 0>.
6122   for (unsigned i = 0; i != NumElts; ++i)
6123     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6124       return false;
6125 
6126   return true;
6127 }
6128 
6129 // If N is an integer constant that can be moved into a register in one
6130 // instruction, return an SDValue of such a constant (will become a MOV
6131 // instruction).  Otherwise return null.
6132 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6133                                      const ARMSubtarget *ST, const SDLoc &dl) {
6134   uint64_t Val;
6135   if (!isa<ConstantSDNode>(N))
6136     return SDValue();
6137   Val = cast<ConstantSDNode>(N)->getZExtValue();
6138 
6139   if (ST->isThumb1Only()) {
6140     if (Val <= 255 || ~Val <= 255)
6141       return DAG.getConstant(Val, dl, MVT::i32);
6142   } else {
6143     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6144       return DAG.getConstant(Val, dl, MVT::i32);
6145   }
6146   return SDValue();
6147 }
6148 
6149 // If this is a case we can't handle, return null and let the default
6150 // expansion code take care of it.
6151 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6152                                              const ARMSubtarget *ST) const {
6153   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6154   SDLoc dl(Op);
6155   EVT VT = Op.getValueType();
6156 
6157   APInt SplatBits, SplatUndef;
6158   unsigned SplatBitSize;
6159   bool HasAnyUndefs;
6160   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6161     if (SplatUndef.isAllOnesValue())
6162       return DAG.getUNDEF(VT);
6163 
6164     if (SplatBitSize <= 64) {
6165       // Check if an immediate VMOV works.
6166       EVT VmovVT;
6167       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6168                                       SplatUndef.getZExtValue(), SplatBitSize,
6169                                       DAG, dl, VmovVT, VT.is128BitVector(),
6170                                       VMOVModImm);
6171       if (Val.getNode()) {
6172         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6173         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6174       }
6175 
6176       // Try an immediate VMVN.
6177       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6178       Val = isNEONModifiedImm(NegatedImm,
6179                                       SplatUndef.getZExtValue(), SplatBitSize,
6180                                       DAG, dl, VmovVT, VT.is128BitVector(),
6181                                       VMVNModImm);
6182       if (Val.getNode()) {
6183         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6184         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6185       }
6186 
6187       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6188       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6189         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6190         if (ImmVal != -1) {
6191           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6192           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6193         }
6194       }
6195     }
6196   }
6197 
6198   // Scan through the operands to see if only one value is used.
6199   //
6200   // As an optimisation, even if more than one value is used it may be more
6201   // profitable to splat with one value then change some lanes.
6202   //
6203   // Heuristically we decide to do this if the vector has a "dominant" value,
6204   // defined as splatted to more than half of the lanes.
6205   unsigned NumElts = VT.getVectorNumElements();
6206   bool isOnlyLowElement = true;
6207   bool usesOnlyOneValue = true;
6208   bool hasDominantValue = false;
6209   bool isConstant = true;
6210 
6211   // Map of the number of times a particular SDValue appears in the
6212   // element list.
6213   DenseMap<SDValue, unsigned> ValueCounts;
6214   SDValue Value;
6215   for (unsigned i = 0; i < NumElts; ++i) {
6216     SDValue V = Op.getOperand(i);
6217     if (V.isUndef())
6218       continue;
6219     if (i > 0)
6220       isOnlyLowElement = false;
6221     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6222       isConstant = false;
6223 
6224     ValueCounts.insert(std::make_pair(V, 0));
6225     unsigned &Count = ValueCounts[V];
6226 
6227     // Is this value dominant? (takes up more than half of the lanes)
6228     if (++Count > (NumElts / 2)) {
6229       hasDominantValue = true;
6230       Value = V;
6231     }
6232   }
6233   if (ValueCounts.size() != 1)
6234     usesOnlyOneValue = false;
6235   if (!Value.getNode() && !ValueCounts.empty())
6236     Value = ValueCounts.begin()->first;
6237 
6238   if (ValueCounts.empty())
6239     return DAG.getUNDEF(VT);
6240 
6241   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6242   // Keep going if we are hitting this case.
6243   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6244     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6245 
6246   unsigned EltSize = VT.getScalarSizeInBits();
6247 
6248   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6249   // i32 and try again.
6250   if (hasDominantValue && EltSize <= 32) {
6251     if (!isConstant) {
6252       SDValue N;
6253 
6254       // If we are VDUPing a value that comes directly from a vector, that will
6255       // cause an unnecessary move to and from a GPR, where instead we could
6256       // just use VDUPLANE. We can only do this if the lane being extracted
6257       // is at a constant index, as the VDUP from lane instructions only have
6258       // constant-index forms.
6259       ConstantSDNode *constIndex;
6260       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6261           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6262         // We need to create a new undef vector to use for the VDUPLANE if the
6263         // size of the vector from which we get the value is different than the
6264         // size of the vector that we need to create. We will insert the element
6265         // such that the register coalescer will remove unnecessary copies.
6266         if (VT != Value->getOperand(0).getValueType()) {
6267           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6268                              VT.getVectorNumElements();
6269           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6270                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6271                         Value, DAG.getConstant(index, dl, MVT::i32)),
6272                            DAG.getConstant(index, dl, MVT::i32));
6273         } else
6274           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6275                         Value->getOperand(0), Value->getOperand(1));
6276       } else
6277         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6278 
6279       if (!usesOnlyOneValue) {
6280         // The dominant value was splatted as 'N', but we now have to insert
6281         // all differing elements.
6282         for (unsigned I = 0; I < NumElts; ++I) {
6283           if (Op.getOperand(I) == Value)
6284             continue;
6285           SmallVector<SDValue, 3> Ops;
6286           Ops.push_back(N);
6287           Ops.push_back(Op.getOperand(I));
6288           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6289           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6290         }
6291       }
6292       return N;
6293     }
6294     if (VT.getVectorElementType().isFloatingPoint()) {
6295       SmallVector<SDValue, 8> Ops;
6296       for (unsigned i = 0; i < NumElts; ++i)
6297         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6298                                   Op.getOperand(i)));
6299       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6300       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6301       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6302       if (Val.getNode())
6303         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6304     }
6305     if (usesOnlyOneValue) {
6306       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6307       if (isConstant && Val.getNode())
6308         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6309     }
6310   }
6311 
6312   // If all elements are constants and the case above didn't get hit, fall back
6313   // to the default expansion, which will generate a load from the constant
6314   // pool.
6315   if (isConstant)
6316     return SDValue();
6317 
6318   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6319   if (NumElts >= 4) {
6320     SDValue shuffle = ReconstructShuffle(Op, DAG);
6321     if (shuffle != SDValue())
6322       return shuffle;
6323   }
6324 
6325   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6326     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6327     // into two 64-bit vectors; we might discover a better way to lower it.
6328     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6329     EVT ExtVT = VT.getVectorElementType();
6330     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6331     SDValue Lower =
6332         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6333     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6334       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6335     SDValue Upper = DAG.getBuildVector(
6336         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6337     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6338       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6339     if (Lower && Upper)
6340       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6341   }
6342 
6343   // Vectors with 32- or 64-bit elements can be built by directly assigning
6344   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6345   // will be legalized.
6346   if (EltSize >= 32) {
6347     // Do the expansion with floating-point types, since that is what the VFP
6348     // registers are defined to use, and since i64 is not legal.
6349     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6350     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6351     SmallVector<SDValue, 8> Ops;
6352     for (unsigned i = 0; i < NumElts; ++i)
6353       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6354     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6355     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6356   }
6357 
6358   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6359   // know the default expansion would otherwise fall back on something even
6360   // worse. For a vector with one or two non-undef values, that's
6361   // scalar_to_vector for the elements followed by a shuffle (provided the
6362   // shuffle is valid for the target) and materialization element by element
6363   // on the stack followed by a load for everything else.
6364   if (!isConstant && !usesOnlyOneValue) {
6365     SDValue Vec = DAG.getUNDEF(VT);
6366     for (unsigned i = 0 ; i < NumElts; ++i) {
6367       SDValue V = Op.getOperand(i);
6368       if (V.isUndef())
6369         continue;
6370       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6371       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6372     }
6373     return Vec;
6374   }
6375 
6376   return SDValue();
6377 }
6378 
6379 // Gather data to see if the operation can be modelled as a
6380 // shuffle in combination with VEXTs.
6381 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6382                                               SelectionDAG &DAG) const {
6383   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6384   SDLoc dl(Op);
6385   EVT VT = Op.getValueType();
6386   unsigned NumElts = VT.getVectorNumElements();
6387 
6388   struct ShuffleSourceInfo {
6389     SDValue Vec;
6390     unsigned MinElt = std::numeric_limits<unsigned>::max();
6391     unsigned MaxElt = 0;
6392 
6393     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6394     // be compatible with the shuffle we intend to construct. As a result
6395     // ShuffleVec will be some sliding window into the original Vec.
6396     SDValue ShuffleVec;
6397 
6398     // Code should guarantee that element i in Vec starts at element "WindowBase
6399     // + i * WindowScale in ShuffleVec".
6400     int WindowBase = 0;
6401     int WindowScale = 1;
6402 
6403     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6404 
6405     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6406   };
6407 
6408   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6409   // node.
6410   SmallVector<ShuffleSourceInfo, 2> Sources;
6411   for (unsigned i = 0; i < NumElts; ++i) {
6412     SDValue V = Op.getOperand(i);
6413     if (V.isUndef())
6414       continue;
6415     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6416       // A shuffle can only come from building a vector from various
6417       // elements of other vectors.
6418       return SDValue();
6419     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6420       // Furthermore, shuffles require a constant mask, whereas extractelts
6421       // accept variable indices.
6422       return SDValue();
6423     }
6424 
6425     // Add this element source to the list if it's not already there.
6426     SDValue SourceVec = V.getOperand(0);
6427     auto Source = llvm::find(Sources, SourceVec);
6428     if (Source == Sources.end())
6429       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6430 
6431     // Update the minimum and maximum lane number seen.
6432     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6433     Source->MinElt = std::min(Source->MinElt, EltNo);
6434     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6435   }
6436 
6437   // Currently only do something sane when at most two source vectors
6438   // are involved.
6439   if (Sources.size() > 2)
6440     return SDValue();
6441 
6442   // Find out the smallest element size among result and two sources, and use
6443   // it as element size to build the shuffle_vector.
6444   EVT SmallestEltTy = VT.getVectorElementType();
6445   for (auto &Source : Sources) {
6446     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6447     if (SrcEltTy.bitsLT(SmallestEltTy))
6448       SmallestEltTy = SrcEltTy;
6449   }
6450   unsigned ResMultiplier =
6451       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6452   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6453   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6454 
6455   // If the source vector is too wide or too narrow, we may nevertheless be able
6456   // to construct a compatible shuffle either by concatenating it with UNDEF or
6457   // extracting a suitable range of elements.
6458   for (auto &Src : Sources) {
6459     EVT SrcVT = Src.ShuffleVec.getValueType();
6460 
6461     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6462       continue;
6463 
6464     // This stage of the search produces a source with the same element type as
6465     // the original, but with a total width matching the BUILD_VECTOR output.
6466     EVT EltVT = SrcVT.getVectorElementType();
6467     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6468     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6469 
6470     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6471       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6472         return SDValue();
6473       // We can pad out the smaller vector for free, so if it's part of a
6474       // shuffle...
6475       Src.ShuffleVec =
6476           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6477                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6478       continue;
6479     }
6480 
6481     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6482       return SDValue();
6483 
6484     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6485       // Span too large for a VEXT to cope
6486       return SDValue();
6487     }
6488 
6489     if (Src.MinElt >= NumSrcElts) {
6490       // The extraction can just take the second half
6491       Src.ShuffleVec =
6492           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6493                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6494       Src.WindowBase = -NumSrcElts;
6495     } else if (Src.MaxElt < NumSrcElts) {
6496       // The extraction can just take the first half
6497       Src.ShuffleVec =
6498           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6499                       DAG.getConstant(0, dl, MVT::i32));
6500     } else {
6501       // An actual VEXT is needed
6502       SDValue VEXTSrc1 =
6503           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6504                       DAG.getConstant(0, dl, MVT::i32));
6505       SDValue VEXTSrc2 =
6506           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6507                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6508 
6509       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6510                                    VEXTSrc2,
6511                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6512       Src.WindowBase = -Src.MinElt;
6513     }
6514   }
6515 
6516   // Another possible incompatibility occurs from the vector element types. We
6517   // can fix this by bitcasting the source vectors to the same type we intend
6518   // for the shuffle.
6519   for (auto &Src : Sources) {
6520     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6521     if (SrcEltTy == SmallestEltTy)
6522       continue;
6523     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6524     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6525     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6526     Src.WindowBase *= Src.WindowScale;
6527   }
6528 
6529   // Final sanity check before we try to actually produce a shuffle.
6530   DEBUG(
6531     for (auto Src : Sources)
6532       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6533   );
6534 
6535   // The stars all align, our next step is to produce the mask for the shuffle.
6536   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6537   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6538   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6539     SDValue Entry = Op.getOperand(i);
6540     if (Entry.isUndef())
6541       continue;
6542 
6543     auto Src = llvm::find(Sources, Entry.getOperand(0));
6544     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6545 
6546     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6547     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6548     // segment.
6549     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6550     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6551                                VT.getScalarSizeInBits());
6552     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6553 
6554     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6555     // starting at the appropriate offset.
6556     int *LaneMask = &Mask[i * ResMultiplier];
6557 
6558     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6559     ExtractBase += NumElts * (Src - Sources.begin());
6560     for (int j = 0; j < LanesDefined; ++j)
6561       LaneMask[j] = ExtractBase + j;
6562   }
6563 
6564   // Final check before we try to produce nonsense...
6565   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6566     return SDValue();
6567 
6568   // We can't handle more than two sources. This should have already
6569   // been checked before this point.
6570   assert(Sources.size() <= 2 && "Too many sources!");
6571 
6572   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6573   for (unsigned i = 0; i < Sources.size(); ++i)
6574     ShuffleOps[i] = Sources[i].ShuffleVec;
6575 
6576   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6577                                          ShuffleOps[1], Mask);
6578   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6579 }
6580 
6581 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6582 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6583 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6584 /// are assumed to be legal.
6585 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
6586   if (VT.getVectorNumElements() == 4 &&
6587       (VT.is128BitVector() || VT.is64BitVector())) {
6588     unsigned PFIndexes[4];
6589     for (unsigned i = 0; i != 4; ++i) {
6590       if (M[i] < 0)
6591         PFIndexes[i] = 8;
6592       else
6593         PFIndexes[i] = M[i];
6594     }
6595 
6596     // Compute the index in the perfect shuffle table.
6597     unsigned PFTableIndex =
6598       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6599     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6600     unsigned Cost = (PFEntry >> 30);
6601 
6602     if (Cost <= 4)
6603       return true;
6604   }
6605 
6606   bool ReverseVEXT, isV_UNDEF;
6607   unsigned Imm, WhichResult;
6608 
6609   unsigned EltSize = VT.getScalarSizeInBits();
6610   return (EltSize >= 32 ||
6611           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6612           isVREVMask(M, VT, 64) ||
6613           isVREVMask(M, VT, 32) ||
6614           isVREVMask(M, VT, 16) ||
6615           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6616           isVTBLMask(M, VT) ||
6617           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6618           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6619 }
6620 
6621 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6622 /// the specified operations to build the shuffle.
6623 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6624                                       SDValue RHS, SelectionDAG &DAG,
6625                                       const SDLoc &dl) {
6626   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6627   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6628   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6629 
6630   enum {
6631     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6632     OP_VREV,
6633     OP_VDUP0,
6634     OP_VDUP1,
6635     OP_VDUP2,
6636     OP_VDUP3,
6637     OP_VEXT1,
6638     OP_VEXT2,
6639     OP_VEXT3,
6640     OP_VUZPL, // VUZP, left result
6641     OP_VUZPR, // VUZP, right result
6642     OP_VZIPL, // VZIP, left result
6643     OP_VZIPR, // VZIP, right result
6644     OP_VTRNL, // VTRN, left result
6645     OP_VTRNR  // VTRN, right result
6646   };
6647 
6648   if (OpNum == OP_COPY) {
6649     if (LHSID == (1*9+2)*9+3) return LHS;
6650     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6651     return RHS;
6652   }
6653 
6654   SDValue OpLHS, OpRHS;
6655   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6656   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6657   EVT VT = OpLHS.getValueType();
6658 
6659   switch (OpNum) {
6660   default: llvm_unreachable("Unknown shuffle opcode!");
6661   case OP_VREV:
6662     // VREV divides the vector in half and swaps within the half.
6663     if (VT.getVectorElementType() == MVT::i32 ||
6664         VT.getVectorElementType() == MVT::f32)
6665       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6666     // vrev <4 x i16> -> VREV32
6667     if (VT.getVectorElementType() == MVT::i16)
6668       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6669     // vrev <4 x i8> -> VREV16
6670     assert(VT.getVectorElementType() == MVT::i8);
6671     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6672   case OP_VDUP0:
6673   case OP_VDUP1:
6674   case OP_VDUP2:
6675   case OP_VDUP3:
6676     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6677                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6678   case OP_VEXT1:
6679   case OP_VEXT2:
6680   case OP_VEXT3:
6681     return DAG.getNode(ARMISD::VEXT, dl, VT,
6682                        OpLHS, OpRHS,
6683                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6684   case OP_VUZPL:
6685   case OP_VUZPR:
6686     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6687                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6688   case OP_VZIPL:
6689   case OP_VZIPR:
6690     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6691                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6692   case OP_VTRNL:
6693   case OP_VTRNR:
6694     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6695                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6696   }
6697 }
6698 
6699 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6700                                        ArrayRef<int> ShuffleMask,
6701                                        SelectionDAG &DAG) {
6702   // Check to see if we can use the VTBL instruction.
6703   SDValue V1 = Op.getOperand(0);
6704   SDValue V2 = Op.getOperand(1);
6705   SDLoc DL(Op);
6706 
6707   SmallVector<SDValue, 8> VTBLMask;
6708   for (ArrayRef<int>::iterator
6709          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6710     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6711 
6712   if (V2.getNode()->isUndef())
6713     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6714                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6715 
6716   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6717                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6718 }
6719 
6720 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6721                                                       SelectionDAG &DAG) {
6722   SDLoc DL(Op);
6723   SDValue OpLHS = Op.getOperand(0);
6724   EVT VT = OpLHS.getValueType();
6725 
6726   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6727          "Expect an v8i16/v16i8 type");
6728   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6729   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6730   // extract the first 8 bytes into the top double word and the last 8 bytes
6731   // into the bottom double word. The v8i16 case is similar.
6732   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6733   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6734                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6735 }
6736 
6737 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6738   SDValue V1 = Op.getOperand(0);
6739   SDValue V2 = Op.getOperand(1);
6740   SDLoc dl(Op);
6741   EVT VT = Op.getValueType();
6742   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6743 
6744   // Convert shuffles that are directly supported on NEON to target-specific
6745   // DAG nodes, instead of keeping them as shuffles and matching them again
6746   // during code selection.  This is more efficient and avoids the possibility
6747   // of inconsistencies between legalization and selection.
6748   // FIXME: floating-point vectors should be canonicalized to integer vectors
6749   // of the same time so that they get CSEd properly.
6750   ArrayRef<int> ShuffleMask = SVN->getMask();
6751 
6752   unsigned EltSize = VT.getScalarSizeInBits();
6753   if (EltSize <= 32) {
6754     if (SVN->isSplat()) {
6755       int Lane = SVN->getSplatIndex();
6756       // If this is undef splat, generate it via "just" vdup, if possible.
6757       if (Lane == -1) Lane = 0;
6758 
6759       // Test if V1 is a SCALAR_TO_VECTOR.
6760       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6761         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6762       }
6763       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6764       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6765       // reaches it).
6766       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6767           !isa<ConstantSDNode>(V1.getOperand(0))) {
6768         bool IsScalarToVector = true;
6769         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6770           if (!V1.getOperand(i).isUndef()) {
6771             IsScalarToVector = false;
6772             break;
6773           }
6774         if (IsScalarToVector)
6775           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6776       }
6777       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6778                          DAG.getConstant(Lane, dl, MVT::i32));
6779     }
6780 
6781     bool ReverseVEXT;
6782     unsigned Imm;
6783     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6784       if (ReverseVEXT)
6785         std::swap(V1, V2);
6786       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6787                          DAG.getConstant(Imm, dl, MVT::i32));
6788     }
6789 
6790     if (isVREVMask(ShuffleMask, VT, 64))
6791       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6792     if (isVREVMask(ShuffleMask, VT, 32))
6793       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6794     if (isVREVMask(ShuffleMask, VT, 16))
6795       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6796 
6797     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6798       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6799                          DAG.getConstant(Imm, dl, MVT::i32));
6800     }
6801 
6802     // Check for Neon shuffles that modify both input vectors in place.
6803     // If both results are used, i.e., if there are two shuffles with the same
6804     // source operands and with masks corresponding to both results of one of
6805     // these operations, DAG memoization will ensure that a single node is
6806     // used for both shuffles.
6807     unsigned WhichResult;
6808     bool isV_UNDEF;
6809     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6810             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6811       if (isV_UNDEF)
6812         V2 = V1;
6813       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6814           .getValue(WhichResult);
6815     }
6816 
6817     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6818     // shuffles that produce a result larger than their operands with:
6819     //   shuffle(concat(v1, undef), concat(v2, undef))
6820     // ->
6821     //   shuffle(concat(v1, v2), undef)
6822     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6823     //
6824     // This is useful in the general case, but there are special cases where
6825     // native shuffles produce larger results: the two-result ops.
6826     //
6827     // Look through the concat when lowering them:
6828     //   shuffle(concat(v1, v2), undef)
6829     // ->
6830     //   concat(VZIP(v1, v2):0, :1)
6831     //
6832     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6833       SDValue SubV1 = V1->getOperand(0);
6834       SDValue SubV2 = V1->getOperand(1);
6835       EVT SubVT = SubV1.getValueType();
6836 
6837       // We expect these to have been canonicalized to -1.
6838       assert(llvm::all_of(ShuffleMask, [&](int i) {
6839         return i < (int)VT.getVectorNumElements();
6840       }) && "Unexpected shuffle index into UNDEF operand!");
6841 
6842       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6843               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6844         if (isV_UNDEF)
6845           SubV2 = SubV1;
6846         assert((WhichResult == 0) &&
6847                "In-place shuffle of concat can only have one result!");
6848         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6849                                   SubV1, SubV2);
6850         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6851                            Res.getValue(1));
6852       }
6853     }
6854   }
6855 
6856   // If the shuffle is not directly supported and it has 4 elements, use
6857   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6858   unsigned NumElts = VT.getVectorNumElements();
6859   if (NumElts == 4) {
6860     unsigned PFIndexes[4];
6861     for (unsigned i = 0; i != 4; ++i) {
6862       if (ShuffleMask[i] < 0)
6863         PFIndexes[i] = 8;
6864       else
6865         PFIndexes[i] = ShuffleMask[i];
6866     }
6867 
6868     // Compute the index in the perfect shuffle table.
6869     unsigned PFTableIndex =
6870       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6871     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6872     unsigned Cost = (PFEntry >> 30);
6873 
6874     if (Cost <= 4)
6875       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6876   }
6877 
6878   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6879   if (EltSize >= 32) {
6880     // Do the expansion with floating-point types, since that is what the VFP
6881     // registers are defined to use, and since i64 is not legal.
6882     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6883     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6884     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6885     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6886     SmallVector<SDValue, 8> Ops;
6887     for (unsigned i = 0; i < NumElts; ++i) {
6888       if (ShuffleMask[i] < 0)
6889         Ops.push_back(DAG.getUNDEF(EltVT));
6890       else
6891         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6892                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
6893                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
6894                                                   dl, MVT::i32)));
6895     }
6896     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6897     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6898   }
6899 
6900   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
6901     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
6902 
6903   if (VT == MVT::v8i8)
6904     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
6905       return NewOp;
6906 
6907   return SDValue();
6908 }
6909 
6910 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6911   // INSERT_VECTOR_ELT is legal only for immediate indexes.
6912   SDValue Lane = Op.getOperand(2);
6913   if (!isa<ConstantSDNode>(Lane))
6914     return SDValue();
6915 
6916   return Op;
6917 }
6918 
6919 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
6920   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
6921   SDValue Lane = Op.getOperand(1);
6922   if (!isa<ConstantSDNode>(Lane))
6923     return SDValue();
6924 
6925   SDValue Vec = Op.getOperand(0);
6926   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
6927     SDLoc dl(Op);
6928     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
6929   }
6930 
6931   return Op;
6932 }
6933 
6934 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6935   // The only time a CONCAT_VECTORS operation can have legal types is when
6936   // two 64-bit vectors are concatenated to a 128-bit vector.
6937   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
6938          "unexpected CONCAT_VECTORS");
6939   SDLoc dl(Op);
6940   SDValue Val = DAG.getUNDEF(MVT::v2f64);
6941   SDValue Op0 = Op.getOperand(0);
6942   SDValue Op1 = Op.getOperand(1);
6943   if (!Op0.isUndef())
6944     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6945                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
6946                       DAG.getIntPtrConstant(0, dl));
6947   if (!Op1.isUndef())
6948     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
6949                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
6950                       DAG.getIntPtrConstant(1, dl));
6951   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
6952 }
6953 
6954 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
6955 /// element has been zero/sign-extended, depending on the isSigned parameter,
6956 /// from an integer type half its size.
6957 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
6958                                    bool isSigned) {
6959   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
6960   EVT VT = N->getValueType(0);
6961   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
6962     SDNode *BVN = N->getOperand(0).getNode();
6963     if (BVN->getValueType(0) != MVT::v4i32 ||
6964         BVN->getOpcode() != ISD::BUILD_VECTOR)
6965       return false;
6966     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
6967     unsigned HiElt = 1 - LoElt;
6968     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
6969     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
6970     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
6971     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
6972     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
6973       return false;
6974     if (isSigned) {
6975       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
6976           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
6977         return true;
6978     } else {
6979       if (Hi0->isNullValue() && Hi1->isNullValue())
6980         return true;
6981     }
6982     return false;
6983   }
6984 
6985   if (N->getOpcode() != ISD::BUILD_VECTOR)
6986     return false;
6987 
6988   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6989     SDNode *Elt = N->getOperand(i).getNode();
6990     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
6991       unsigned EltSize = VT.getScalarSizeInBits();
6992       unsigned HalfSize = EltSize / 2;
6993       if (isSigned) {
6994         if (!isIntN(HalfSize, C->getSExtValue()))
6995           return false;
6996       } else {
6997         if (!isUIntN(HalfSize, C->getZExtValue()))
6998           return false;
6999       }
7000       continue;
7001     }
7002     return false;
7003   }
7004 
7005   return true;
7006 }
7007 
7008 /// isSignExtended - Check if a node is a vector value that is sign-extended
7009 /// or a constant BUILD_VECTOR with sign-extended elements.
7010 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7011   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7012     return true;
7013   if (isExtendedBUILD_VECTOR(N, DAG, true))
7014     return true;
7015   return false;
7016 }
7017 
7018 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7019 /// or a constant BUILD_VECTOR with zero-extended elements.
7020 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7021   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7022     return true;
7023   if (isExtendedBUILD_VECTOR(N, DAG, false))
7024     return true;
7025   return false;
7026 }
7027 
7028 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7029   if (OrigVT.getSizeInBits() >= 64)
7030     return OrigVT;
7031 
7032   assert(OrigVT.isSimple() && "Expecting a simple value type");
7033 
7034   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7035   switch (OrigSimpleTy) {
7036   default: llvm_unreachable("Unexpected Vector Type");
7037   case MVT::v2i8:
7038   case MVT::v2i16:
7039      return MVT::v2i32;
7040   case MVT::v4i8:
7041     return  MVT::v4i16;
7042   }
7043 }
7044 
7045 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7046 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7047 /// We insert the required extension here to get the vector to fill a D register.
7048 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7049                                             const EVT &OrigTy,
7050                                             const EVT &ExtTy,
7051                                             unsigned ExtOpcode) {
7052   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7053   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7054   // 64-bits we need to insert a new extension so that it will be 64-bits.
7055   assert(ExtTy.is128BitVector() && "Unexpected extension size");
7056   if (OrigTy.getSizeInBits() >= 64)
7057     return N;
7058 
7059   // Must extend size to at least 64 bits to be used as an operand for VMULL.
7060   EVT NewVT = getExtensionTo64Bits(OrigTy);
7061 
7062   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7063 }
7064 
7065 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7066 /// does not do any sign/zero extension. If the original vector is less
7067 /// than 64 bits, an appropriate extension will be added after the load to
7068 /// reach a total size of 64 bits. We have to add the extension separately
7069 /// because ARM does not have a sign/zero extending load for vectors.
7070 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7071   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7072 
7073   // The load already has the right type.
7074   if (ExtendedTy == LD->getMemoryVT())
7075     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7076                        LD->getBasePtr(), LD->getPointerInfo(),
7077                        LD->getAlignment(), LD->getMemOperand()->getFlags());
7078 
7079   // We need to create a zextload/sextload. We cannot just create a load
7080   // followed by a zext/zext node because LowerMUL is also run during normal
7081   // operation legalization where we can't create illegal types.
7082   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7083                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7084                         LD->getMemoryVT(), LD->getAlignment(),
7085                         LD->getMemOperand()->getFlags());
7086 }
7087 
7088 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7089 /// extending load, or BUILD_VECTOR with extended elements, return the
7090 /// unextended value. The unextended vector should be 64 bits so that it can
7091 /// be used as an operand to a VMULL instruction. If the original vector size
7092 /// before extension is less than 64 bits we add a an extension to resize
7093 /// the vector to 64 bits.
7094 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7095   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7096     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7097                                         N->getOperand(0)->getValueType(0),
7098                                         N->getValueType(0),
7099                                         N->getOpcode());
7100 
7101   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7102     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7103            "Expected extending load");
7104 
7105     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7106     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7107     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7108     SDValue extLoad =
7109         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7110     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7111 
7112     return newLoad;
7113   }
7114 
7115   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7116   // have been legalized as a BITCAST from v4i32.
7117   if (N->getOpcode() == ISD::BITCAST) {
7118     SDNode *BVN = N->getOperand(0).getNode();
7119     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7120            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7121     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7122     return DAG.getBuildVector(
7123         MVT::v2i32, SDLoc(N),
7124         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7125   }
7126   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7127   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7128   EVT VT = N->getValueType(0);
7129   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7130   unsigned NumElts = VT.getVectorNumElements();
7131   MVT TruncVT = MVT::getIntegerVT(EltSize);
7132   SmallVector<SDValue, 8> Ops;
7133   SDLoc dl(N);
7134   for (unsigned i = 0; i != NumElts; ++i) {
7135     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7136     const APInt &CInt = C->getAPIntValue();
7137     // Element types smaller than 32 bits are not legal, so use i32 elements.
7138     // The values are implicitly truncated so sext vs. zext doesn't matter.
7139     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7140   }
7141   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7142 }
7143 
7144 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7145   unsigned Opcode = N->getOpcode();
7146   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7147     SDNode *N0 = N->getOperand(0).getNode();
7148     SDNode *N1 = N->getOperand(1).getNode();
7149     return N0->hasOneUse() && N1->hasOneUse() &&
7150       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7151   }
7152   return false;
7153 }
7154 
7155 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7156   unsigned Opcode = N->getOpcode();
7157   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7158     SDNode *N0 = N->getOperand(0).getNode();
7159     SDNode *N1 = N->getOperand(1).getNode();
7160     return N0->hasOneUse() && N1->hasOneUse() &&
7161       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7162   }
7163   return false;
7164 }
7165 
7166 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7167   // Multiplications are only custom-lowered for 128-bit vectors so that
7168   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7169   EVT VT = Op.getValueType();
7170   assert(VT.is128BitVector() && VT.isInteger() &&
7171          "unexpected type for custom-lowering ISD::MUL");
7172   SDNode *N0 = Op.getOperand(0).getNode();
7173   SDNode *N1 = Op.getOperand(1).getNode();
7174   unsigned NewOpc = 0;
7175   bool isMLA = false;
7176   bool isN0SExt = isSignExtended(N0, DAG);
7177   bool isN1SExt = isSignExtended(N1, DAG);
7178   if (isN0SExt && isN1SExt)
7179     NewOpc = ARMISD::VMULLs;
7180   else {
7181     bool isN0ZExt = isZeroExtended(N0, DAG);
7182     bool isN1ZExt = isZeroExtended(N1, DAG);
7183     if (isN0ZExt && isN1ZExt)
7184       NewOpc = ARMISD::VMULLu;
7185     else if (isN1SExt || isN1ZExt) {
7186       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7187       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7188       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7189         NewOpc = ARMISD::VMULLs;
7190         isMLA = true;
7191       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7192         NewOpc = ARMISD::VMULLu;
7193         isMLA = true;
7194       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7195         std::swap(N0, N1);
7196         NewOpc = ARMISD::VMULLu;
7197         isMLA = true;
7198       }
7199     }
7200 
7201     if (!NewOpc) {
7202       if (VT == MVT::v2i64)
7203         // Fall through to expand this.  It is not legal.
7204         return SDValue();
7205       else
7206         // Other vector multiplications are legal.
7207         return Op;
7208     }
7209   }
7210 
7211   // Legalize to a VMULL instruction.
7212   SDLoc DL(Op);
7213   SDValue Op0;
7214   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7215   if (!isMLA) {
7216     Op0 = SkipExtensionForVMULL(N0, DAG);
7217     assert(Op0.getValueType().is64BitVector() &&
7218            Op1.getValueType().is64BitVector() &&
7219            "unexpected types for extended operands to VMULL");
7220     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7221   }
7222 
7223   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7224   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7225   //   vmull q0, d4, d6
7226   //   vmlal q0, d5, d6
7227   // is faster than
7228   //   vaddl q0, d4, d5
7229   //   vmovl q1, d6
7230   //   vmul  q0, q0, q1
7231   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7232   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7233   EVT Op1VT = Op1.getValueType();
7234   return DAG.getNode(N0->getOpcode(), DL, VT,
7235                      DAG.getNode(NewOpc, DL, VT,
7236                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7237                      DAG.getNode(NewOpc, DL, VT,
7238                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7239 }
7240 
7241 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7242                               SelectionDAG &DAG) {
7243   // TODO: Should this propagate fast-math-flags?
7244 
7245   // Convert to float
7246   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7247   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7248   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7249   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7250   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7251   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7252   // Get reciprocal estimate.
7253   // float4 recip = vrecpeq_f32(yf);
7254   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7255                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7256                    Y);
7257   // Because char has a smaller range than uchar, we can actually get away
7258   // without any newton steps.  This requires that we use a weird bias
7259   // of 0xb000, however (again, this has been exhaustively tested).
7260   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7261   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7262   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7263   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7264   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7265   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7266   // Convert back to short.
7267   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7268   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7269   return X;
7270 }
7271 
7272 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7273                                SelectionDAG &DAG) {
7274   // TODO: Should this propagate fast-math-flags?
7275 
7276   SDValue N2;
7277   // Convert to float.
7278   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7279   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7280   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7281   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7282   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7283   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7284 
7285   // Use reciprocal estimate and one refinement step.
7286   // float4 recip = vrecpeq_f32(yf);
7287   // recip *= vrecpsq_f32(yf, recip);
7288   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7289                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7290                    N1);
7291   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7292                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7293                    N1, N2);
7294   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7295   // Because short has a smaller range than ushort, we can actually get away
7296   // with only a single newton step.  This requires that we use a weird bias
7297   // of 89, however (again, this has been exhaustively tested).
7298   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7299   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7300   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7301   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7302   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7303   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7304   // Convert back to integer and return.
7305   // return vmovn_s32(vcvt_s32_f32(result));
7306   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7307   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7308   return N0;
7309 }
7310 
7311 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7312   EVT VT = Op.getValueType();
7313   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7314          "unexpected type for custom-lowering ISD::SDIV");
7315 
7316   SDLoc dl(Op);
7317   SDValue N0 = Op.getOperand(0);
7318   SDValue N1 = Op.getOperand(1);
7319   SDValue N2, N3;
7320 
7321   if (VT == MVT::v8i8) {
7322     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7323     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7324 
7325     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7326                      DAG.getIntPtrConstant(4, dl));
7327     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7328                      DAG.getIntPtrConstant(4, dl));
7329     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7330                      DAG.getIntPtrConstant(0, dl));
7331     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7332                      DAG.getIntPtrConstant(0, dl));
7333 
7334     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7335     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7336 
7337     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7338     N0 = LowerCONCAT_VECTORS(N0, DAG);
7339 
7340     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7341     return N0;
7342   }
7343   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7344 }
7345 
7346 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7347   // TODO: Should this propagate fast-math-flags?
7348   EVT VT = Op.getValueType();
7349   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7350          "unexpected type for custom-lowering ISD::UDIV");
7351 
7352   SDLoc dl(Op);
7353   SDValue N0 = Op.getOperand(0);
7354   SDValue N1 = Op.getOperand(1);
7355   SDValue N2, N3;
7356 
7357   if (VT == MVT::v8i8) {
7358     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7359     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7360 
7361     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7362                      DAG.getIntPtrConstant(4, dl));
7363     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7364                      DAG.getIntPtrConstant(4, dl));
7365     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7366                      DAG.getIntPtrConstant(0, dl));
7367     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7368                      DAG.getIntPtrConstant(0, dl));
7369 
7370     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7371     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7372 
7373     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7374     N0 = LowerCONCAT_VECTORS(N0, DAG);
7375 
7376     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7377                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7378                                      MVT::i32),
7379                      N0);
7380     return N0;
7381   }
7382 
7383   // v4i16 sdiv ... Convert to float.
7384   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7385   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7386   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7387   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7388   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7389   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7390 
7391   // Use reciprocal estimate and two refinement steps.
7392   // float4 recip = vrecpeq_f32(yf);
7393   // recip *= vrecpsq_f32(yf, recip);
7394   // recip *= vrecpsq_f32(yf, recip);
7395   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7396                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7397                    BN1);
7398   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7399                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7400                    BN1, N2);
7401   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7402   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7403                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7404                    BN1, N2);
7405   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7406   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7407   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7408   // and that it will never cause us to return an answer too large).
7409   // float4 result = as_float4(as_int4(xf*recip) + 2);
7410   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7411   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7412   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7413   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7414   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7415   // Convert back to integer and return.
7416   // return vmovn_u32(vcvt_s32_f32(result));
7417   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7418   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7419   return N0;
7420 }
7421 
7422 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7423   EVT VT = Op.getNode()->getValueType(0);
7424   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7425 
7426   unsigned Opc;
7427   bool ExtraOp = false;
7428   switch (Op.getOpcode()) {
7429   default: llvm_unreachable("Invalid code");
7430   case ISD::ADDC: Opc = ARMISD::ADDC; break;
7431   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7432   case ISD::SUBC: Opc = ARMISD::SUBC; break;
7433   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7434   }
7435 
7436   if (!ExtraOp)
7437     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7438                        Op.getOperand(1));
7439   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7440                      Op.getOperand(1), Op.getOperand(2));
7441 }
7442 
7443 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
7444   SDNode *N = Op.getNode();
7445   EVT VT = N->getValueType(0);
7446   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7447 
7448   SDValue Carry = Op.getOperand(2);
7449   EVT CarryVT = Carry.getValueType();
7450 
7451   SDLoc DL(Op);
7452 
7453   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
7454 
7455   SDValue Result;
7456   if (Op.getOpcode() == ISD::ADDCARRY) {
7457     // This converts the boolean value carry into the carry flag.
7458     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7459 
7460     // Do the addition proper using the carry flag we wanted.
7461     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
7462                          Op.getOperand(1), Carry.getValue(1));
7463 
7464     // Now convert the carry flag into a boolean value.
7465     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7466   } else {
7467     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
7468     // have to invert the carry first.
7469     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7470                         DAG.getConstant(1, DL, MVT::i32), Carry);
7471     // This converts the boolean value carry into the carry flag.
7472     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7473 
7474     // Do the subtraction proper using the carry flag we wanted.
7475     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
7476                          Op.getOperand(1), Carry.getValue(1));
7477 
7478     // Now convert the carry flag into a boolean value.
7479     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7480     // But the carry returned by ARMISD::SUBE is not a borrow as expected
7481     // by ISD::SUBCARRY, so compute 1 - C.
7482     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7483                         DAG.getConstant(1, DL, MVT::i32), Carry);
7484   }
7485 
7486   // Return both values.
7487   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
7488 }
7489 
7490 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7491   assert(Subtarget->isTargetDarwin());
7492 
7493   // For iOS, we want to call an alternative entry point: __sincos_stret,
7494   // return values are passed via sret.
7495   SDLoc dl(Op);
7496   SDValue Arg = Op.getOperand(0);
7497   EVT ArgVT = Arg.getValueType();
7498   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7499   auto PtrVT = getPointerTy(DAG.getDataLayout());
7500 
7501   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7502   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7503 
7504   // Pair of floats / doubles used to pass the result.
7505   Type *RetTy = StructType::get(ArgTy, ArgTy);
7506   auto &DL = DAG.getDataLayout();
7507 
7508   ArgListTy Args;
7509   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7510   SDValue SRet;
7511   if (ShouldUseSRet) {
7512     // Create stack object for sret.
7513     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7514     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7515     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7516     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7517 
7518     ArgListEntry Entry;
7519     Entry.Node = SRet;
7520     Entry.Ty = RetTy->getPointerTo();
7521     Entry.IsSExt = false;
7522     Entry.IsZExt = false;
7523     Entry.IsSRet = true;
7524     Args.push_back(Entry);
7525     RetTy = Type::getVoidTy(*DAG.getContext());
7526   }
7527 
7528   ArgListEntry Entry;
7529   Entry.Node = Arg;
7530   Entry.Ty = ArgTy;
7531   Entry.IsSExt = false;
7532   Entry.IsZExt = false;
7533   Args.push_back(Entry);
7534 
7535   const char *LibcallName =
7536       (ArgVT == MVT::f64) ? "__sincos_stret" : "__sincosf_stret";
7537   RTLIB::Libcall LC =
7538       (ArgVT == MVT::f64) ? RTLIB::SINCOS_F64 : RTLIB::SINCOS_F32;
7539   CallingConv::ID CC = getLibcallCallingConv(LC);
7540   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7541 
7542   TargetLowering::CallLoweringInfo CLI(DAG);
7543   CLI.setDebugLoc(dl)
7544       .setChain(DAG.getEntryNode())
7545       .setCallee(CC, RetTy, Callee, std::move(Args))
7546       .setDiscardResult(ShouldUseSRet);
7547   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7548 
7549   if (!ShouldUseSRet)
7550     return CallResult.first;
7551 
7552   SDValue LoadSin =
7553       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7554 
7555   // Address of cos field.
7556   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7557                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7558   SDValue LoadCos =
7559       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7560 
7561   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7562   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7563                      LoadSin.getValue(0), LoadCos.getValue(0));
7564 }
7565 
7566 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7567                                                   bool Signed,
7568                                                   SDValue &Chain) const {
7569   EVT VT = Op.getValueType();
7570   assert((VT == MVT::i32 || VT == MVT::i64) &&
7571          "unexpected type for custom lowering DIV");
7572   SDLoc dl(Op);
7573 
7574   const auto &DL = DAG.getDataLayout();
7575   const auto &TLI = DAG.getTargetLoweringInfo();
7576 
7577   const char *Name = nullptr;
7578   if (Signed)
7579     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7580   else
7581     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7582 
7583   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7584 
7585   ARMTargetLowering::ArgListTy Args;
7586 
7587   for (auto AI : {1, 0}) {
7588     ArgListEntry Arg;
7589     Arg.Node = Op.getOperand(AI);
7590     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7591     Args.push_back(Arg);
7592   }
7593 
7594   CallLoweringInfo CLI(DAG);
7595   CLI.setDebugLoc(dl)
7596     .setChain(Chain)
7597     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7598                ES, std::move(Args));
7599 
7600   return LowerCallTo(CLI).first;
7601 }
7602 
7603 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7604                                             bool Signed) const {
7605   assert(Op.getValueType() == MVT::i32 &&
7606          "unexpected type for custom lowering DIV");
7607   SDLoc dl(Op);
7608 
7609   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7610                                DAG.getEntryNode(), Op.getOperand(1));
7611 
7612   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7613 }
7614 
7615 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7616   SDLoc DL(N);
7617   SDValue Op = N->getOperand(1);
7618   if (N->getValueType(0) == MVT::i32)
7619     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7620   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7621                            DAG.getConstant(0, DL, MVT::i32));
7622   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7623                            DAG.getConstant(1, DL, MVT::i32));
7624   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7625                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7626 }
7627 
7628 void ARMTargetLowering::ExpandDIV_Windows(
7629     SDValue Op, SelectionDAG &DAG, bool Signed,
7630     SmallVectorImpl<SDValue> &Results) const {
7631   const auto &DL = DAG.getDataLayout();
7632   const auto &TLI = DAG.getTargetLoweringInfo();
7633 
7634   assert(Op.getValueType() == MVT::i64 &&
7635          "unexpected type for custom lowering DIV");
7636   SDLoc dl(Op);
7637 
7638   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7639 
7640   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7641 
7642   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7643   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7644                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7645   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7646 
7647   Results.push_back(Lower);
7648   Results.push_back(Upper);
7649 }
7650 
7651 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7652   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7653     // Acquire/Release load/store is not legal for targets without a dmb or
7654     // equivalent available.
7655     return SDValue();
7656 
7657   // Monotonic load/store is legal for all targets.
7658   return Op;
7659 }
7660 
7661 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7662                                     SmallVectorImpl<SDValue> &Results,
7663                                     SelectionDAG &DAG,
7664                                     const ARMSubtarget *Subtarget) {
7665   SDLoc DL(N);
7666   // Under Power Management extensions, the cycle-count is:
7667   //    mrc p15, #0, <Rt>, c9, c13, #0
7668   SDValue Ops[] = { N->getOperand(0), // Chain
7669                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7670                     DAG.getConstant(15, DL, MVT::i32),
7671                     DAG.getConstant(0, DL, MVT::i32),
7672                     DAG.getConstant(9, DL, MVT::i32),
7673                     DAG.getConstant(13, DL, MVT::i32),
7674                     DAG.getConstant(0, DL, MVT::i32)
7675   };
7676 
7677   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7678                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7679   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7680                                 DAG.getConstant(0, DL, MVT::i32)));
7681   Results.push_back(Cycles32.getValue(1));
7682 }
7683 
7684 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7685   SDLoc dl(V.getNode());
7686   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7687   SDValue VHi = DAG.getAnyExtOrTrunc(
7688       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7689       dl, MVT::i32);
7690   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7691   if (isBigEndian)
7692     std::swap (VLo, VHi);
7693   SDValue RegClass =
7694       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7695   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7696   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7697   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7698   return SDValue(
7699       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7700 }
7701 
7702 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7703                                        SmallVectorImpl<SDValue> & Results,
7704                                        SelectionDAG &DAG) {
7705   assert(N->getValueType(0) == MVT::i64 &&
7706          "AtomicCmpSwap on types less than 64 should be legal");
7707   SDValue Ops[] = {N->getOperand(1),
7708                    createGPRPairNode(DAG, N->getOperand(2)),
7709                    createGPRPairNode(DAG, N->getOperand(3)),
7710                    N->getOperand(0)};
7711   SDNode *CmpSwap = DAG.getMachineNode(
7712       ARM::CMP_SWAP_64, SDLoc(N),
7713       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7714 
7715   MachineFunction &MF = DAG.getMachineFunction();
7716   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7717   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7718   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7719 
7720   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7721 
7722   Results.push_back(
7723       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
7724                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7725   Results.push_back(
7726       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
7727                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7728   Results.push_back(SDValue(CmpSwap, 2));
7729 }
7730 
7731 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7732                           SelectionDAG &DAG) {
7733   const auto &TLI = DAG.getTargetLoweringInfo();
7734 
7735   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7736          "Custom lowering is MSVCRT specific!");
7737 
7738   SDLoc dl(Op);
7739   SDValue Val = Op.getOperand(0);
7740   MVT Ty = Val->getSimpleValueType(0);
7741   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7742   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7743                                          TLI.getPointerTy(DAG.getDataLayout()));
7744 
7745   TargetLowering::ArgListTy Args;
7746   TargetLowering::ArgListEntry Entry;
7747 
7748   Entry.Node = Val;
7749   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7750   Entry.IsZExt = true;
7751   Args.push_back(Entry);
7752 
7753   Entry.Node = Exponent;
7754   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7755   Entry.IsZExt = true;
7756   Args.push_back(Entry);
7757 
7758   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7759 
7760   // In the in-chain to the call is the entry node  If we are emitting a
7761   // tailcall, the chain will be mutated if the node has a non-entry input
7762   // chain.
7763   SDValue InChain = DAG.getEntryNode();
7764   SDValue TCChain = InChain;
7765 
7766   const auto *F = DAG.getMachineFunction().getFunction();
7767   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
7768               F->getReturnType() == LCRTy;
7769   if (IsTC)
7770     InChain = TCChain;
7771 
7772   TargetLowering::CallLoweringInfo CLI(DAG);
7773   CLI.setDebugLoc(dl)
7774       .setChain(InChain)
7775       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
7776       .setTailCall(IsTC);
7777   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
7778 
7779   // Return the chain (the DAG root) if it is a tail call
7780   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
7781 }
7782 
7783 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7784   switch (Op.getOpcode()) {
7785   default: llvm_unreachable("Don't know how to custom lower this!");
7786   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7787   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7788   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7789   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7790   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7791   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7792   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7793   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7794   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7795   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7796   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7797   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7798   case ISD::SINT_TO_FP:
7799   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7800   case ISD::FP_TO_SINT:
7801   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7802   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7803   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7804   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7805   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7806   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7807   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7808   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7809                                                                Subtarget);
7810   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
7811   case ISD::SHL:
7812   case ISD::SRL:
7813   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
7814   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
7815   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
7816   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
7817   case ISD::SRL_PARTS:
7818   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7819   case ISD::CTTZ:
7820   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7821   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7822   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7823   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
7824   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7825   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7826   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7827   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7828   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7829   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7830   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7831   case ISD::MUL:           return LowerMUL(Op, DAG);
7832   case ISD::SDIV:
7833     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7834       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7835     return LowerSDIV(Op, DAG);
7836   case ISD::UDIV:
7837     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7838       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7839     return LowerUDIV(Op, DAG);
7840   case ISD::ADDC:
7841   case ISD::ADDE:
7842   case ISD::SUBC:
7843   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7844   case ISD::ADDCARRY:
7845   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
7846   case ISD::SADDO:
7847   case ISD::SSUBO:
7848     return LowerSignedALUO(Op, DAG);
7849   case ISD::UADDO:
7850   case ISD::USUBO:
7851     return LowerUnsignedALUO(Op, DAG);
7852   case ISD::ATOMIC_LOAD:
7853   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7854   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7855   case ISD::SDIVREM:
7856   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7857   case ISD::DYNAMIC_STACKALLOC:
7858     if (Subtarget->getTargetTriple().isWindowsItaniumEnvironment())
7859       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7860     llvm_unreachable("Don't know how to custom lower this!");
7861   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7862   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7863   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
7864   case ARMISD::WIN__DBZCHK: return SDValue();
7865   }
7866 }
7867 
7868 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
7869                                  SelectionDAG &DAG) {
7870   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7871   unsigned Opc = 0;
7872   if (IntNo == Intrinsic::arm_smlald)
7873     Opc = ARMISD::SMLALD;
7874   else if (IntNo == Intrinsic::arm_smlaldx)
7875     Opc = ARMISD::SMLALDX;
7876   else if (IntNo == Intrinsic::arm_smlsld)
7877     Opc = ARMISD::SMLSLD;
7878   else if (IntNo == Intrinsic::arm_smlsldx)
7879     Opc = ARMISD::SMLSLDX;
7880   else
7881     return;
7882 
7883   SDLoc dl(N);
7884   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7885                            N->getOperand(3),
7886                            DAG.getConstant(0, dl, MVT::i32));
7887   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7888                            N->getOperand(3),
7889                            DAG.getConstant(1, dl, MVT::i32));
7890 
7891   SDValue LongMul = DAG.getNode(Opc, dl,
7892                                 DAG.getVTList(MVT::i32, MVT::i32),
7893                                 N->getOperand(1), N->getOperand(2),
7894                                 Lo, Hi);
7895   Results.push_back(LongMul.getValue(0));
7896   Results.push_back(LongMul.getValue(1));
7897 }
7898 
7899 /// ReplaceNodeResults - Replace the results of node with an illegal result
7900 /// type with new values built out of custom code.
7901 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
7902                                            SmallVectorImpl<SDValue> &Results,
7903                                            SelectionDAG &DAG) const {
7904   SDValue Res;
7905   switch (N->getOpcode()) {
7906   default:
7907     llvm_unreachable("Don't know how to custom expand this!");
7908   case ISD::READ_REGISTER:
7909     ExpandREAD_REGISTER(N, Results, DAG);
7910     break;
7911   case ISD::BITCAST:
7912     Res = ExpandBITCAST(N, DAG);
7913     break;
7914   case ISD::SRL:
7915   case ISD::SRA:
7916     Res = Expand64BitShift(N, DAG, Subtarget);
7917     break;
7918   case ISD::SREM:
7919   case ISD::UREM:
7920     Res = LowerREM(N, DAG);
7921     break;
7922   case ISD::SDIVREM:
7923   case ISD::UDIVREM:
7924     Res = LowerDivRem(SDValue(N, 0), DAG);
7925     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
7926     Results.push_back(Res.getValue(0));
7927     Results.push_back(Res.getValue(1));
7928     return;
7929   case ISD::READCYCLECOUNTER:
7930     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
7931     return;
7932   case ISD::UDIV:
7933   case ISD::SDIV:
7934     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
7935     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
7936                              Results);
7937   case ISD::ATOMIC_CMP_SWAP:
7938     ReplaceCMP_SWAP_64Results(N, Results, DAG);
7939     return;
7940   case ISD::INTRINSIC_WO_CHAIN:
7941     return ReplaceLongIntrinsic(N, Results, DAG);
7942   }
7943   if (Res.getNode())
7944     Results.push_back(Res);
7945 }
7946 
7947 //===----------------------------------------------------------------------===//
7948 //                           ARM Scheduler Hooks
7949 //===----------------------------------------------------------------------===//
7950 
7951 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
7952 /// registers the function context.
7953 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
7954                                                MachineBasicBlock *MBB,
7955                                                MachineBasicBlock *DispatchBB,
7956                                                int FI) const {
7957   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
7958          "ROPI/RWPI not currently supported with SjLj");
7959   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
7960   DebugLoc dl = MI.getDebugLoc();
7961   MachineFunction *MF = MBB->getParent();
7962   MachineRegisterInfo *MRI = &MF->getRegInfo();
7963   MachineConstantPool *MCP = MF->getConstantPool();
7964   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
7965   const Function *F = MF->getFunction();
7966 
7967   bool isThumb = Subtarget->isThumb();
7968   bool isThumb2 = Subtarget->isThumb2();
7969 
7970   unsigned PCLabelId = AFI->createPICLabelUId();
7971   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
7972   ARMConstantPoolValue *CPV =
7973     ARMConstantPoolMBB::Create(F->getContext(), DispatchBB, PCLabelId, PCAdj);
7974   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
7975 
7976   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
7977                                            : &ARM::GPRRegClass;
7978 
7979   // Grab constant pool and fixed stack memory operands.
7980   MachineMemOperand *CPMMO =
7981       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
7982                                MachineMemOperand::MOLoad, 4, 4);
7983 
7984   MachineMemOperand *FIMMOSt =
7985       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
7986                                MachineMemOperand::MOStore, 4, 4);
7987 
7988   // Load the address of the dispatch MBB into the jump buffer.
7989   if (isThumb2) {
7990     // Incoming value: jbuf
7991     //   ldr.n  r5, LCPI1_1
7992     //   orr    r5, r5, #1
7993     //   add    r5, pc
7994     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
7995     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
7996     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
7997         .addConstantPoolIndex(CPI)
7998         .addMemOperand(CPMMO)
7999         .add(predOps(ARMCC::AL));
8000     // Set the low bit because of thumb mode.
8001     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8002     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8003         .addReg(NewVReg1, RegState::Kill)
8004         .addImm(0x01)
8005         .add(predOps(ARMCC::AL))
8006         .add(condCodeOp());
8007     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8008     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8009       .addReg(NewVReg2, RegState::Kill)
8010       .addImm(PCLabelId);
8011     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8012         .addReg(NewVReg3, RegState::Kill)
8013         .addFrameIndex(FI)
8014         .addImm(36) // &jbuf[1] :: pc
8015         .addMemOperand(FIMMOSt)
8016         .add(predOps(ARMCC::AL));
8017   } else if (isThumb) {
8018     // Incoming value: jbuf
8019     //   ldr.n  r1, LCPI1_4
8020     //   add    r1, pc
8021     //   mov    r2, #1
8022     //   orrs   r1, r2
8023     //   add    r2, $jbuf, #+4 ; &jbuf[1]
8024     //   str    r1, [r2]
8025     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8026     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8027         .addConstantPoolIndex(CPI)
8028         .addMemOperand(CPMMO)
8029         .add(predOps(ARMCC::AL));
8030     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8031     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8032       .addReg(NewVReg1, RegState::Kill)
8033       .addImm(PCLabelId);
8034     // Set the low bit because of thumb mode.
8035     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8036     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8037         .addReg(ARM::CPSR, RegState::Define)
8038         .addImm(1)
8039         .add(predOps(ARMCC::AL));
8040     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8041     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8042         .addReg(ARM::CPSR, RegState::Define)
8043         .addReg(NewVReg2, RegState::Kill)
8044         .addReg(NewVReg3, RegState::Kill)
8045         .add(predOps(ARMCC::AL));
8046     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8047     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8048             .addFrameIndex(FI)
8049             .addImm(36); // &jbuf[1] :: pc
8050     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8051         .addReg(NewVReg4, RegState::Kill)
8052         .addReg(NewVReg5, RegState::Kill)
8053         .addImm(0)
8054         .addMemOperand(FIMMOSt)
8055         .add(predOps(ARMCC::AL));
8056   } else {
8057     // Incoming value: jbuf
8058     //   ldr  r1, LCPI1_1
8059     //   add  r1, pc, r1
8060     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
8061     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8062     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
8063         .addConstantPoolIndex(CPI)
8064         .addImm(0)
8065         .addMemOperand(CPMMO)
8066         .add(predOps(ARMCC::AL));
8067     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8068     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
8069         .addReg(NewVReg1, RegState::Kill)
8070         .addImm(PCLabelId)
8071         .add(predOps(ARMCC::AL));
8072     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
8073         .addReg(NewVReg2, RegState::Kill)
8074         .addFrameIndex(FI)
8075         .addImm(36) // &jbuf[1] :: pc
8076         .addMemOperand(FIMMOSt)
8077         .add(predOps(ARMCC::AL));
8078   }
8079 }
8080 
8081 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
8082                                               MachineBasicBlock *MBB) const {
8083   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8084   DebugLoc dl = MI.getDebugLoc();
8085   MachineFunction *MF = MBB->getParent();
8086   MachineRegisterInfo *MRI = &MF->getRegInfo();
8087   MachineFrameInfo &MFI = MF->getFrameInfo();
8088   int FI = MFI.getFunctionContextIndex();
8089 
8090   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
8091                                                         : &ARM::GPRnopcRegClass;
8092 
8093   // Get a mapping of the call site numbers to all of the landing pads they're
8094   // associated with.
8095   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
8096   unsigned MaxCSNum = 0;
8097   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8098        ++BB) {
8099     if (!BB->isEHPad()) continue;
8100 
8101     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8102     // pad.
8103     for (MachineBasicBlock::iterator
8104            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8105       if (!II->isEHLabel()) continue;
8106 
8107       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8108       if (!MF->hasCallSiteLandingPad(Sym)) continue;
8109 
8110       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8111       for (SmallVectorImpl<unsigned>::iterator
8112              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8113            CSI != CSE; ++CSI) {
8114         CallSiteNumToLPad[*CSI].push_back(&*BB);
8115         MaxCSNum = std::max(MaxCSNum, *CSI);
8116       }
8117       break;
8118     }
8119   }
8120 
8121   // Get an ordered list of the machine basic blocks for the jump table.
8122   std::vector<MachineBasicBlock*> LPadList;
8123   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8124   LPadList.reserve(CallSiteNumToLPad.size());
8125   for (unsigned I = 1; I <= MaxCSNum; ++I) {
8126     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8127     for (SmallVectorImpl<MachineBasicBlock*>::iterator
8128            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8129       LPadList.push_back(*II);
8130       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8131     }
8132   }
8133 
8134   assert(!LPadList.empty() &&
8135          "No landing pad destinations for the dispatch jump table!");
8136 
8137   // Create the jump table and associated information.
8138   MachineJumpTableInfo *JTI =
8139     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8140   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8141 
8142   // Create the MBBs for the dispatch code.
8143 
8144   // Shove the dispatch's address into the return slot in the function context.
8145   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8146   DispatchBB->setIsEHPad();
8147 
8148   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8149   unsigned trap_opcode;
8150   if (Subtarget->isThumb())
8151     trap_opcode = ARM::tTRAP;
8152   else
8153     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8154 
8155   BuildMI(TrapBB, dl, TII->get(trap_opcode));
8156   DispatchBB->addSuccessor(TrapBB);
8157 
8158   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8159   DispatchBB->addSuccessor(DispContBB);
8160 
8161   // Insert and MBBs.
8162   MF->insert(MF->end(), DispatchBB);
8163   MF->insert(MF->end(), DispContBB);
8164   MF->insert(MF->end(), TrapBB);
8165 
8166   // Insert code into the entry block that creates and registers the function
8167   // context.
8168   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8169 
8170   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8171       MachinePointerInfo::getFixedStack(*MF, FI),
8172       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8173 
8174   MachineInstrBuilder MIB;
8175   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8176 
8177   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8178   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8179 
8180   // Add a register mask with no preserved registers.  This results in all
8181   // registers being marked as clobbered. This can't work if the dispatch block
8182   // is in a Thumb1 function and is linked with ARM code which uses the FP
8183   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8184   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8185 
8186   bool IsPositionIndependent = isPositionIndependent();
8187   unsigned NumLPads = LPadList.size();
8188   if (Subtarget->isThumb2()) {
8189     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8190     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8191         .addFrameIndex(FI)
8192         .addImm(4)
8193         .addMemOperand(FIMMOLd)
8194         .add(predOps(ARMCC::AL));
8195 
8196     if (NumLPads < 256) {
8197       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8198           .addReg(NewVReg1)
8199           .addImm(LPadList.size())
8200           .add(predOps(ARMCC::AL));
8201     } else {
8202       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8203       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8204           .addImm(NumLPads & 0xFFFF)
8205           .add(predOps(ARMCC::AL));
8206 
8207       unsigned VReg2 = VReg1;
8208       if ((NumLPads & 0xFFFF0000) != 0) {
8209         VReg2 = MRI->createVirtualRegister(TRC);
8210         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8211             .addReg(VReg1)
8212             .addImm(NumLPads >> 16)
8213             .add(predOps(ARMCC::AL));
8214       }
8215 
8216       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8217           .addReg(NewVReg1)
8218           .addReg(VReg2)
8219           .add(predOps(ARMCC::AL));
8220     }
8221 
8222     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8223       .addMBB(TrapBB)
8224       .addImm(ARMCC::HI)
8225       .addReg(ARM::CPSR);
8226 
8227     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8228     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8229         .addJumpTableIndex(MJTI)
8230         .add(predOps(ARMCC::AL));
8231 
8232     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8233     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8234         .addReg(NewVReg3, RegState::Kill)
8235         .addReg(NewVReg1)
8236         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8237         .add(predOps(ARMCC::AL))
8238         .add(condCodeOp());
8239 
8240     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8241       .addReg(NewVReg4, RegState::Kill)
8242       .addReg(NewVReg1)
8243       .addJumpTableIndex(MJTI);
8244   } else if (Subtarget->isThumb()) {
8245     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8246     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8247         .addFrameIndex(FI)
8248         .addImm(1)
8249         .addMemOperand(FIMMOLd)
8250         .add(predOps(ARMCC::AL));
8251 
8252     if (NumLPads < 256) {
8253       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8254           .addReg(NewVReg1)
8255           .addImm(NumLPads)
8256           .add(predOps(ARMCC::AL));
8257     } else {
8258       MachineConstantPool *ConstantPool = MF->getConstantPool();
8259       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8260       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8261 
8262       // MachineConstantPool wants an explicit alignment.
8263       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8264       if (Align == 0)
8265         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8266       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8267 
8268       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8269       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8270           .addReg(VReg1, RegState::Define)
8271           .addConstantPoolIndex(Idx)
8272           .add(predOps(ARMCC::AL));
8273       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8274           .addReg(NewVReg1)
8275           .addReg(VReg1)
8276           .add(predOps(ARMCC::AL));
8277     }
8278 
8279     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8280       .addMBB(TrapBB)
8281       .addImm(ARMCC::HI)
8282       .addReg(ARM::CPSR);
8283 
8284     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8285     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8286         .addReg(ARM::CPSR, RegState::Define)
8287         .addReg(NewVReg1)
8288         .addImm(2)
8289         .add(predOps(ARMCC::AL));
8290 
8291     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8292     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8293         .addJumpTableIndex(MJTI)
8294         .add(predOps(ARMCC::AL));
8295 
8296     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8297     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8298         .addReg(ARM::CPSR, RegState::Define)
8299         .addReg(NewVReg2, RegState::Kill)
8300         .addReg(NewVReg3)
8301         .add(predOps(ARMCC::AL));
8302 
8303     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8304         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8305 
8306     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8307     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8308         .addReg(NewVReg4, RegState::Kill)
8309         .addImm(0)
8310         .addMemOperand(JTMMOLd)
8311         .add(predOps(ARMCC::AL));
8312 
8313     unsigned NewVReg6 = NewVReg5;
8314     if (IsPositionIndependent) {
8315       NewVReg6 = MRI->createVirtualRegister(TRC);
8316       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8317           .addReg(ARM::CPSR, RegState::Define)
8318           .addReg(NewVReg5, RegState::Kill)
8319           .addReg(NewVReg3)
8320           .add(predOps(ARMCC::AL));
8321     }
8322 
8323     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8324       .addReg(NewVReg6, RegState::Kill)
8325       .addJumpTableIndex(MJTI);
8326   } else {
8327     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8328     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8329         .addFrameIndex(FI)
8330         .addImm(4)
8331         .addMemOperand(FIMMOLd)
8332         .add(predOps(ARMCC::AL));
8333 
8334     if (NumLPads < 256) {
8335       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8336           .addReg(NewVReg1)
8337           .addImm(NumLPads)
8338           .add(predOps(ARMCC::AL));
8339     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8340       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8341       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8342           .addImm(NumLPads & 0xFFFF)
8343           .add(predOps(ARMCC::AL));
8344 
8345       unsigned VReg2 = VReg1;
8346       if ((NumLPads & 0xFFFF0000) != 0) {
8347         VReg2 = MRI->createVirtualRegister(TRC);
8348         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8349             .addReg(VReg1)
8350             .addImm(NumLPads >> 16)
8351             .add(predOps(ARMCC::AL));
8352       }
8353 
8354       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8355           .addReg(NewVReg1)
8356           .addReg(VReg2)
8357           .add(predOps(ARMCC::AL));
8358     } else {
8359       MachineConstantPool *ConstantPool = MF->getConstantPool();
8360       Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8361       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8362 
8363       // MachineConstantPool wants an explicit alignment.
8364       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8365       if (Align == 0)
8366         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8367       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8368 
8369       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8370       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8371           .addReg(VReg1, RegState::Define)
8372           .addConstantPoolIndex(Idx)
8373           .addImm(0)
8374           .add(predOps(ARMCC::AL));
8375       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8376           .addReg(NewVReg1)
8377           .addReg(VReg1, RegState::Kill)
8378           .add(predOps(ARMCC::AL));
8379     }
8380 
8381     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8382       .addMBB(TrapBB)
8383       .addImm(ARMCC::HI)
8384       .addReg(ARM::CPSR);
8385 
8386     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8387     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8388         .addReg(NewVReg1)
8389         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8390         .add(predOps(ARMCC::AL))
8391         .add(condCodeOp());
8392     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8393     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8394         .addJumpTableIndex(MJTI)
8395         .add(predOps(ARMCC::AL));
8396 
8397     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8398         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8399     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8400     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8401         .addReg(NewVReg3, RegState::Kill)
8402         .addReg(NewVReg4)
8403         .addImm(0)
8404         .addMemOperand(JTMMOLd)
8405         .add(predOps(ARMCC::AL));
8406 
8407     if (IsPositionIndependent) {
8408       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8409         .addReg(NewVReg5, RegState::Kill)
8410         .addReg(NewVReg4)
8411         .addJumpTableIndex(MJTI);
8412     } else {
8413       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8414         .addReg(NewVReg5, RegState::Kill)
8415         .addJumpTableIndex(MJTI);
8416     }
8417   }
8418 
8419   // Add the jump table entries as successors to the MBB.
8420   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8421   for (std::vector<MachineBasicBlock*>::iterator
8422          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8423     MachineBasicBlock *CurMBB = *I;
8424     if (SeenMBBs.insert(CurMBB).second)
8425       DispContBB->addSuccessor(CurMBB);
8426   }
8427 
8428   // N.B. the order the invoke BBs are processed in doesn't matter here.
8429   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8430   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8431   for (MachineBasicBlock *BB : InvokeBBs) {
8432 
8433     // Remove the landing pad successor from the invoke block and replace it
8434     // with the new dispatch block.
8435     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8436                                                   BB->succ_end());
8437     while (!Successors.empty()) {
8438       MachineBasicBlock *SMBB = Successors.pop_back_val();
8439       if (SMBB->isEHPad()) {
8440         BB->removeSuccessor(SMBB);
8441         MBBLPads.push_back(SMBB);
8442       }
8443     }
8444 
8445     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8446     BB->normalizeSuccProbs();
8447 
8448     // Find the invoke call and mark all of the callee-saved registers as
8449     // 'implicit defined' so that they're spilled. This prevents code from
8450     // moving instructions to before the EH block, where they will never be
8451     // executed.
8452     for (MachineBasicBlock::reverse_iterator
8453            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8454       if (!II->isCall()) continue;
8455 
8456       DenseMap<unsigned, bool> DefRegs;
8457       for (MachineInstr::mop_iterator
8458              OI = II->operands_begin(), OE = II->operands_end();
8459            OI != OE; ++OI) {
8460         if (!OI->isReg()) continue;
8461         DefRegs[OI->getReg()] = true;
8462       }
8463 
8464       MachineInstrBuilder MIB(*MF, &*II);
8465 
8466       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8467         unsigned Reg = SavedRegs[i];
8468         if (Subtarget->isThumb2() &&
8469             !ARM::tGPRRegClass.contains(Reg) &&
8470             !ARM::hGPRRegClass.contains(Reg))
8471           continue;
8472         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8473           continue;
8474         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8475           continue;
8476         if (!DefRegs[Reg])
8477           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8478       }
8479 
8480       break;
8481     }
8482   }
8483 
8484   // Mark all former landing pads as non-landing pads. The dispatch is the only
8485   // landing pad now.
8486   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8487          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8488     (*I)->setIsEHPad(false);
8489 
8490   // The instruction is gone now.
8491   MI.eraseFromParent();
8492 }
8493 
8494 static
8495 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8496   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8497        E = MBB->succ_end(); I != E; ++I)
8498     if (*I != Succ)
8499       return *I;
8500   llvm_unreachable("Expecting a BB with two successors!");
8501 }
8502 
8503 /// Return the load opcode for a given load size. If load size >= 8,
8504 /// neon opcode will be returned.
8505 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8506   if (LdSize >= 8)
8507     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8508                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8509   if (IsThumb1)
8510     return LdSize == 4 ? ARM::tLDRi
8511                        : LdSize == 2 ? ARM::tLDRHi
8512                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8513   if (IsThumb2)
8514     return LdSize == 4 ? ARM::t2LDR_POST
8515                        : LdSize == 2 ? ARM::t2LDRH_POST
8516                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8517   return LdSize == 4 ? ARM::LDR_POST_IMM
8518                      : LdSize == 2 ? ARM::LDRH_POST
8519                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8520 }
8521 
8522 /// Return the store opcode for a given store size. If store size >= 8,
8523 /// neon opcode will be returned.
8524 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8525   if (StSize >= 8)
8526     return StSize == 16 ? ARM::VST1q32wb_fixed
8527                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8528   if (IsThumb1)
8529     return StSize == 4 ? ARM::tSTRi
8530                        : StSize == 2 ? ARM::tSTRHi
8531                                      : StSize == 1 ? ARM::tSTRBi : 0;
8532   if (IsThumb2)
8533     return StSize == 4 ? ARM::t2STR_POST
8534                        : StSize == 2 ? ARM::t2STRH_POST
8535                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8536   return StSize == 4 ? ARM::STR_POST_IMM
8537                      : StSize == 2 ? ARM::STRH_POST
8538                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8539 }
8540 
8541 /// Emit a post-increment load operation with given size. The instructions
8542 /// will be added to BB at Pos.
8543 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8544                        const TargetInstrInfo *TII, const DebugLoc &dl,
8545                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8546                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8547   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8548   assert(LdOpc != 0 && "Should have a load opcode");
8549   if (LdSize >= 8) {
8550     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8551         .addReg(AddrOut, RegState::Define)
8552         .addReg(AddrIn)
8553         .addImm(0)
8554         .add(predOps(ARMCC::AL));
8555   } else if (IsThumb1) {
8556     // load + update AddrIn
8557     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8558         .addReg(AddrIn)
8559         .addImm(0)
8560         .add(predOps(ARMCC::AL));
8561     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8562         .add(t1CondCodeOp())
8563         .addReg(AddrIn)
8564         .addImm(LdSize)
8565         .add(predOps(ARMCC::AL));
8566   } else if (IsThumb2) {
8567     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8568         .addReg(AddrOut, RegState::Define)
8569         .addReg(AddrIn)
8570         .addImm(LdSize)
8571         .add(predOps(ARMCC::AL));
8572   } else { // arm
8573     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8574         .addReg(AddrOut, RegState::Define)
8575         .addReg(AddrIn)
8576         .addReg(0)
8577         .addImm(LdSize)
8578         .add(predOps(ARMCC::AL));
8579   }
8580 }
8581 
8582 /// Emit a post-increment store operation with given size. The instructions
8583 /// will be added to BB at Pos.
8584 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8585                        const TargetInstrInfo *TII, const DebugLoc &dl,
8586                        unsigned StSize, unsigned Data, unsigned AddrIn,
8587                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8588   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8589   assert(StOpc != 0 && "Should have a store opcode");
8590   if (StSize >= 8) {
8591     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8592         .addReg(AddrIn)
8593         .addImm(0)
8594         .addReg(Data)
8595         .add(predOps(ARMCC::AL));
8596   } else if (IsThumb1) {
8597     // store + update AddrIn
8598     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8599         .addReg(Data)
8600         .addReg(AddrIn)
8601         .addImm(0)
8602         .add(predOps(ARMCC::AL));
8603     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8604         .add(t1CondCodeOp())
8605         .addReg(AddrIn)
8606         .addImm(StSize)
8607         .add(predOps(ARMCC::AL));
8608   } else if (IsThumb2) {
8609     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8610         .addReg(Data)
8611         .addReg(AddrIn)
8612         .addImm(StSize)
8613         .add(predOps(ARMCC::AL));
8614   } else { // arm
8615     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8616         .addReg(Data)
8617         .addReg(AddrIn)
8618         .addReg(0)
8619         .addImm(StSize)
8620         .add(predOps(ARMCC::AL));
8621   }
8622 }
8623 
8624 MachineBasicBlock *
8625 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8626                                    MachineBasicBlock *BB) const {
8627   // This pseudo instruction has 3 operands: dst, src, size
8628   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8629   // Otherwise, we will generate unrolled scalar copies.
8630   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8631   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8632   MachineFunction::iterator It = ++BB->getIterator();
8633 
8634   unsigned dest = MI.getOperand(0).getReg();
8635   unsigned src = MI.getOperand(1).getReg();
8636   unsigned SizeVal = MI.getOperand(2).getImm();
8637   unsigned Align = MI.getOperand(3).getImm();
8638   DebugLoc dl = MI.getDebugLoc();
8639 
8640   MachineFunction *MF = BB->getParent();
8641   MachineRegisterInfo &MRI = MF->getRegInfo();
8642   unsigned UnitSize = 0;
8643   const TargetRegisterClass *TRC = nullptr;
8644   const TargetRegisterClass *VecTRC = nullptr;
8645 
8646   bool IsThumb1 = Subtarget->isThumb1Only();
8647   bool IsThumb2 = Subtarget->isThumb2();
8648   bool IsThumb = Subtarget->isThumb();
8649 
8650   if (Align & 1) {
8651     UnitSize = 1;
8652   } else if (Align & 2) {
8653     UnitSize = 2;
8654   } else {
8655     // Check whether we can use NEON instructions.
8656     if (!MF->getFunction()->hasFnAttribute(Attribute::NoImplicitFloat) &&
8657         Subtarget->hasNEON()) {
8658       if ((Align % 16 == 0) && SizeVal >= 16)
8659         UnitSize = 16;
8660       else if ((Align % 8 == 0) && SizeVal >= 8)
8661         UnitSize = 8;
8662     }
8663     // Can't use NEON instructions.
8664     if (UnitSize == 0)
8665       UnitSize = 4;
8666   }
8667 
8668   // Select the correct opcode and register class for unit size load/store
8669   bool IsNeon = UnitSize >= 8;
8670   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8671   if (IsNeon)
8672     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8673                             : UnitSize == 8 ? &ARM::DPRRegClass
8674                                             : nullptr;
8675 
8676   unsigned BytesLeft = SizeVal % UnitSize;
8677   unsigned LoopSize = SizeVal - BytesLeft;
8678 
8679   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8680     // Use LDR and STR to copy.
8681     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8682     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8683     unsigned srcIn = src;
8684     unsigned destIn = dest;
8685     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8686       unsigned srcOut = MRI.createVirtualRegister(TRC);
8687       unsigned destOut = MRI.createVirtualRegister(TRC);
8688       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8689       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8690                  IsThumb1, IsThumb2);
8691       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8692                  IsThumb1, IsThumb2);
8693       srcIn = srcOut;
8694       destIn = destOut;
8695     }
8696 
8697     // Handle the leftover bytes with LDRB and STRB.
8698     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8699     // [destOut] = STRB_POST(scratch, destIn, 1)
8700     for (unsigned i = 0; i < BytesLeft; i++) {
8701       unsigned srcOut = MRI.createVirtualRegister(TRC);
8702       unsigned destOut = MRI.createVirtualRegister(TRC);
8703       unsigned scratch = MRI.createVirtualRegister(TRC);
8704       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8705                  IsThumb1, IsThumb2);
8706       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8707                  IsThumb1, IsThumb2);
8708       srcIn = srcOut;
8709       destIn = destOut;
8710     }
8711     MI.eraseFromParent(); // The instruction is gone now.
8712     return BB;
8713   }
8714 
8715   // Expand the pseudo op to a loop.
8716   // thisMBB:
8717   //   ...
8718   //   movw varEnd, # --> with thumb2
8719   //   movt varEnd, #
8720   //   ldrcp varEnd, idx --> without thumb2
8721   //   fallthrough --> loopMBB
8722   // loopMBB:
8723   //   PHI varPhi, varEnd, varLoop
8724   //   PHI srcPhi, src, srcLoop
8725   //   PHI destPhi, dst, destLoop
8726   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8727   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8728   //   subs varLoop, varPhi, #UnitSize
8729   //   bne loopMBB
8730   //   fallthrough --> exitMBB
8731   // exitMBB:
8732   //   epilogue to handle left-over bytes
8733   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8734   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8735   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8736   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8737   MF->insert(It, loopMBB);
8738   MF->insert(It, exitMBB);
8739 
8740   // Transfer the remainder of BB and its successor edges to exitMBB.
8741   exitMBB->splice(exitMBB->begin(), BB,
8742                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8743   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8744 
8745   // Load an immediate to varEnd.
8746   unsigned varEnd = MRI.createVirtualRegister(TRC);
8747   if (Subtarget->useMovt(*MF)) {
8748     unsigned Vtmp = varEnd;
8749     if ((LoopSize & 0xFFFF0000) != 0)
8750       Vtmp = MRI.createVirtualRegister(TRC);
8751     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8752         .addImm(LoopSize & 0xFFFF)
8753         .add(predOps(ARMCC::AL));
8754 
8755     if ((LoopSize & 0xFFFF0000) != 0)
8756       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8757           .addReg(Vtmp)
8758           .addImm(LoopSize >> 16)
8759           .add(predOps(ARMCC::AL));
8760   } else {
8761     MachineConstantPool *ConstantPool = MF->getConstantPool();
8762     Type *Int32Ty = Type::getInt32Ty(MF->getFunction()->getContext());
8763     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8764 
8765     // MachineConstantPool wants an explicit alignment.
8766     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8767     if (Align == 0)
8768       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8769     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8770 
8771     if (IsThumb)
8772       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
8773           .addReg(varEnd, RegState::Define)
8774           .addConstantPoolIndex(Idx)
8775           .add(predOps(ARMCC::AL));
8776     else
8777       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
8778           .addReg(varEnd, RegState::Define)
8779           .addConstantPoolIndex(Idx)
8780           .addImm(0)
8781           .add(predOps(ARMCC::AL));
8782   }
8783   BB->addSuccessor(loopMBB);
8784 
8785   // Generate the loop body:
8786   //   varPhi = PHI(varLoop, varEnd)
8787   //   srcPhi = PHI(srcLoop, src)
8788   //   destPhi = PHI(destLoop, dst)
8789   MachineBasicBlock *entryBB = BB;
8790   BB = loopMBB;
8791   unsigned varLoop = MRI.createVirtualRegister(TRC);
8792   unsigned varPhi = MRI.createVirtualRegister(TRC);
8793   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8794   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8795   unsigned destLoop = MRI.createVirtualRegister(TRC);
8796   unsigned destPhi = MRI.createVirtualRegister(TRC);
8797 
8798   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8799     .addReg(varLoop).addMBB(loopMBB)
8800     .addReg(varEnd).addMBB(entryBB);
8801   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8802     .addReg(srcLoop).addMBB(loopMBB)
8803     .addReg(src).addMBB(entryBB);
8804   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8805     .addReg(destLoop).addMBB(loopMBB)
8806     .addReg(dest).addMBB(entryBB);
8807 
8808   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8809   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8810   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8811   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8812              IsThumb1, IsThumb2);
8813   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8814              IsThumb1, IsThumb2);
8815 
8816   // Decrement loop variable by UnitSize.
8817   if (IsThumb1) {
8818     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
8819         .add(t1CondCodeOp())
8820         .addReg(varPhi)
8821         .addImm(UnitSize)
8822         .add(predOps(ARMCC::AL));
8823   } else {
8824     MachineInstrBuilder MIB =
8825         BuildMI(*BB, BB->end(), dl,
8826                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8827     MIB.addReg(varPhi)
8828         .addImm(UnitSize)
8829         .add(predOps(ARMCC::AL))
8830         .add(condCodeOp());
8831     MIB->getOperand(5).setReg(ARM::CPSR);
8832     MIB->getOperand(5).setIsDef(true);
8833   }
8834   BuildMI(*BB, BB->end(), dl,
8835           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8836       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8837 
8838   // loopMBB can loop back to loopMBB or fall through to exitMBB.
8839   BB->addSuccessor(loopMBB);
8840   BB->addSuccessor(exitMBB);
8841 
8842   // Add epilogue to handle BytesLeft.
8843   BB = exitMBB;
8844   auto StartOfExit = exitMBB->begin();
8845 
8846   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8847   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8848   unsigned srcIn = srcLoop;
8849   unsigned destIn = destLoop;
8850   for (unsigned i = 0; i < BytesLeft; i++) {
8851     unsigned srcOut = MRI.createVirtualRegister(TRC);
8852     unsigned destOut = MRI.createVirtualRegister(TRC);
8853     unsigned scratch = MRI.createVirtualRegister(TRC);
8854     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8855                IsThumb1, IsThumb2);
8856     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8857                IsThumb1, IsThumb2);
8858     srcIn = srcOut;
8859     destIn = destOut;
8860   }
8861 
8862   MI.eraseFromParent(); // The instruction is gone now.
8863   return BB;
8864 }
8865 
8866 MachineBasicBlock *
8867 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8868                                        MachineBasicBlock *MBB) const {
8869   const TargetMachine &TM = getTargetMachine();
8870   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8871   DebugLoc DL = MI.getDebugLoc();
8872 
8873   assert(Subtarget->isTargetWindows() &&
8874          "__chkstk is only supported on Windows");
8875   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8876 
8877   // __chkstk takes the number of words to allocate on the stack in R4, and
8878   // returns the stack adjustment in number of bytes in R4.  This will not
8879   // clober any other registers (other than the obvious lr).
8880   //
8881   // Although, technically, IP should be considered a register which may be
8882   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
8883   // thumb-2 environment, so there is no interworking required.  As a result, we
8884   // do not expect a veneer to be emitted by the linker, clobbering IP.
8885   //
8886   // Each module receives its own copy of __chkstk, so no import thunk is
8887   // required, again, ensuring that IP is not clobbered.
8888   //
8889   // Finally, although some linkers may theoretically provide a trampoline for
8890   // out of range calls (which is quite common due to a 32M range limitation of
8891   // branches for Thumb), we can generate the long-call version via
8892   // -mcmodel=large, alleviating the need for the trampoline which may clobber
8893   // IP.
8894 
8895   switch (TM.getCodeModel()) {
8896   case CodeModel::Small:
8897   case CodeModel::Medium:
8898   case CodeModel::Kernel:
8899     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
8900         .add(predOps(ARMCC::AL))
8901         .addExternalSymbol("__chkstk")
8902         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8903         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8904         .addReg(ARM::R12,
8905                 RegState::Implicit | RegState::Define | RegState::Dead)
8906         .addReg(ARM::CPSR,
8907                 RegState::Implicit | RegState::Define | RegState::Dead);
8908     break;
8909   case CodeModel::Large: {
8910     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
8911     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
8912 
8913     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
8914       .addExternalSymbol("__chkstk");
8915     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
8916         .add(predOps(ARMCC::AL))
8917         .addReg(Reg, RegState::Kill)
8918         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
8919         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
8920         .addReg(ARM::R12,
8921                 RegState::Implicit | RegState::Define | RegState::Dead)
8922         .addReg(ARM::CPSR,
8923                 RegState::Implicit | RegState::Define | RegState::Dead);
8924     break;
8925   }
8926   }
8927 
8928   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
8929       .addReg(ARM::SP, RegState::Kill)
8930       .addReg(ARM::R4, RegState::Kill)
8931       .setMIFlags(MachineInstr::FrameSetup)
8932       .add(predOps(ARMCC::AL))
8933       .add(condCodeOp());
8934 
8935   MI.eraseFromParent();
8936   return MBB;
8937 }
8938 
8939 MachineBasicBlock *
8940 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
8941                                        MachineBasicBlock *MBB) const {
8942   DebugLoc DL = MI.getDebugLoc();
8943   MachineFunction *MF = MBB->getParent();
8944   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8945 
8946   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
8947   MF->insert(++MBB->getIterator(), ContBB);
8948   ContBB->splice(ContBB->begin(), MBB,
8949                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
8950   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
8951   MBB->addSuccessor(ContBB);
8952 
8953   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8954   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
8955   MF->push_back(TrapBB);
8956   MBB->addSuccessor(TrapBB);
8957 
8958   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
8959       .addReg(MI.getOperand(0).getReg())
8960       .addImm(0)
8961       .add(predOps(ARMCC::AL));
8962   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
8963       .addMBB(TrapBB)
8964       .addImm(ARMCC::EQ)
8965       .addReg(ARM::CPSR);
8966 
8967   MI.eraseFromParent();
8968   return ContBB;
8969 }
8970 
8971 MachineBasicBlock *
8972 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
8973                                                MachineBasicBlock *BB) const {
8974   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8975   DebugLoc dl = MI.getDebugLoc();
8976   bool isThumb2 = Subtarget->isThumb2();
8977   switch (MI.getOpcode()) {
8978   default: {
8979     MI.print(errs());
8980     llvm_unreachable("Unexpected instr type to insert");
8981   }
8982 
8983   // Thumb1 post-indexed loads are really just single-register LDMs.
8984   case ARM::tLDR_postidx: {
8985     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
8986         .add(MI.getOperand(1))  // Rn_wb
8987         .add(MI.getOperand(2))  // Rn
8988         .add(MI.getOperand(3))  // PredImm
8989         .add(MI.getOperand(4))  // PredReg
8990         .add(MI.getOperand(0)); // Rt
8991     MI.eraseFromParent();
8992     return BB;
8993   }
8994 
8995   // The Thumb2 pre-indexed stores have the same MI operands, they just
8996   // define them differently in the .td files from the isel patterns, so
8997   // they need pseudos.
8998   case ARM::t2STR_preidx:
8999     MI.setDesc(TII->get(ARM::t2STR_PRE));
9000     return BB;
9001   case ARM::t2STRB_preidx:
9002     MI.setDesc(TII->get(ARM::t2STRB_PRE));
9003     return BB;
9004   case ARM::t2STRH_preidx:
9005     MI.setDesc(TII->get(ARM::t2STRH_PRE));
9006     return BB;
9007 
9008   case ARM::STRi_preidx:
9009   case ARM::STRBi_preidx: {
9010     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9011                                                          : ARM::STRB_PRE_IMM;
9012     // Decode the offset.
9013     unsigned Offset = MI.getOperand(4).getImm();
9014     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
9015     Offset = ARM_AM::getAM2Offset(Offset);
9016     if (isSub)
9017       Offset = -Offset;
9018 
9019     MachineMemOperand *MMO = *MI.memoperands_begin();
9020     BuildMI(*BB, MI, dl, TII->get(NewOpc))
9021         .add(MI.getOperand(0)) // Rn_wb
9022         .add(MI.getOperand(1)) // Rt
9023         .add(MI.getOperand(2)) // Rn
9024         .addImm(Offset)        // offset (skip GPR==zero_reg)
9025         .add(MI.getOperand(5)) // pred
9026         .add(MI.getOperand(6))
9027         .addMemOperand(MMO);
9028     MI.eraseFromParent();
9029     return BB;
9030   }
9031   case ARM::STRr_preidx:
9032   case ARM::STRBr_preidx:
9033   case ARM::STRH_preidx: {
9034     unsigned NewOpc;
9035     switch (MI.getOpcode()) {
9036     default: llvm_unreachable("unexpected opcode!");
9037     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
9038     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
9039     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
9040     }
9041     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
9042     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
9043       MIB.add(MI.getOperand(i));
9044     MI.eraseFromParent();
9045     return BB;
9046   }
9047 
9048   case ARM::tMOVCCr_pseudo: {
9049     // To "insert" a SELECT_CC instruction, we actually have to insert the
9050     // diamond control-flow pattern.  The incoming instruction knows the
9051     // destination vreg to set, the condition code register to branch on, the
9052     // true/false values to select between, and a branch opcode to use.
9053     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9054     MachineFunction::iterator It = ++BB->getIterator();
9055 
9056     //  thisMBB:
9057     //  ...
9058     //   TrueVal = ...
9059     //   cmpTY ccX, r1, r2
9060     //   bCC copy1MBB
9061     //   fallthrough --> copy0MBB
9062     MachineBasicBlock *thisMBB  = BB;
9063     MachineFunction *F = BB->getParent();
9064     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9065     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
9066     F->insert(It, copy0MBB);
9067     F->insert(It, sinkMBB);
9068 
9069     // Transfer the remainder of BB and its successor edges to sinkMBB.
9070     sinkMBB->splice(sinkMBB->begin(), BB,
9071                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9072     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9073 
9074     BB->addSuccessor(copy0MBB);
9075     BB->addSuccessor(sinkMBB);
9076 
9077     BuildMI(BB, dl, TII->get(ARM::tBcc))
9078         .addMBB(sinkMBB)
9079         .addImm(MI.getOperand(3).getImm())
9080         .addReg(MI.getOperand(4).getReg());
9081 
9082     //  copy0MBB:
9083     //   %FalseValue = ...
9084     //   # fallthrough to sinkMBB
9085     BB = copy0MBB;
9086 
9087     // Update machine-CFG edges
9088     BB->addSuccessor(sinkMBB);
9089 
9090     //  sinkMBB:
9091     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9092     //  ...
9093     BB = sinkMBB;
9094     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
9095         .addReg(MI.getOperand(1).getReg())
9096         .addMBB(copy0MBB)
9097         .addReg(MI.getOperand(2).getReg())
9098         .addMBB(thisMBB);
9099 
9100     MI.eraseFromParent(); // The pseudo instruction is gone now.
9101     return BB;
9102   }
9103 
9104   case ARM::BCCi64:
9105   case ARM::BCCZi64: {
9106     // If there is an unconditional branch to the other successor, remove it.
9107     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9108 
9109     // Compare both parts that make up the double comparison separately for
9110     // equality.
9111     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9112 
9113     unsigned LHS1 = MI.getOperand(1).getReg();
9114     unsigned LHS2 = MI.getOperand(2).getReg();
9115     if (RHSisZero) {
9116       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9117           .addReg(LHS1)
9118           .addImm(0)
9119           .add(predOps(ARMCC::AL));
9120       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9121         .addReg(LHS2).addImm(0)
9122         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9123     } else {
9124       unsigned RHS1 = MI.getOperand(3).getReg();
9125       unsigned RHS2 = MI.getOperand(4).getReg();
9126       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9127           .addReg(LHS1)
9128           .addReg(RHS1)
9129           .add(predOps(ARMCC::AL));
9130       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9131         .addReg(LHS2).addReg(RHS2)
9132         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9133     }
9134 
9135     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9136     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9137     if (MI.getOperand(0).getImm() == ARMCC::NE)
9138       std::swap(destMBB, exitMBB);
9139 
9140     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9141       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9142     if (isThumb2)
9143       BuildMI(BB, dl, TII->get(ARM::t2B))
9144           .addMBB(exitMBB)
9145           .add(predOps(ARMCC::AL));
9146     else
9147       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9148 
9149     MI.eraseFromParent(); // The pseudo instruction is gone now.
9150     return BB;
9151   }
9152 
9153   case ARM::Int_eh_sjlj_setjmp:
9154   case ARM::Int_eh_sjlj_setjmp_nofp:
9155   case ARM::tInt_eh_sjlj_setjmp:
9156   case ARM::t2Int_eh_sjlj_setjmp:
9157   case ARM::t2Int_eh_sjlj_setjmp_nofp:
9158     return BB;
9159 
9160   case ARM::Int_eh_sjlj_setup_dispatch:
9161     EmitSjLjDispatchBlock(MI, BB);
9162     return BB;
9163 
9164   case ARM::ABS:
9165   case ARM::t2ABS: {
9166     // To insert an ABS instruction, we have to insert the
9167     // diamond control-flow pattern.  The incoming instruction knows the
9168     // source vreg to test against 0, the destination vreg to set,
9169     // the condition code register to branch on, the
9170     // true/false values to select between, and a branch opcode to use.
9171     // It transforms
9172     //     V1 = ABS V0
9173     // into
9174     //     V2 = MOVS V0
9175     //     BCC                      (branch to SinkBB if V0 >= 0)
9176     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
9177     //     SinkBB: V1 = PHI(V2, V3)
9178     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9179     MachineFunction::iterator BBI = ++BB->getIterator();
9180     MachineFunction *Fn = BB->getParent();
9181     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9182     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
9183     Fn->insert(BBI, RSBBB);
9184     Fn->insert(BBI, SinkBB);
9185 
9186     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9187     unsigned int ABSDstReg = MI.getOperand(0).getReg();
9188     bool ABSSrcKIll = MI.getOperand(1).isKill();
9189     bool isThumb2 = Subtarget->isThumb2();
9190     MachineRegisterInfo &MRI = Fn->getRegInfo();
9191     // In Thumb mode S must not be specified if source register is the SP or
9192     // PC and if destination register is the SP, so restrict register class
9193     unsigned NewRsbDstReg =
9194       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9195 
9196     // Transfer the remainder of BB and its successor edges to sinkMBB.
9197     SinkBB->splice(SinkBB->begin(), BB,
9198                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9199     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9200 
9201     BB->addSuccessor(RSBBB);
9202     BB->addSuccessor(SinkBB);
9203 
9204     // fall through to SinkMBB
9205     RSBBB->addSuccessor(SinkBB);
9206 
9207     // insert a cmp at the end of BB
9208     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9209         .addReg(ABSSrcReg)
9210         .addImm(0)
9211         .add(predOps(ARMCC::AL));
9212 
9213     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9214     BuildMI(BB, dl,
9215       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9216       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9217 
9218     // insert rsbri in RSBBB
9219     // Note: BCC and rsbri will be converted into predicated rsbmi
9220     // by if-conversion pass
9221     BuildMI(*RSBBB, RSBBB->begin(), dl,
9222             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9223         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9224         .addImm(0)
9225         .add(predOps(ARMCC::AL))
9226         .add(condCodeOp());
9227 
9228     // insert PHI in SinkBB,
9229     // reuse ABSDstReg to not change uses of ABS instruction
9230     BuildMI(*SinkBB, SinkBB->begin(), dl,
9231       TII->get(ARM::PHI), ABSDstReg)
9232       .addReg(NewRsbDstReg).addMBB(RSBBB)
9233       .addReg(ABSSrcReg).addMBB(BB);
9234 
9235     // remove ABS instruction
9236     MI.eraseFromParent();
9237 
9238     // return last added BB
9239     return SinkBB;
9240   }
9241   case ARM::COPY_STRUCT_BYVAL_I32:
9242     ++NumLoopByVals;
9243     return EmitStructByval(MI, BB);
9244   case ARM::WIN__CHKSTK:
9245     return EmitLowered__chkstk(MI, BB);
9246   case ARM::WIN__DBZCHK:
9247     return EmitLowered__dbzchk(MI, BB);
9248   }
9249 }
9250 
9251 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
9252 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9253 /// instead of as a custom inserter because we need the use list from the SDNode.
9254 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9255                                     MachineInstr &MI, const SDNode *Node) {
9256   bool isThumb1 = Subtarget->isThumb1Only();
9257 
9258   DebugLoc DL = MI.getDebugLoc();
9259   MachineFunction *MF = MI.getParent()->getParent();
9260   MachineRegisterInfo &MRI = MF->getRegInfo();
9261   MachineInstrBuilder MIB(*MF, MI);
9262 
9263   // If the new dst/src is unused mark it as dead.
9264   if (!Node->hasAnyUseOfValue(0)) {
9265     MI.getOperand(0).setIsDead(true);
9266   }
9267   if (!Node->hasAnyUseOfValue(1)) {
9268     MI.getOperand(1).setIsDead(true);
9269   }
9270 
9271   // The MEMCPY both defines and kills the scratch registers.
9272   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9273     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9274                                                          : &ARM::GPRRegClass);
9275     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9276   }
9277 }
9278 
9279 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9280                                                       SDNode *Node) const {
9281   if (MI.getOpcode() == ARM::MEMCPY) {
9282     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9283     return;
9284   }
9285 
9286   const MCInstrDesc *MCID = &MI.getDesc();
9287   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9288   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9289   // operand is still set to noreg. If needed, set the optional operand's
9290   // register to CPSR, and remove the redundant implicit def.
9291   //
9292   // e.g. ADCS (..., CPSR<imp-def>) -> ADC (... opt:CPSR<def>).
9293 
9294   // Rename pseudo opcodes.
9295   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9296   unsigned ccOutIdx;
9297   if (NewOpc) {
9298     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9299     MCID = &TII->get(NewOpc);
9300 
9301     assert(MCID->getNumOperands() ==
9302            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9303         && "converted opcode should be the same except for cc_out"
9304            " (and, on Thumb1, pred)");
9305 
9306     MI.setDesc(*MCID);
9307 
9308     // Add the optional cc_out operand
9309     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9310 
9311     // On Thumb1, move all input operands to the end, then add the predicate
9312     if (Subtarget->isThumb1Only()) {
9313       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9314         MI.addOperand(MI.getOperand(1));
9315         MI.RemoveOperand(1);
9316       }
9317 
9318       // Restore the ties
9319       for (unsigned i = MI.getNumOperands(); i--;) {
9320         const MachineOperand& op = MI.getOperand(i);
9321         if (op.isReg() && op.isUse()) {
9322           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9323           if (DefIdx != -1)
9324             MI.tieOperands(DefIdx, i);
9325         }
9326       }
9327 
9328       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9329       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9330       ccOutIdx = 1;
9331     } else
9332       ccOutIdx = MCID->getNumOperands() - 1;
9333   } else
9334     ccOutIdx = MCID->getNumOperands() - 1;
9335 
9336   // Any ARM instruction that sets the 's' bit should specify an optional
9337   // "cc_out" operand in the last operand position.
9338   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9339     assert(!NewOpc && "Optional cc_out operand required");
9340     return;
9341   }
9342   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9343   // since we already have an optional CPSR def.
9344   bool definesCPSR = false;
9345   bool deadCPSR = false;
9346   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9347        ++i) {
9348     const MachineOperand &MO = MI.getOperand(i);
9349     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9350       definesCPSR = true;
9351       if (MO.isDead())
9352         deadCPSR = true;
9353       MI.RemoveOperand(i);
9354       break;
9355     }
9356   }
9357   if (!definesCPSR) {
9358     assert(!NewOpc && "Optional cc_out operand required");
9359     return;
9360   }
9361   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9362   if (deadCPSR) {
9363     assert(!MI.getOperand(ccOutIdx).getReg() &&
9364            "expect uninitialized optional cc_out operand");
9365     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9366     if (!Subtarget->isThumb1Only())
9367       return;
9368   }
9369 
9370   // If this instruction was defined with an optional CPSR def and its dag node
9371   // had a live implicit CPSR def, then activate the optional CPSR def.
9372   MachineOperand &MO = MI.getOperand(ccOutIdx);
9373   MO.setReg(ARM::CPSR);
9374   MO.setIsDef(true);
9375 }
9376 
9377 //===----------------------------------------------------------------------===//
9378 //                           ARM Optimization Hooks
9379 //===----------------------------------------------------------------------===//
9380 
9381 // Helper function that checks if N is a null or all ones constant.
9382 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9383   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9384 }
9385 
9386 // Return true if N is conditionally 0 or all ones.
9387 // Detects these expressions where cc is an i1 value:
9388 //
9389 //   (select cc 0, y)   [AllOnes=0]
9390 //   (select cc y, 0)   [AllOnes=0]
9391 //   (zext cc)          [AllOnes=0]
9392 //   (sext cc)          [AllOnes=0/1]
9393 //   (select cc -1, y)  [AllOnes=1]
9394 //   (select cc y, -1)  [AllOnes=1]
9395 //
9396 // Invert is set when N is the null/all ones constant when CC is false.
9397 // OtherOp is set to the alternative value of N.
9398 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9399                                        SDValue &CC, bool &Invert,
9400                                        SDValue &OtherOp,
9401                                        SelectionDAG &DAG) {
9402   switch (N->getOpcode()) {
9403   default: return false;
9404   case ISD::SELECT: {
9405     CC = N->getOperand(0);
9406     SDValue N1 = N->getOperand(1);
9407     SDValue N2 = N->getOperand(2);
9408     if (isZeroOrAllOnes(N1, AllOnes)) {
9409       Invert = false;
9410       OtherOp = N2;
9411       return true;
9412     }
9413     if (isZeroOrAllOnes(N2, AllOnes)) {
9414       Invert = true;
9415       OtherOp = N1;
9416       return true;
9417     }
9418     return false;
9419   }
9420   case ISD::ZERO_EXTEND:
9421     // (zext cc) can never be the all ones value.
9422     if (AllOnes)
9423       return false;
9424     LLVM_FALLTHROUGH;
9425   case ISD::SIGN_EXTEND: {
9426     SDLoc dl(N);
9427     EVT VT = N->getValueType(0);
9428     CC = N->getOperand(0);
9429     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9430       return false;
9431     Invert = !AllOnes;
9432     if (AllOnes)
9433       // When looking for an AllOnes constant, N is an sext, and the 'other'
9434       // value is 0.
9435       OtherOp = DAG.getConstant(0, dl, VT);
9436     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9437       // When looking for a 0 constant, N can be zext or sext.
9438       OtherOp = DAG.getConstant(1, dl, VT);
9439     else
9440       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9441                                 VT);
9442     return true;
9443   }
9444   }
9445 }
9446 
9447 // Combine a constant select operand into its use:
9448 //
9449 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9450 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9451 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9452 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9453 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9454 //
9455 // The transform is rejected if the select doesn't have a constant operand that
9456 // is null, or all ones when AllOnes is set.
9457 //
9458 // Also recognize sext/zext from i1:
9459 //
9460 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9461 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9462 //
9463 // These transformations eventually create predicated instructions.
9464 //
9465 // @param N       The node to transform.
9466 // @param Slct    The N operand that is a select.
9467 // @param OtherOp The other N operand (x above).
9468 // @param DCI     Context.
9469 // @param AllOnes Require the select constant to be all ones instead of null.
9470 // @returns The new node, or SDValue() on failure.
9471 static
9472 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9473                             TargetLowering::DAGCombinerInfo &DCI,
9474                             bool AllOnes = false) {
9475   SelectionDAG &DAG = DCI.DAG;
9476   EVT VT = N->getValueType(0);
9477   SDValue NonConstantVal;
9478   SDValue CCOp;
9479   bool SwapSelectOps;
9480   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9481                                   NonConstantVal, DAG))
9482     return SDValue();
9483 
9484   // Slct is now know to be the desired identity constant when CC is true.
9485   SDValue TrueVal = OtherOp;
9486   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9487                                  OtherOp, NonConstantVal);
9488   // Unless SwapSelectOps says CC should be false.
9489   if (SwapSelectOps)
9490     std::swap(TrueVal, FalseVal);
9491 
9492   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9493                      CCOp, TrueVal, FalseVal);
9494 }
9495 
9496 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9497 static
9498 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9499                                        TargetLowering::DAGCombinerInfo &DCI) {
9500   SDValue N0 = N->getOperand(0);
9501   SDValue N1 = N->getOperand(1);
9502   if (N0.getNode()->hasOneUse())
9503     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9504       return Result;
9505   if (N1.getNode()->hasOneUse())
9506     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9507       return Result;
9508   return SDValue();
9509 }
9510 
9511 static bool IsVUZPShuffleNode(SDNode *N) {
9512   // VUZP shuffle node.
9513   if (N->getOpcode() == ARMISD::VUZP)
9514     return true;
9515 
9516   // "VUZP" on i32 is an alias for VTRN.
9517   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9518     return true;
9519 
9520   return false;
9521 }
9522 
9523 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9524                                  TargetLowering::DAGCombinerInfo &DCI,
9525                                  const ARMSubtarget *Subtarget) {
9526   // Look for ADD(VUZP.0, VUZP.1).
9527   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9528       N0 == N1)
9529    return SDValue();
9530 
9531   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9532   if (!N->getValueType(0).is64BitVector())
9533     return SDValue();
9534 
9535   // Generate vpadd.
9536   SelectionDAG &DAG = DCI.DAG;
9537   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9538   SDLoc dl(N);
9539   SDNode *Unzip = N0.getNode();
9540   EVT VT = N->getValueType(0);
9541 
9542   SmallVector<SDValue, 8> Ops;
9543   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9544                                 TLI.getPointerTy(DAG.getDataLayout())));
9545   Ops.push_back(Unzip->getOperand(0));
9546   Ops.push_back(Unzip->getOperand(1));
9547 
9548   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9549 }
9550 
9551 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9552                                       TargetLowering::DAGCombinerInfo &DCI,
9553                                       const ARMSubtarget *Subtarget) {
9554   // Check for two extended operands.
9555   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9556         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9557       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9558         N1.getOpcode() == ISD::ZERO_EXTEND))
9559     return SDValue();
9560 
9561   SDValue N00 = N0.getOperand(0);
9562   SDValue N10 = N1.getOperand(0);
9563 
9564   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9565   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9566       N00 == N10)
9567     return SDValue();
9568 
9569   // We only recognize Q register paddl here; this can't be reached until
9570   // after type legalization.
9571   if (!N00.getValueType().is64BitVector() ||
9572       !N0.getValueType().is128BitVector())
9573     return SDValue();
9574 
9575   // Generate vpaddl.
9576   SelectionDAG &DAG = DCI.DAG;
9577   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9578   SDLoc dl(N);
9579   EVT VT = N->getValueType(0);
9580 
9581   SmallVector<SDValue, 8> Ops;
9582   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9583   unsigned Opcode;
9584   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9585     Opcode = Intrinsic::arm_neon_vpaddls;
9586   else
9587     Opcode = Intrinsic::arm_neon_vpaddlu;
9588   Ops.push_back(DAG.getConstant(Opcode, dl,
9589                                 TLI.getPointerTy(DAG.getDataLayout())));
9590   EVT ElemTy = N00.getValueType().getVectorElementType();
9591   unsigned NumElts = VT.getVectorNumElements();
9592   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9593   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9594                                N00.getOperand(0), N00.getOperand(1));
9595   Ops.push_back(Concat);
9596 
9597   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9598 }
9599 
9600 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9601 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9602 // much easier to match.
9603 static SDValue
9604 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9605                                TargetLowering::DAGCombinerInfo &DCI,
9606                                const ARMSubtarget *Subtarget) {
9607   // Only perform optimization if after legalize, and if NEON is available. We
9608   // also expected both operands to be BUILD_VECTORs.
9609   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9610       || N0.getOpcode() != ISD::BUILD_VECTOR
9611       || N1.getOpcode() != ISD::BUILD_VECTOR)
9612     return SDValue();
9613 
9614   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9615   EVT VT = N->getValueType(0);
9616   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9617     return SDValue();
9618 
9619   // Check that the vector operands are of the right form.
9620   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9621   // operands, where N is the size of the formed vector.
9622   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9623   // index such that we have a pair wise add pattern.
9624 
9625   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9626   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9627     return SDValue();
9628   SDValue Vec = N0->getOperand(0)->getOperand(0);
9629   SDNode *V = Vec.getNode();
9630   unsigned nextIndex = 0;
9631 
9632   // For each operands to the ADD which are BUILD_VECTORs,
9633   // check to see if each of their operands are an EXTRACT_VECTOR with
9634   // the same vector and appropriate index.
9635   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9636     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9637         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9638 
9639       SDValue ExtVec0 = N0->getOperand(i);
9640       SDValue ExtVec1 = N1->getOperand(i);
9641 
9642       // First operand is the vector, verify its the same.
9643       if (V != ExtVec0->getOperand(0).getNode() ||
9644           V != ExtVec1->getOperand(0).getNode())
9645         return SDValue();
9646 
9647       // Second is the constant, verify its correct.
9648       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9649       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9650 
9651       // For the constant, we want to see all the even or all the odd.
9652       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9653           || C1->getZExtValue() != nextIndex+1)
9654         return SDValue();
9655 
9656       // Increment index.
9657       nextIndex+=2;
9658     } else
9659       return SDValue();
9660   }
9661 
9662   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9663   // we're using the entire input vector, otherwise there's a size/legality
9664   // mismatch somewhere.
9665   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9666       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9667     return SDValue();
9668 
9669   // Create VPADDL node.
9670   SelectionDAG &DAG = DCI.DAG;
9671   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9672 
9673   SDLoc dl(N);
9674 
9675   // Build operand list.
9676   SmallVector<SDValue, 8> Ops;
9677   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9678                                 TLI.getPointerTy(DAG.getDataLayout())));
9679 
9680   // Input is the vector.
9681   Ops.push_back(Vec);
9682 
9683   // Get widened type and narrowed type.
9684   MVT widenType;
9685   unsigned numElem = VT.getVectorNumElements();
9686 
9687   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9688   switch (inputLaneType.getSimpleVT().SimpleTy) {
9689     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9690     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9691     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9692     default:
9693       llvm_unreachable("Invalid vector element type for padd optimization.");
9694   }
9695 
9696   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9697   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9698   return DAG.getNode(ExtOp, dl, VT, tmp);
9699 }
9700 
9701 static SDValue findMUL_LOHI(SDValue V) {
9702   if (V->getOpcode() == ISD::UMUL_LOHI ||
9703       V->getOpcode() == ISD::SMUL_LOHI)
9704     return V;
9705   return SDValue();
9706 }
9707 
9708 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9709                                         TargetLowering::DAGCombinerInfo &DCI,
9710                                         const ARMSubtarget *Subtarget) {
9711   if (Subtarget->isThumb()) {
9712     if (!Subtarget->hasDSP())
9713       return SDValue();
9714   } else if (!Subtarget->hasV5TEOps())
9715     return SDValue();
9716 
9717   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
9718   // accumulates the product into a 64-bit value. The 16-bit values will
9719   // be sign extended somehow or SRA'd into 32-bit values
9720   // (addc (adde (mul 16bit, 16bit), lo), hi)
9721   SDValue Mul = AddcNode->getOperand(0);
9722   SDValue Lo = AddcNode->getOperand(1);
9723   if (Mul.getOpcode() != ISD::MUL) {
9724     Lo = AddcNode->getOperand(0);
9725     Mul = AddcNode->getOperand(1);
9726     if (Mul.getOpcode() != ISD::MUL)
9727       return SDValue();
9728   }
9729 
9730   SDValue SRA = AddeNode->getOperand(0);
9731   SDValue Hi = AddeNode->getOperand(1);
9732   if (SRA.getOpcode() != ISD::SRA) {
9733     SRA = AddeNode->getOperand(1);
9734     Hi = AddeNode->getOperand(0);
9735     if (SRA.getOpcode() != ISD::SRA)
9736       return SDValue();
9737   }
9738   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
9739     if (Const->getZExtValue() != 31)
9740       return SDValue();
9741   } else
9742     return SDValue();
9743 
9744   if (SRA.getOperand(0) != Mul)
9745     return SDValue();
9746 
9747   SelectionDAG &DAG = DCI.DAG;
9748   SDLoc dl(AddcNode);
9749   unsigned Opcode = 0;
9750   SDValue Op0;
9751   SDValue Op1;
9752 
9753   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
9754     Opcode = ARMISD::SMLALBB;
9755     Op0 = Mul.getOperand(0);
9756     Op1 = Mul.getOperand(1);
9757   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
9758     Opcode = ARMISD::SMLALBT;
9759     Op0 = Mul.getOperand(0);
9760     Op1 = Mul.getOperand(1).getOperand(0);
9761   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
9762     Opcode = ARMISD::SMLALTB;
9763     Op0 = Mul.getOperand(0).getOperand(0);
9764     Op1 = Mul.getOperand(1);
9765   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
9766     Opcode = ARMISD::SMLALTT;
9767     Op0 = Mul->getOperand(0).getOperand(0);
9768     Op1 = Mul->getOperand(1).getOperand(0);
9769   }
9770 
9771   if (!Op0 || !Op1)
9772     return SDValue();
9773 
9774   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
9775                               Op0, Op1, Lo, Hi);
9776   // Replace the ADDs' nodes uses by the MLA node's values.
9777   SDValue HiMLALResult(SMLAL.getNode(), 1);
9778   SDValue LoMLALResult(SMLAL.getNode(), 0);
9779 
9780   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9781   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9782 
9783   // Return original node to notify the driver to stop replacing.
9784   SDValue resNode(AddcNode, 0);
9785   return resNode;
9786 }
9787 
9788 static SDValue AddCombineTo64bitMLAL(SDNode *AddeNode,
9789                                      TargetLowering::DAGCombinerInfo &DCI,
9790                                      const ARMSubtarget *Subtarget) {
9791   // Look for multiply add opportunities.
9792   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9793   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9794   // a glue link from the first add to the second add.
9795   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9796   // a S/UMLAL instruction.
9797   //                  UMUL_LOHI
9798   //                 / :lo    \ :hi
9799   //                V          \          [no multiline comment]
9800   //    loAdd ->  ADDC         |
9801   //                 \ :carry /
9802   //                  V      V
9803   //                    ADDE   <- hiAdd
9804   //
9805   assert(AddeNode->getOpcode() == ARMISD::ADDE && "Expect an ADDE");
9806 
9807   assert(AddeNode->getNumOperands() == 3 &&
9808          AddeNode->getOperand(2).getValueType() == MVT::i32 &&
9809          "ADDE node has the wrong inputs");
9810 
9811   // Check that we are chained to the right ADDC node.
9812   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9813   if (AddcNode->getOpcode() != ARMISD::ADDC)
9814     return SDValue();
9815 
9816   SDValue AddcOp0 = AddcNode->getOperand(0);
9817   SDValue AddcOp1 = AddcNode->getOperand(1);
9818 
9819   // Check if the two operands are from the same mul_lohi node.
9820   if (AddcOp0.getNode() == AddcOp1.getNode())
9821     return SDValue();
9822 
9823   assert(AddcNode->getNumValues() == 2 &&
9824          AddcNode->getValueType(0) == MVT::i32 &&
9825          "Expect ADDC with two result values. First: i32");
9826 
9827   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
9828   // maybe a SMLAL which multiplies two 16-bit values.
9829   if (AddcOp0->getOpcode() != ISD::UMUL_LOHI &&
9830       AddcOp0->getOpcode() != ISD::SMUL_LOHI &&
9831       AddcOp1->getOpcode() != ISD::UMUL_LOHI &&
9832       AddcOp1->getOpcode() != ISD::SMUL_LOHI)
9833     return AddCombineTo64BitSMLAL16(AddcNode, AddeNode, DCI, Subtarget);
9834 
9835   // Check for the triangle shape.
9836   SDValue AddeOp0 = AddeNode->getOperand(0);
9837   SDValue AddeOp1 = AddeNode->getOperand(1);
9838 
9839   // Make sure that the ADDE operands are not coming from the same node.
9840   if (AddeOp0.getNode() == AddeOp1.getNode())
9841     return SDValue();
9842 
9843   // Find the MUL_LOHI node walking up ADDE's operands.
9844   bool IsLeftOperandMUL = false;
9845   SDValue MULOp = findMUL_LOHI(AddeOp0);
9846   if (MULOp == SDValue())
9847    MULOp = findMUL_LOHI(AddeOp1);
9848   else
9849     IsLeftOperandMUL = true;
9850   if (MULOp == SDValue())
9851     return SDValue();
9852 
9853   // Figure out the right opcode.
9854   unsigned Opc = MULOp->getOpcode();
9855   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
9856 
9857   // Figure out the high and low input values to the MLAL node.
9858   SDValue* HiAdd = nullptr;
9859   SDValue* LoMul = nullptr;
9860   SDValue* LowAdd = nullptr;
9861 
9862   // Ensure that ADDE is from high result of ISD::xMUL_LOHI.
9863   if ((AddeOp0 != MULOp.getValue(1)) && (AddeOp1 != MULOp.getValue(1)))
9864     return SDValue();
9865 
9866   if (IsLeftOperandMUL)
9867     HiAdd = &AddeOp1;
9868   else
9869     HiAdd = &AddeOp0;
9870 
9871 
9872   // Ensure that LoMul and LowAdd are taken from correct ISD::SMUL_LOHI node
9873   // whose low result is fed to the ADDC we are checking.
9874 
9875   if (AddcOp0 == MULOp.getValue(0)) {
9876     LoMul = &AddcOp0;
9877     LowAdd = &AddcOp1;
9878   }
9879   if (AddcOp1 == MULOp.getValue(0)) {
9880     LoMul = &AddcOp1;
9881     LowAdd = &AddcOp0;
9882   }
9883 
9884   if (!LoMul)
9885     return SDValue();
9886 
9887   // If HiAdd is the same node as ADDC or is a predecessor of ADDC the
9888   // replacement below will create a cycle.
9889   if (AddcNode == HiAdd->getNode() ||
9890       AddcNode->isPredecessorOf(HiAdd->getNode()))
9891     return SDValue();
9892 
9893   // Create the merged node.
9894   SelectionDAG &DAG = DCI.DAG;
9895 
9896   // Build operand list.
9897   SmallVector<SDValue, 8> Ops;
9898   Ops.push_back(LoMul->getOperand(0));
9899   Ops.push_back(LoMul->getOperand(1));
9900   Ops.push_back(*LowAdd);
9901   Ops.push_back(*HiAdd);
9902 
9903   SDValue MLALNode =  DAG.getNode(FinalOpc, SDLoc(AddcNode),
9904                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9905 
9906   // Replace the ADDs' nodes uses by the MLA node's values.
9907   SDValue HiMLALResult(MLALNode.getNode(), 1);
9908   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9909 
9910   SDValue LoMLALResult(MLALNode.getNode(), 0);
9911   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9912 
9913   // Return original node to notify the driver to stop replacing.
9914   return SDValue(AddeNode, 0);
9915 }
9916 
9917 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
9918                                       TargetLowering::DAGCombinerInfo &DCI,
9919                                       const ARMSubtarget *Subtarget) {
9920   // UMAAL is similar to UMLAL except that it adds two unsigned values.
9921   // While trying to combine for the other MLAL nodes, first search for the
9922   // chance to use UMAAL. Check if Addc uses a node which has already
9923   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
9924   // as the addend, and it's handled in PerformUMLALCombine.
9925 
9926   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9927     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9928 
9929   // Check that we have a glued ADDC node.
9930   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
9931   if (AddcNode->getOpcode() != ARMISD::ADDC)
9932     return SDValue();
9933 
9934   // Find the converted UMAAL or quit if it doesn't exist.
9935   SDNode *UmlalNode = nullptr;
9936   SDValue AddHi;
9937   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
9938     UmlalNode = AddcNode->getOperand(0).getNode();
9939     AddHi = AddcNode->getOperand(1);
9940   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
9941     UmlalNode = AddcNode->getOperand(1).getNode();
9942     AddHi = AddcNode->getOperand(0);
9943   } else {
9944     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
9945   }
9946 
9947   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
9948   // the ADDC as well as Zero.
9949   if (!isNullConstant(UmlalNode->getOperand(3)))
9950     return SDValue();
9951 
9952   if ((isNullConstant(AddeNode->getOperand(0)) &&
9953        AddeNode->getOperand(1).getNode() == UmlalNode) ||
9954       (AddeNode->getOperand(0).getNode() == UmlalNode &&
9955        isNullConstant(AddeNode->getOperand(1)))) {
9956     SelectionDAG &DAG = DCI.DAG;
9957     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
9958                       UmlalNode->getOperand(2), AddHi };
9959     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
9960                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
9961 
9962     // Replace the ADDs' nodes uses by the UMAAL node's values.
9963     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
9964     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
9965 
9966     // Return original node to notify the driver to stop replacing.
9967     return SDValue(AddeNode, 0);
9968   }
9969   return SDValue();
9970 }
9971 
9972 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
9973                                    const ARMSubtarget *Subtarget) {
9974   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
9975     return SDValue();
9976 
9977   // Check that we have a pair of ADDC and ADDE as operands.
9978   // Both addends of the ADDE must be zero.
9979   SDNode* AddcNode = N->getOperand(2).getNode();
9980   SDNode* AddeNode = N->getOperand(3).getNode();
9981   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
9982       (AddeNode->getOpcode() == ARMISD::ADDE) &&
9983       isNullConstant(AddeNode->getOperand(0)) &&
9984       isNullConstant(AddeNode->getOperand(1)) &&
9985       (AddeNode->getOperand(2).getNode() == AddcNode))
9986     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
9987                        DAG.getVTList(MVT::i32, MVT::i32),
9988                        {N->getOperand(0), N->getOperand(1),
9989                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
9990   else
9991     return SDValue();
9992 }
9993 
9994 static SDValue PerformAddcSubcCombine(SDNode *N,
9995                                       TargetLowering::DAGCombinerInfo &DCI,
9996                                       const ARMSubtarget *Subtarget) {
9997   SelectionDAG &DAG(DCI.DAG);
9998 
9999   if (N->getOpcode() == ARMISD::ADDC) {
10000     // (ADDC (ADDE 0, 0, C), -1) -> C
10001     SDValue LHS = N->getOperand(0);
10002     SDValue RHS = N->getOperand(1);
10003     if (LHS->getOpcode() == ARMISD::ADDE &&
10004         isNullConstant(LHS->getOperand(0)) &&
10005         isNullConstant(LHS->getOperand(1)) && isAllOnesConstant(RHS)) {
10006       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
10007     }
10008   }
10009 
10010   if (Subtarget->isThumb1Only()) {
10011     SDValue RHS = N->getOperand(1);
10012     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10013       int32_t imm = C->getSExtValue();
10014       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
10015         SDLoc DL(N);
10016         RHS = DAG.getConstant(-imm, DL, MVT::i32);
10017         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
10018                                                            : ARMISD::ADDC;
10019         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
10020       }
10021     }
10022   }
10023   return SDValue();
10024 }
10025 
10026 static SDValue PerformAddeSubeCombine(SDNode *N, SelectionDAG &DAG,
10027                                       const ARMSubtarget *Subtarget) {
10028   if (Subtarget->isThumb1Only()) {
10029     SDValue RHS = N->getOperand(1);
10030     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10031       int64_t imm = C->getSExtValue();
10032       if (imm < 0) {
10033         SDLoc DL(N);
10034 
10035         // The with-carry-in form matches bitwise not instead of the negation.
10036         // Effectively, the inverse interpretation of the carry flag already
10037         // accounts for part of the negation.
10038         RHS = DAG.getConstant(~imm, DL, MVT::i32);
10039 
10040         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
10041                                                            : ARMISD::ADDE;
10042         return DAG.getNode(Opcode, DL, N->getVTList(),
10043                            N->getOperand(0), RHS, N->getOperand(2));
10044       }
10045     }
10046   }
10047   return SDValue();
10048 }
10049 
10050 /// PerformADDECombine - Target-specific dag combine transform from
10051 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
10052 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
10053 static SDValue PerformADDECombine(SDNode *N,
10054                                   TargetLowering::DAGCombinerInfo &DCI,
10055                                   const ARMSubtarget *Subtarget) {
10056   // Only ARM and Thumb2 support UMLAL/SMLAL.
10057   if (Subtarget->isThumb1Only())
10058     return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
10059 
10060   // Only perform the checks after legalize when the pattern is available.
10061   if (DCI.isBeforeLegalize()) return SDValue();
10062 
10063   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
10064 }
10065 
10066 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
10067 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
10068 /// called with the default operands, and if that fails, with commuted
10069 /// operands.
10070 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
10071                                           TargetLowering::DAGCombinerInfo &DCI,
10072                                           const ARMSubtarget *Subtarget){
10073   // Attempt to create vpadd for this add.
10074   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
10075     return Result;
10076 
10077   // Attempt to create vpaddl for this add.
10078   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
10079     return Result;
10080   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
10081                                                       Subtarget))
10082     return Result;
10083 
10084   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10085   if (N0.getNode()->hasOneUse())
10086     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
10087       return Result;
10088   return SDValue();
10089 }
10090 
10091 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
10092 ///
10093 static SDValue PerformADDCombine(SDNode *N,
10094                                  TargetLowering::DAGCombinerInfo &DCI,
10095                                  const ARMSubtarget *Subtarget) {
10096   SDValue N0 = N->getOperand(0);
10097   SDValue N1 = N->getOperand(1);
10098 
10099   // First try with the default operand order.
10100   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
10101     return Result;
10102 
10103   // If that didn't work, try again with the operands commuted.
10104   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
10105 }
10106 
10107 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
10108 ///
10109 static SDValue PerformSUBCombine(SDNode *N,
10110                                  TargetLowering::DAGCombinerInfo &DCI) {
10111   SDValue N0 = N->getOperand(0);
10112   SDValue N1 = N->getOperand(1);
10113 
10114   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10115   if (N1.getNode()->hasOneUse())
10116     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10117       return Result;
10118 
10119   return SDValue();
10120 }
10121 
10122 /// PerformVMULCombine
10123 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10124 /// special multiplier accumulator forwarding.
10125 ///   vmul d3, d0, d2
10126 ///   vmla d3, d1, d2
10127 /// is faster than
10128 ///   vadd d3, d0, d1
10129 ///   vmul d3, d3, d2
10130 //  However, for (A + B) * (A + B),
10131 //    vadd d2, d0, d1
10132 //    vmul d3, d0, d2
10133 //    vmla d3, d1, d2
10134 //  is slower than
10135 //    vadd d2, d0, d1
10136 //    vmul d3, d2, d2
10137 static SDValue PerformVMULCombine(SDNode *N,
10138                                   TargetLowering::DAGCombinerInfo &DCI,
10139                                   const ARMSubtarget *Subtarget) {
10140   if (!Subtarget->hasVMLxForwarding())
10141     return SDValue();
10142 
10143   SelectionDAG &DAG = DCI.DAG;
10144   SDValue N0 = N->getOperand(0);
10145   SDValue N1 = N->getOperand(1);
10146   unsigned Opcode = N0.getOpcode();
10147   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10148       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10149     Opcode = N1.getOpcode();
10150     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10151         Opcode != ISD::FADD && Opcode != ISD::FSUB)
10152       return SDValue();
10153     std::swap(N0, N1);
10154   }
10155 
10156   if (N0 == N1)
10157     return SDValue();
10158 
10159   EVT VT = N->getValueType(0);
10160   SDLoc DL(N);
10161   SDValue N00 = N0->getOperand(0);
10162   SDValue N01 = N0->getOperand(1);
10163   return DAG.getNode(Opcode, DL, VT,
10164                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10165                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10166 }
10167 
10168 static SDValue PerformMULCombine(SDNode *N,
10169                                  TargetLowering::DAGCombinerInfo &DCI,
10170                                  const ARMSubtarget *Subtarget) {
10171   SelectionDAG &DAG = DCI.DAG;
10172 
10173   if (Subtarget->isThumb1Only())
10174     return SDValue();
10175 
10176   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10177     return SDValue();
10178 
10179   EVT VT = N->getValueType(0);
10180   if (VT.is64BitVector() || VT.is128BitVector())
10181     return PerformVMULCombine(N, DCI, Subtarget);
10182   if (VT != MVT::i32)
10183     return SDValue();
10184 
10185   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10186   if (!C)
10187     return SDValue();
10188 
10189   int64_t MulAmt = C->getSExtValue();
10190   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10191 
10192   ShiftAmt = ShiftAmt & (32 - 1);
10193   SDValue V = N->getOperand(0);
10194   SDLoc DL(N);
10195 
10196   SDValue Res;
10197   MulAmt >>= ShiftAmt;
10198 
10199   if (MulAmt >= 0) {
10200     if (isPowerOf2_32(MulAmt - 1)) {
10201       // (mul x, 2^N + 1) => (add (shl x, N), x)
10202       Res = DAG.getNode(ISD::ADD, DL, VT,
10203                         V,
10204                         DAG.getNode(ISD::SHL, DL, VT,
10205                                     V,
10206                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
10207                                                     MVT::i32)));
10208     } else if (isPowerOf2_32(MulAmt + 1)) {
10209       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10210       Res = DAG.getNode(ISD::SUB, DL, VT,
10211                         DAG.getNode(ISD::SHL, DL, VT,
10212                                     V,
10213                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10214                                                     MVT::i32)),
10215                         V);
10216     } else
10217       return SDValue();
10218   } else {
10219     uint64_t MulAmtAbs = -MulAmt;
10220     if (isPowerOf2_32(MulAmtAbs + 1)) {
10221       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10222       Res = DAG.getNode(ISD::SUB, DL, VT,
10223                         V,
10224                         DAG.getNode(ISD::SHL, DL, VT,
10225                                     V,
10226                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10227                                                     MVT::i32)));
10228     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10229       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10230       Res = DAG.getNode(ISD::ADD, DL, VT,
10231                         V,
10232                         DAG.getNode(ISD::SHL, DL, VT,
10233                                     V,
10234                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10235                                                     MVT::i32)));
10236       Res = DAG.getNode(ISD::SUB, DL, VT,
10237                         DAG.getConstant(0, DL, MVT::i32), Res);
10238     } else
10239       return SDValue();
10240   }
10241 
10242   if (ShiftAmt != 0)
10243     Res = DAG.getNode(ISD::SHL, DL, VT,
10244                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10245 
10246   // Do not add new nodes to DAG combiner worklist.
10247   DCI.CombineTo(N, Res, false);
10248   return SDValue();
10249 }
10250 
10251 static SDValue PerformANDCombine(SDNode *N,
10252                                  TargetLowering::DAGCombinerInfo &DCI,
10253                                  const ARMSubtarget *Subtarget) {
10254   // Attempt to use immediate-form VBIC
10255   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10256   SDLoc dl(N);
10257   EVT VT = N->getValueType(0);
10258   SelectionDAG &DAG = DCI.DAG;
10259 
10260   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10261     return SDValue();
10262 
10263   APInt SplatBits, SplatUndef;
10264   unsigned SplatBitSize;
10265   bool HasAnyUndefs;
10266   if (BVN &&
10267       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10268     if (SplatBitSize <= 64) {
10269       EVT VbicVT;
10270       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10271                                       SplatUndef.getZExtValue(), SplatBitSize,
10272                                       DAG, dl, VbicVT, VT.is128BitVector(),
10273                                       OtherModImm);
10274       if (Val.getNode()) {
10275         SDValue Input =
10276           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10277         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10278         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10279       }
10280     }
10281   }
10282 
10283   if (!Subtarget->isThumb1Only()) {
10284     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10285     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10286       return Result;
10287   }
10288 
10289   return SDValue();
10290 }
10291 
10292 // Try combining OR nodes to SMULWB, SMULWT.
10293 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10294                                          TargetLowering::DAGCombinerInfo &DCI,
10295                                          const ARMSubtarget *Subtarget) {
10296   if (!Subtarget->hasV6Ops() ||
10297       (Subtarget->isThumb() &&
10298        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10299     return SDValue();
10300 
10301   SDValue SRL = OR->getOperand(0);
10302   SDValue SHL = OR->getOperand(1);
10303 
10304   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10305     SRL = OR->getOperand(1);
10306     SHL = OR->getOperand(0);
10307   }
10308   if (!isSRL16(SRL) || !isSHL16(SHL))
10309     return SDValue();
10310 
10311   // The first operands to the shifts need to be the two results from the
10312   // same smul_lohi node.
10313   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10314        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10315     return SDValue();
10316 
10317   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10318   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10319       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10320     return SDValue();
10321 
10322   // Now we have:
10323   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10324   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10325   // For SMUWB the 16-bit value will signed extended somehow.
10326   // For SMULWT only the SRA is required.
10327   // Check both sides of SMUL_LOHI
10328   SDValue OpS16 = SMULLOHI->getOperand(0);
10329   SDValue OpS32 = SMULLOHI->getOperand(1);
10330 
10331   SelectionDAG &DAG = DCI.DAG;
10332   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10333     OpS16 = OpS32;
10334     OpS32 = SMULLOHI->getOperand(0);
10335   }
10336 
10337   SDLoc dl(OR);
10338   unsigned Opcode = 0;
10339   if (isS16(OpS16, DAG))
10340     Opcode = ARMISD::SMULWB;
10341   else if (isSRA16(OpS16)) {
10342     Opcode = ARMISD::SMULWT;
10343     OpS16 = OpS16->getOperand(0);
10344   }
10345   else
10346     return SDValue();
10347 
10348   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10349   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10350   return SDValue(OR, 0);
10351 }
10352 
10353 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
10354 static SDValue PerformORCombine(SDNode *N,
10355                                 TargetLowering::DAGCombinerInfo &DCI,
10356                                 const ARMSubtarget *Subtarget) {
10357   // Attempt to use immediate-form VORR
10358   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10359   SDLoc dl(N);
10360   EVT VT = N->getValueType(0);
10361   SelectionDAG &DAG = DCI.DAG;
10362 
10363   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10364     return SDValue();
10365 
10366   APInt SplatBits, SplatUndef;
10367   unsigned SplatBitSize;
10368   bool HasAnyUndefs;
10369   if (BVN && Subtarget->hasNEON() &&
10370       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10371     if (SplatBitSize <= 64) {
10372       EVT VorrVT;
10373       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
10374                                       SplatUndef.getZExtValue(), SplatBitSize,
10375                                       DAG, dl, VorrVT, VT.is128BitVector(),
10376                                       OtherModImm);
10377       if (Val.getNode()) {
10378         SDValue Input =
10379           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
10380         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
10381         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
10382       }
10383     }
10384   }
10385 
10386   if (!Subtarget->isThumb1Only()) {
10387     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10388     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10389       return Result;
10390     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
10391       return Result;
10392   }
10393 
10394   // The code below optimizes (or (and X, Y), Z).
10395   // The AND operand needs to have a single user to make these optimizations
10396   // profitable.
10397   SDValue N0 = N->getOperand(0);
10398   if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
10399     return SDValue();
10400   SDValue N1 = N->getOperand(1);
10401 
10402   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
10403   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
10404       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10405     APInt SplatUndef;
10406     unsigned SplatBitSize;
10407     bool HasAnyUndefs;
10408 
10409     APInt SplatBits0, SplatBits1;
10410     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
10411     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
10412     // Ensure that the second operand of both ands are constants
10413     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
10414                                       HasAnyUndefs) && !HasAnyUndefs) {
10415         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
10416                                           HasAnyUndefs) && !HasAnyUndefs) {
10417             // Ensure that the bit width of the constants are the same and that
10418             // the splat arguments are logical inverses as per the pattern we
10419             // are trying to simplify.
10420             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
10421                 SplatBits0 == ~SplatBits1) {
10422                 // Canonicalize the vector type to make instruction selection
10423                 // simpler.
10424                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
10425                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
10426                                              N0->getOperand(1),
10427                                              N0->getOperand(0),
10428                                              N1->getOperand(0));
10429                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10430             }
10431         }
10432     }
10433   }
10434 
10435   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
10436   // reasonable.
10437 
10438   // BFI is only available on V6T2+
10439   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10440     return SDValue();
10441 
10442   SDLoc DL(N);
10443   // 1) or (and A, mask), val => ARMbfi A, val, mask
10444   //      iff (val & mask) == val
10445   //
10446   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10447   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10448   //          && mask == ~mask2
10449   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10450   //          && ~mask == mask2
10451   //  (i.e., copy a bitfield value into another bitfield of the same width)
10452 
10453   if (VT != MVT::i32)
10454     return SDValue();
10455 
10456   SDValue N00 = N0.getOperand(0);
10457 
10458   // The value and the mask need to be constants so we can verify this is
10459   // actually a bitfield set. If the mask is 0xffff, we can do better
10460   // via a movt instruction, so don't use BFI in that case.
10461   SDValue MaskOp = N0.getOperand(1);
10462   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10463   if (!MaskC)
10464     return SDValue();
10465   unsigned Mask = MaskC->getZExtValue();
10466   if (Mask == 0xffff)
10467     return SDValue();
10468   SDValue Res;
10469   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10470   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10471   if (N1C) {
10472     unsigned Val = N1C->getZExtValue();
10473     if ((Val & ~Mask) != Val)
10474       return SDValue();
10475 
10476     if (ARM::isBitFieldInvertedMask(Mask)) {
10477       Val >>= countTrailingZeros(~Mask);
10478 
10479       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10480                         DAG.getConstant(Val, DL, MVT::i32),
10481                         DAG.getConstant(Mask, DL, MVT::i32));
10482 
10483       // Do not add new nodes to DAG combiner worklist.
10484       DCI.CombineTo(N, Res, false);
10485       return SDValue();
10486     }
10487   } else if (N1.getOpcode() == ISD::AND) {
10488     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10489     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10490     if (!N11C)
10491       return SDValue();
10492     unsigned Mask2 = N11C->getZExtValue();
10493 
10494     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10495     // as is to match.
10496     if (ARM::isBitFieldInvertedMask(Mask) &&
10497         (Mask == ~Mask2)) {
10498       // The pack halfword instruction works better for masks that fit it,
10499       // so use that when it's available.
10500       if (Subtarget->hasDSP() &&
10501           (Mask == 0xffff || Mask == 0xffff0000))
10502         return SDValue();
10503       // 2a
10504       unsigned amt = countTrailingZeros(Mask2);
10505       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10506                         DAG.getConstant(amt, DL, MVT::i32));
10507       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10508                         DAG.getConstant(Mask, DL, MVT::i32));
10509       // Do not add new nodes to DAG combiner worklist.
10510       DCI.CombineTo(N, Res, false);
10511       return SDValue();
10512     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10513                (~Mask == Mask2)) {
10514       // The pack halfword instruction works better for masks that fit it,
10515       // so use that when it's available.
10516       if (Subtarget->hasDSP() &&
10517           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10518         return SDValue();
10519       // 2b
10520       unsigned lsb = countTrailingZeros(Mask);
10521       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10522                         DAG.getConstant(lsb, DL, MVT::i32));
10523       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10524                         DAG.getConstant(Mask2, DL, MVT::i32));
10525       // Do not add new nodes to DAG combiner worklist.
10526       DCI.CombineTo(N, Res, false);
10527       return SDValue();
10528     }
10529   }
10530 
10531   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10532       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10533       ARM::isBitFieldInvertedMask(~Mask)) {
10534     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10535     // where lsb(mask) == #shamt and masked bits of B are known zero.
10536     SDValue ShAmt = N00.getOperand(1);
10537     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10538     unsigned LSB = countTrailingZeros(Mask);
10539     if (ShAmtC != LSB)
10540       return SDValue();
10541 
10542     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10543                       DAG.getConstant(~Mask, DL, MVT::i32));
10544 
10545     // Do not add new nodes to DAG combiner worklist.
10546     DCI.CombineTo(N, Res, false);
10547   }
10548 
10549   return SDValue();
10550 }
10551 
10552 static SDValue PerformXORCombine(SDNode *N,
10553                                  TargetLowering::DAGCombinerInfo &DCI,
10554                                  const ARMSubtarget *Subtarget) {
10555   EVT VT = N->getValueType(0);
10556   SelectionDAG &DAG = DCI.DAG;
10557 
10558   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10559     return SDValue();
10560 
10561   if (!Subtarget->isThumb1Only()) {
10562     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10563     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10564       return Result;
10565   }
10566 
10567   return SDValue();
10568 }
10569 
10570 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
10571 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
10572 // their position in "to" (Rd).
10573 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
10574   assert(N->getOpcode() == ARMISD::BFI);
10575 
10576   SDValue From = N->getOperand(1);
10577   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
10578   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
10579 
10580   // If the Base came from a SHR #C, we can deduce that it is really testing bit
10581   // #C in the base of the SHR.
10582   if (From->getOpcode() == ISD::SRL &&
10583       isa<ConstantSDNode>(From->getOperand(1))) {
10584     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
10585     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
10586     FromMask <<= Shift.getLimitedValue(31);
10587     From = From->getOperand(0);
10588   }
10589 
10590   return From;
10591 }
10592 
10593 // If A and B contain one contiguous set of bits, does A | B == A . B?
10594 //
10595 // Neither A nor B must be zero.
10596 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
10597   unsigned LastActiveBitInA =  A.countTrailingZeros();
10598   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
10599   return LastActiveBitInA - 1 == FirstActiveBitInB;
10600 }
10601 
10602 static SDValue FindBFIToCombineWith(SDNode *N) {
10603   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
10604   // if one exists.
10605   APInt ToMask, FromMask;
10606   SDValue From = ParseBFI(N, ToMask, FromMask);
10607   SDValue To = N->getOperand(0);
10608 
10609   // Now check for a compatible BFI to merge with. We can pass through BFIs that
10610   // aren't compatible, but not if they set the same bit in their destination as
10611   // we do (or that of any BFI we're going to combine with).
10612   SDValue V = To;
10613   APInt CombinedToMask = ToMask;
10614   while (V.getOpcode() == ARMISD::BFI) {
10615     APInt NewToMask, NewFromMask;
10616     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
10617     if (NewFrom != From) {
10618       // This BFI has a different base. Keep going.
10619       CombinedToMask |= NewToMask;
10620       V = V.getOperand(0);
10621       continue;
10622     }
10623 
10624     // Do the written bits conflict with any we've seen so far?
10625     if ((NewToMask & CombinedToMask).getBoolValue())
10626       // Conflicting bits - bail out because going further is unsafe.
10627       return SDValue();
10628 
10629     // Are the new bits contiguous when combined with the old bits?
10630     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
10631         BitsProperlyConcatenate(FromMask, NewFromMask))
10632       return V;
10633     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
10634         BitsProperlyConcatenate(NewFromMask, FromMask))
10635       return V;
10636 
10637     // We've seen a write to some bits, so track it.
10638     CombinedToMask |= NewToMask;
10639     // Keep going...
10640     V = V.getOperand(0);
10641   }
10642 
10643   return SDValue();
10644 }
10645 
10646 static SDValue PerformBFICombine(SDNode *N,
10647                                  TargetLowering::DAGCombinerInfo &DCI) {
10648   SDValue N1 = N->getOperand(1);
10649   if (N1.getOpcode() == ISD::AND) {
10650     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
10651     // the bits being cleared by the AND are not demanded by the BFI.
10652     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10653     if (!N11C)
10654       return SDValue();
10655     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10656     unsigned LSB = countTrailingZeros(~InvMask);
10657     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
10658     assert(Width <
10659                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
10660            "undefined behavior");
10661     unsigned Mask = (1u << Width) - 1;
10662     unsigned Mask2 = N11C->getZExtValue();
10663     if ((Mask & (~Mask2)) == 0)
10664       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
10665                              N->getOperand(0), N1.getOperand(0),
10666                              N->getOperand(2));
10667   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
10668     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
10669     // Keep track of any consecutive bits set that all come from the same base
10670     // value. We can combine these together into a single BFI.
10671     SDValue CombineBFI = FindBFIToCombineWith(N);
10672     if (CombineBFI == SDValue())
10673       return SDValue();
10674 
10675     // We've found a BFI.
10676     APInt ToMask1, FromMask1;
10677     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
10678 
10679     APInt ToMask2, FromMask2;
10680     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
10681     assert(From1 == From2);
10682     (void)From2;
10683 
10684     // First, unlink CombineBFI.
10685     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
10686     // Then create a new BFI, combining the two together.
10687     APInt NewFromMask = FromMask1 | FromMask2;
10688     APInt NewToMask = ToMask1 | ToMask2;
10689 
10690     EVT VT = N->getValueType(0);
10691     SDLoc dl(N);
10692 
10693     if (NewFromMask[0] == 0)
10694       From1 = DCI.DAG.getNode(
10695         ISD::SRL, dl, VT, From1,
10696         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
10697     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
10698                            DCI.DAG.getConstant(~NewToMask, dl, VT));
10699   }
10700   return SDValue();
10701 }
10702 
10703 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
10704 /// ARMISD::VMOVRRD.
10705 static SDValue PerformVMOVRRDCombine(SDNode *N,
10706                                      TargetLowering::DAGCombinerInfo &DCI,
10707                                      const ARMSubtarget *Subtarget) {
10708   // vmovrrd(vmovdrr x, y) -> x,y
10709   SDValue InDouble = N->getOperand(0);
10710   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
10711     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
10712 
10713   // vmovrrd(load f64) -> (load i32), (load i32)
10714   SDNode *InNode = InDouble.getNode();
10715   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
10716       InNode->getValueType(0) == MVT::f64 &&
10717       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
10718       !cast<LoadSDNode>(InNode)->isVolatile()) {
10719     // TODO: Should this be done for non-FrameIndex operands?
10720     LoadSDNode *LD = cast<LoadSDNode>(InNode);
10721 
10722     SelectionDAG &DAG = DCI.DAG;
10723     SDLoc DL(LD);
10724     SDValue BasePtr = LD->getBasePtr();
10725     SDValue NewLD1 =
10726         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
10727                     LD->getAlignment(), LD->getMemOperand()->getFlags());
10728 
10729     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
10730                                     DAG.getConstant(4, DL, MVT::i32));
10731     SDValue NewLD2 = DAG.getLoad(
10732         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
10733         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
10734 
10735     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
10736     if (DCI.DAG.getDataLayout().isBigEndian())
10737       std::swap (NewLD1, NewLD2);
10738     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
10739     return Result;
10740   }
10741 
10742   return SDValue();
10743 }
10744 
10745 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
10746 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
10747 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
10748   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
10749   SDValue Op0 = N->getOperand(0);
10750   SDValue Op1 = N->getOperand(1);
10751   if (Op0.getOpcode() == ISD::BITCAST)
10752     Op0 = Op0.getOperand(0);
10753   if (Op1.getOpcode() == ISD::BITCAST)
10754     Op1 = Op1.getOperand(0);
10755   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
10756       Op0.getNode() == Op1.getNode() &&
10757       Op0.getResNo() == 0 && Op1.getResNo() == 1)
10758     return DAG.getNode(ISD::BITCAST, SDLoc(N),
10759                        N->getValueType(0), Op0.getOperand(0));
10760   return SDValue();
10761 }
10762 
10763 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
10764 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
10765 /// i64 vector to have f64 elements, since the value can then be loaded
10766 /// directly into a VFP register.
10767 static bool hasNormalLoadOperand(SDNode *N) {
10768   unsigned NumElts = N->getValueType(0).getVectorNumElements();
10769   for (unsigned i = 0; i < NumElts; ++i) {
10770     SDNode *Elt = N->getOperand(i).getNode();
10771     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
10772       return true;
10773   }
10774   return false;
10775 }
10776 
10777 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
10778 /// ISD::BUILD_VECTOR.
10779 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
10780                                           TargetLowering::DAGCombinerInfo &DCI,
10781                                           const ARMSubtarget *Subtarget) {
10782   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
10783   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
10784   // into a pair of GPRs, which is fine when the value is used as a scalar,
10785   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
10786   SelectionDAG &DAG = DCI.DAG;
10787   if (N->getNumOperands() == 2)
10788     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
10789       return RV;
10790 
10791   // Load i64 elements as f64 values so that type legalization does not split
10792   // them up into i32 values.
10793   EVT VT = N->getValueType(0);
10794   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
10795     return SDValue();
10796   SDLoc dl(N);
10797   SmallVector<SDValue, 8> Ops;
10798   unsigned NumElts = VT.getVectorNumElements();
10799   for (unsigned i = 0; i < NumElts; ++i) {
10800     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
10801     Ops.push_back(V);
10802     // Make the DAGCombiner fold the bitcast.
10803     DCI.AddToWorklist(V.getNode());
10804   }
10805   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
10806   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
10807   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10808 }
10809 
10810 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
10811 static SDValue
10812 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
10813   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
10814   // At that time, we may have inserted bitcasts from integer to float.
10815   // If these bitcasts have survived DAGCombine, change the lowering of this
10816   // BUILD_VECTOR in something more vector friendly, i.e., that does not
10817   // force to use floating point types.
10818 
10819   // Make sure we can change the type of the vector.
10820   // This is possible iff:
10821   // 1. The vector is only used in a bitcast to a integer type. I.e.,
10822   //    1.1. Vector is used only once.
10823   //    1.2. Use is a bit convert to an integer type.
10824   // 2. The size of its operands are 32-bits (64-bits are not legal).
10825   EVT VT = N->getValueType(0);
10826   EVT EltVT = VT.getVectorElementType();
10827 
10828   // Check 1.1. and 2.
10829   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
10830     return SDValue();
10831 
10832   // By construction, the input type must be float.
10833   assert(EltVT == MVT::f32 && "Unexpected type!");
10834 
10835   // Check 1.2.
10836   SDNode *Use = *N->use_begin();
10837   if (Use->getOpcode() != ISD::BITCAST ||
10838       Use->getValueType(0).isFloatingPoint())
10839     return SDValue();
10840 
10841   // Check profitability.
10842   // Model is, if more than half of the relevant operands are bitcast from
10843   // i32, turn the build_vector into a sequence of insert_vector_elt.
10844   // Relevant operands are everything that is not statically
10845   // (i.e., at compile time) bitcasted.
10846   unsigned NumOfBitCastedElts = 0;
10847   unsigned NumElts = VT.getVectorNumElements();
10848   unsigned NumOfRelevantElts = NumElts;
10849   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
10850     SDValue Elt = N->getOperand(Idx);
10851     if (Elt->getOpcode() == ISD::BITCAST) {
10852       // Assume only bit cast to i32 will go away.
10853       if (Elt->getOperand(0).getValueType() == MVT::i32)
10854         ++NumOfBitCastedElts;
10855     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
10856       // Constants are statically casted, thus do not count them as
10857       // relevant operands.
10858       --NumOfRelevantElts;
10859   }
10860 
10861   // Check if more than half of the elements require a non-free bitcast.
10862   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
10863     return SDValue();
10864 
10865   SelectionDAG &DAG = DCI.DAG;
10866   // Create the new vector type.
10867   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
10868   // Check if the type is legal.
10869   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10870   if (!TLI.isTypeLegal(VecVT))
10871     return SDValue();
10872 
10873   // Combine:
10874   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
10875   // => BITCAST INSERT_VECTOR_ELT
10876   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
10877   //                      (BITCAST EN), N.
10878   SDValue Vec = DAG.getUNDEF(VecVT);
10879   SDLoc dl(N);
10880   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
10881     SDValue V = N->getOperand(Idx);
10882     if (V.isUndef())
10883       continue;
10884     if (V.getOpcode() == ISD::BITCAST &&
10885         V->getOperand(0).getValueType() == MVT::i32)
10886       // Fold obvious case.
10887       V = V.getOperand(0);
10888     else {
10889       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
10890       // Make the DAGCombiner fold the bitcasts.
10891       DCI.AddToWorklist(V.getNode());
10892     }
10893     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
10894     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
10895   }
10896   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
10897   // Make the DAGCombiner fold the bitcasts.
10898   DCI.AddToWorklist(Vec.getNode());
10899   return Vec;
10900 }
10901 
10902 /// PerformInsertEltCombine - Target-specific dag combine xforms for
10903 /// ISD::INSERT_VECTOR_ELT.
10904 static SDValue PerformInsertEltCombine(SDNode *N,
10905                                        TargetLowering::DAGCombinerInfo &DCI) {
10906   // Bitcast an i64 load inserted into a vector to f64.
10907   // Otherwise, the i64 value will be legalized to a pair of i32 values.
10908   EVT VT = N->getValueType(0);
10909   SDNode *Elt = N->getOperand(1).getNode();
10910   if (VT.getVectorElementType() != MVT::i64 ||
10911       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
10912     return SDValue();
10913 
10914   SelectionDAG &DAG = DCI.DAG;
10915   SDLoc dl(N);
10916   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
10917                                  VT.getVectorNumElements());
10918   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
10919   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
10920   // Make the DAGCombiner fold the bitcasts.
10921   DCI.AddToWorklist(Vec.getNode());
10922   DCI.AddToWorklist(V.getNode());
10923   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
10924                                Vec, V, N->getOperand(2));
10925   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
10926 }
10927 
10928 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
10929 /// ISD::VECTOR_SHUFFLE.
10930 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
10931   // The LLVM shufflevector instruction does not require the shuffle mask
10932   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
10933   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
10934   // operands do not match the mask length, they are extended by concatenating
10935   // them with undef vectors.  That is probably the right thing for other
10936   // targets, but for NEON it is better to concatenate two double-register
10937   // size vector operands into a single quad-register size vector.  Do that
10938   // transformation here:
10939   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
10940   //   shuffle(concat(v1, v2), undef)
10941   SDValue Op0 = N->getOperand(0);
10942   SDValue Op1 = N->getOperand(1);
10943   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
10944       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
10945       Op0.getNumOperands() != 2 ||
10946       Op1.getNumOperands() != 2)
10947     return SDValue();
10948   SDValue Concat0Op1 = Op0.getOperand(1);
10949   SDValue Concat1Op1 = Op1.getOperand(1);
10950   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
10951     return SDValue();
10952   // Skip the transformation if any of the types are illegal.
10953   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10954   EVT VT = N->getValueType(0);
10955   if (!TLI.isTypeLegal(VT) ||
10956       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
10957       !TLI.isTypeLegal(Concat1Op1.getValueType()))
10958     return SDValue();
10959 
10960   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10961                                   Op0.getOperand(0), Op1.getOperand(0));
10962   // Translate the shuffle mask.
10963   SmallVector<int, 16> NewMask;
10964   unsigned NumElts = VT.getVectorNumElements();
10965   unsigned HalfElts = NumElts/2;
10966   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10967   for (unsigned n = 0; n < NumElts; ++n) {
10968     int MaskElt = SVN->getMaskElt(n);
10969     int NewElt = -1;
10970     if (MaskElt < (int)HalfElts)
10971       NewElt = MaskElt;
10972     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
10973       NewElt = HalfElts + MaskElt - NumElts;
10974     NewMask.push_back(NewElt);
10975   }
10976   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
10977                               DAG.getUNDEF(VT), NewMask);
10978 }
10979 
10980 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
10981 /// NEON load/store intrinsics, and generic vector load/stores, to merge
10982 /// base address updates.
10983 /// For generic load/stores, the memory type is assumed to be a vector.
10984 /// The caller is assumed to have checked legality.
10985 static SDValue CombineBaseUpdate(SDNode *N,
10986                                  TargetLowering::DAGCombinerInfo &DCI) {
10987   SelectionDAG &DAG = DCI.DAG;
10988   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
10989                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
10990   const bool isStore = N->getOpcode() == ISD::STORE;
10991   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
10992   SDValue Addr = N->getOperand(AddrOpIdx);
10993   MemSDNode *MemN = cast<MemSDNode>(N);
10994   SDLoc dl(N);
10995 
10996   // Search for a use of the address operand that is an increment.
10997   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
10998          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
10999     SDNode *User = *UI;
11000     if (User->getOpcode() != ISD::ADD ||
11001         UI.getUse().getResNo() != Addr.getResNo())
11002       continue;
11003 
11004     // Check that the add is independent of the load/store.  Otherwise, folding
11005     // it would create a cycle.
11006     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
11007       continue;
11008 
11009     // Find the new opcode for the updating load/store.
11010     bool isLoadOp = true;
11011     bool isLaneOp = false;
11012     unsigned NewOpc = 0;
11013     unsigned NumVecs = 0;
11014     if (isIntrinsic) {
11015       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11016       switch (IntNo) {
11017       default: llvm_unreachable("unexpected intrinsic for Neon base update");
11018       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
11019         NumVecs = 1; break;
11020       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
11021         NumVecs = 2; break;
11022       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
11023         NumVecs = 3; break;
11024       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
11025         NumVecs = 4; break;
11026       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
11027         NumVecs = 2; isLaneOp = true; break;
11028       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
11029         NumVecs = 3; isLaneOp = true; break;
11030       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
11031         NumVecs = 4; isLaneOp = true; break;
11032       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
11033         NumVecs = 1; isLoadOp = false; break;
11034       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
11035         NumVecs = 2; isLoadOp = false; break;
11036       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
11037         NumVecs = 3; isLoadOp = false; break;
11038       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
11039         NumVecs = 4; isLoadOp = false; break;
11040       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
11041         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
11042       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
11043         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
11044       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
11045         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
11046       }
11047     } else {
11048       isLaneOp = true;
11049       switch (N->getOpcode()) {
11050       default: llvm_unreachable("unexpected opcode for Neon base update");
11051       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
11052       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
11053       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
11054       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
11055       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
11056         NumVecs = 1; isLaneOp = false; break;
11057       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
11058         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
11059       }
11060     }
11061 
11062     // Find the size of memory referenced by the load/store.
11063     EVT VecTy;
11064     if (isLoadOp) {
11065       VecTy = N->getValueType(0);
11066     } else if (isIntrinsic) {
11067       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
11068     } else {
11069       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
11070       VecTy = N->getOperand(1).getValueType();
11071     }
11072 
11073     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11074     if (isLaneOp)
11075       NumBytes /= VecTy.getVectorNumElements();
11076 
11077     // If the increment is a constant, it must match the memory ref size.
11078     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11079     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
11080     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
11081       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
11082       // separate instructions that make it harder to use a non-constant update.
11083       continue;
11084     }
11085 
11086     // OK, we found an ADD we can fold into the base update.
11087     // Now, create a _UPD node, taking care of not breaking alignment.
11088 
11089     EVT AlignedVecTy = VecTy;
11090     unsigned Alignment = MemN->getAlignment();
11091 
11092     // If this is a less-than-standard-aligned load/store, change the type to
11093     // match the standard alignment.
11094     // The alignment is overlooked when selecting _UPD variants; and it's
11095     // easier to introduce bitcasts here than fix that.
11096     // There are 3 ways to get to this base-update combine:
11097     // - intrinsics: they are assumed to be properly aligned (to the standard
11098     //   alignment of the memory type), so we don't need to do anything.
11099     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
11100     //   intrinsics, so, likewise, there's nothing to do.
11101     // - generic load/store instructions: the alignment is specified as an
11102     //   explicit operand, rather than implicitly as the standard alignment
11103     //   of the memory type (like the intrisics).  We need to change the
11104     //   memory type to match the explicit alignment.  That way, we don't
11105     //   generate non-standard-aligned ARMISD::VLDx nodes.
11106     if (isa<LSBaseSDNode>(N)) {
11107       if (Alignment == 0)
11108         Alignment = 1;
11109       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
11110         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
11111         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
11112         assert(!isLaneOp && "Unexpected generic load/store lane.");
11113         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
11114         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
11115       }
11116       // Don't set an explicit alignment on regular load/stores that we want
11117       // to transform to VLD/VST 1_UPD nodes.
11118       // This matches the behavior of regular load/stores, which only get an
11119       // explicit alignment if the MMO alignment is larger than the standard
11120       // alignment of the memory type.
11121       // Intrinsics, however, always get an explicit alignment, set to the
11122       // alignment of the MMO.
11123       Alignment = 1;
11124     }
11125 
11126     // Create the new updating load/store node.
11127     // First, create an SDVTList for the new updating node's results.
11128     EVT Tys[6];
11129     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
11130     unsigned n;
11131     for (n = 0; n < NumResultVecs; ++n)
11132       Tys[n] = AlignedVecTy;
11133     Tys[n++] = MVT::i32;
11134     Tys[n] = MVT::Other;
11135     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
11136 
11137     // Then, gather the new node's operands.
11138     SmallVector<SDValue, 8> Ops;
11139     Ops.push_back(N->getOperand(0)); // incoming chain
11140     Ops.push_back(N->getOperand(AddrOpIdx));
11141     Ops.push_back(Inc);
11142 
11143     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
11144       // Try to match the intrinsic's signature
11145       Ops.push_back(StN->getValue());
11146     } else {
11147       // Loads (and of course intrinsics) match the intrinsics' signature,
11148       // so just add all but the alignment operand.
11149       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
11150         Ops.push_back(N->getOperand(i));
11151     }
11152 
11153     // For all node types, the alignment operand is always the last one.
11154     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
11155 
11156     // If this is a non-standard-aligned STORE, the penultimate operand is the
11157     // stored value.  Bitcast it to the aligned type.
11158     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11159       SDValue &StVal = Ops[Ops.size()-2];
11160       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11161     }
11162 
11163     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11164     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11165                                            MemN->getMemOperand());
11166 
11167     // Update the uses.
11168     SmallVector<SDValue, 5> NewResults;
11169     for (unsigned i = 0; i < NumResultVecs; ++i)
11170       NewResults.push_back(SDValue(UpdN.getNode(), i));
11171 
11172     // If this is an non-standard-aligned LOAD, the first result is the loaded
11173     // value.  Bitcast it to the expected result type.
11174     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11175       SDValue &LdVal = NewResults[0];
11176       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11177     }
11178 
11179     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11180     DCI.CombineTo(N, NewResults);
11181     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11182 
11183     break;
11184   }
11185   return SDValue();
11186 }
11187 
11188 static SDValue PerformVLDCombine(SDNode *N,
11189                                  TargetLowering::DAGCombinerInfo &DCI) {
11190   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11191     return SDValue();
11192 
11193   return CombineBaseUpdate(N, DCI);
11194 }
11195 
11196 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11197 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11198 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
11199 /// return true.
11200 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11201   SelectionDAG &DAG = DCI.DAG;
11202   EVT VT = N->getValueType(0);
11203   // vldN-dup instructions only support 64-bit vectors for N > 1.
11204   if (!VT.is64BitVector())
11205     return false;
11206 
11207   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11208   SDNode *VLD = N->getOperand(0).getNode();
11209   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11210     return false;
11211   unsigned NumVecs = 0;
11212   unsigned NewOpc = 0;
11213   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11214   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11215     NumVecs = 2;
11216     NewOpc = ARMISD::VLD2DUP;
11217   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11218     NumVecs = 3;
11219     NewOpc = ARMISD::VLD3DUP;
11220   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11221     NumVecs = 4;
11222     NewOpc = ARMISD::VLD4DUP;
11223   } else {
11224     return false;
11225   }
11226 
11227   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11228   // numbers match the load.
11229   unsigned VLDLaneNo =
11230     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11231   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11232        UI != UE; ++UI) {
11233     // Ignore uses of the chain result.
11234     if (UI.getUse().getResNo() == NumVecs)
11235       continue;
11236     SDNode *User = *UI;
11237     if (User->getOpcode() != ARMISD::VDUPLANE ||
11238         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11239       return false;
11240   }
11241 
11242   // Create the vldN-dup node.
11243   EVT Tys[5];
11244   unsigned n;
11245   for (n = 0; n < NumVecs; ++n)
11246     Tys[n] = VT;
11247   Tys[n] = MVT::Other;
11248   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11249   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11250   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11251   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11252                                            Ops, VLDMemInt->getMemoryVT(),
11253                                            VLDMemInt->getMemOperand());
11254 
11255   // Update the uses.
11256   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11257        UI != UE; ++UI) {
11258     unsigned ResNo = UI.getUse().getResNo();
11259     // Ignore uses of the chain result.
11260     if (ResNo == NumVecs)
11261       continue;
11262     SDNode *User = *UI;
11263     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11264   }
11265 
11266   // Now the vldN-lane intrinsic is dead except for its chain result.
11267   // Update uses of the chain.
11268   std::vector<SDValue> VLDDupResults;
11269   for (unsigned n = 0; n < NumVecs; ++n)
11270     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11271   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11272   DCI.CombineTo(VLD, VLDDupResults);
11273 
11274   return true;
11275 }
11276 
11277 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11278 /// ARMISD::VDUPLANE.
11279 static SDValue PerformVDUPLANECombine(SDNode *N,
11280                                       TargetLowering::DAGCombinerInfo &DCI) {
11281   SDValue Op = N->getOperand(0);
11282 
11283   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11284   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11285   if (CombineVLDDUP(N, DCI))
11286     return SDValue(N, 0);
11287 
11288   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11289   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11290   while (Op.getOpcode() == ISD::BITCAST)
11291     Op = Op.getOperand(0);
11292   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11293     return SDValue();
11294 
11295   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11296   unsigned EltSize = Op.getScalarValueSizeInBits();
11297   // The canonical VMOV for a zero vector uses a 32-bit element size.
11298   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11299   unsigned EltBits;
11300   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11301     EltSize = 8;
11302   EVT VT = N->getValueType(0);
11303   if (EltSize > VT.getScalarSizeInBits())
11304     return SDValue();
11305 
11306   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11307 }
11308 
11309 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11310 static SDValue PerformVDUPCombine(SDNode *N,
11311                                   TargetLowering::DAGCombinerInfo &DCI) {
11312   SelectionDAG &DAG = DCI.DAG;
11313   SDValue Op = N->getOperand(0);
11314 
11315   // Match VDUP(LOAD) -> VLD1DUP.
11316   // We match this pattern here rather than waiting for isel because the
11317   // transform is only legal for unindexed loads.
11318   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11319   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11320       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11321     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11322                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11323     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11324     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11325                                              Ops, LD->getMemoryVT(),
11326                                              LD->getMemOperand());
11327     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11328     return VLDDup;
11329   }
11330 
11331   return SDValue();
11332 }
11333 
11334 static SDValue PerformLOADCombine(SDNode *N,
11335                                   TargetLowering::DAGCombinerInfo &DCI) {
11336   EVT VT = N->getValueType(0);
11337 
11338   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11339   if (ISD::isNormalLoad(N) && VT.isVector() &&
11340       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11341     return CombineBaseUpdate(N, DCI);
11342 
11343   return SDValue();
11344 }
11345 
11346 /// PerformSTORECombine - Target-specific dag combine xforms for
11347 /// ISD::STORE.
11348 static SDValue PerformSTORECombine(SDNode *N,
11349                                    TargetLowering::DAGCombinerInfo &DCI) {
11350   StoreSDNode *St = cast<StoreSDNode>(N);
11351   if (St->isVolatile())
11352     return SDValue();
11353 
11354   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11355   // pack all of the elements in one place.  Next, store to memory in fewer
11356   // chunks.
11357   SDValue StVal = St->getValue();
11358   EVT VT = StVal.getValueType();
11359   if (St->isTruncatingStore() && VT.isVector()) {
11360     SelectionDAG &DAG = DCI.DAG;
11361     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11362     EVT StVT = St->getMemoryVT();
11363     unsigned NumElems = VT.getVectorNumElements();
11364     assert(StVT != VT && "Cannot truncate to the same type");
11365     unsigned FromEltSz = VT.getScalarSizeInBits();
11366     unsigned ToEltSz = StVT.getScalarSizeInBits();
11367 
11368     // From, To sizes and ElemCount must be pow of two
11369     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11370 
11371     // We are going to use the original vector elt for storing.
11372     // Accumulated smaller vector elements must be a multiple of the store size.
11373     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11374 
11375     unsigned SizeRatio  = FromEltSz / ToEltSz;
11376     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11377 
11378     // Create a type on which we perform the shuffle.
11379     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11380                                      NumElems*SizeRatio);
11381     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11382 
11383     SDLoc DL(St);
11384     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11385     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11386     for (unsigned i = 0; i < NumElems; ++i)
11387       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11388                           ? (i + 1) * SizeRatio - 1
11389                           : i * SizeRatio;
11390 
11391     // Can't shuffle using an illegal type.
11392     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11393 
11394     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11395                                 DAG.getUNDEF(WideVec.getValueType()),
11396                                 ShuffleVec);
11397     // At this point all of the data is stored at the bottom of the
11398     // register. We now need to save it to mem.
11399 
11400     // Find the largest store unit
11401     MVT StoreType = MVT::i8;
11402     for (MVT Tp : MVT::integer_valuetypes()) {
11403       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11404         StoreType = Tp;
11405     }
11406     // Didn't find a legal store type.
11407     if (!TLI.isTypeLegal(StoreType))
11408       return SDValue();
11409 
11410     // Bitcast the original vector into a vector of store-size units
11411     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11412             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11413     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11414     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11415     SmallVector<SDValue, 8> Chains;
11416     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11417                                         TLI.getPointerTy(DAG.getDataLayout()));
11418     SDValue BasePtr = St->getBasePtr();
11419 
11420     // Perform one or more big stores into memory.
11421     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11422     for (unsigned I = 0; I < E; I++) {
11423       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11424                                    StoreType, ShuffWide,
11425                                    DAG.getIntPtrConstant(I, DL));
11426       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
11427                                 St->getPointerInfo(), St->getAlignment(),
11428                                 St->getMemOperand()->getFlags());
11429       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
11430                             Increment);
11431       Chains.push_back(Ch);
11432     }
11433     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11434   }
11435 
11436   if (!ISD::isNormalStore(St))
11437     return SDValue();
11438 
11439   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
11440   // ARM stores of arguments in the same cache line.
11441   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
11442       StVal.getNode()->hasOneUse()) {
11443     SelectionDAG  &DAG = DCI.DAG;
11444     bool isBigEndian = DAG.getDataLayout().isBigEndian();
11445     SDLoc DL(St);
11446     SDValue BasePtr = St->getBasePtr();
11447     SDValue NewST1 = DAG.getStore(
11448         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
11449         BasePtr, St->getPointerInfo(), St->getAlignment(),
11450         St->getMemOperand()->getFlags());
11451 
11452     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11453                                     DAG.getConstant(4, DL, MVT::i32));
11454     return DAG.getStore(NewST1.getValue(0), DL,
11455                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
11456                         OffsetPtr, St->getPointerInfo(),
11457                         std::min(4U, St->getAlignment() / 2),
11458                         St->getMemOperand()->getFlags());
11459   }
11460 
11461   if (StVal.getValueType() == MVT::i64 &&
11462       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11463 
11464     // Bitcast an i64 store extracted from a vector to f64.
11465     // Otherwise, the i64 value will be legalized to a pair of i32 values.
11466     SelectionDAG &DAG = DCI.DAG;
11467     SDLoc dl(StVal);
11468     SDValue IntVec = StVal.getOperand(0);
11469     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11470                                    IntVec.getValueType().getVectorNumElements());
11471     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
11472     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11473                                  Vec, StVal.getOperand(1));
11474     dl = SDLoc(N);
11475     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
11476     // Make the DAGCombiner fold the bitcasts.
11477     DCI.AddToWorklist(Vec.getNode());
11478     DCI.AddToWorklist(ExtElt.getNode());
11479     DCI.AddToWorklist(V.getNode());
11480     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
11481                         St->getPointerInfo(), St->getAlignment(),
11482                         St->getMemOperand()->getFlags(), St->getAAInfo());
11483   }
11484 
11485   // If this is a legal vector store, try to combine it into a VST1_UPD.
11486   if (ISD::isNormalStore(N) && VT.isVector() &&
11487       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11488     return CombineBaseUpdate(N, DCI);
11489 
11490   return SDValue();
11491 }
11492 
11493 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11494 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11495 /// when the VMUL has a constant operand that is a power of 2.
11496 ///
11497 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11498 ///  vmul.f32        d16, d17, d16
11499 ///  vcvt.s32.f32    d16, d16
11500 /// becomes:
11501 ///  vcvt.s32.f32    d16, d16, #3
11502 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11503                                   const ARMSubtarget *Subtarget) {
11504   if (!Subtarget->hasNEON())
11505     return SDValue();
11506 
11507   SDValue Op = N->getOperand(0);
11508   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11509       Op.getOpcode() != ISD::FMUL)
11510     return SDValue();
11511 
11512   SDValue ConstVec = Op->getOperand(1);
11513   if (!isa<BuildVectorSDNode>(ConstVec))
11514     return SDValue();
11515 
11516   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11517   uint32_t FloatBits = FloatTy.getSizeInBits();
11518   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11519   uint32_t IntBits = IntTy.getSizeInBits();
11520   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11521   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11522     // These instructions only exist converting from f32 to i32. We can handle
11523     // smaller integers by generating an extra truncate, but larger ones would
11524     // be lossy. We also can't handle more then 4 lanes, since these intructions
11525     // only support v2i32/v4i32 types.
11526     return SDValue();
11527   }
11528 
11529   BitVector UndefElements;
11530   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11531   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11532   if (C == -1 || C == 0 || C > 32)
11533     return SDValue();
11534 
11535   SDLoc dl(N);
11536   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
11537   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
11538     Intrinsic::arm_neon_vcvtfp2fxu;
11539   SDValue FixConv = DAG.getNode(
11540       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11541       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
11542       DAG.getConstant(C, dl, MVT::i32));
11543 
11544   if (IntBits < FloatBits)
11545     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
11546 
11547   return FixConv;
11548 }
11549 
11550 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
11551 /// can replace combinations of VCVT (integer to floating-point) and VDIV
11552 /// when the VDIV has a constant operand that is a power of 2.
11553 ///
11554 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11555 ///  vcvt.f32.s32    d16, d16
11556 ///  vdiv.f32        d16, d17, d16
11557 /// becomes:
11558 ///  vcvt.f32.s32    d16, d16, #3
11559 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
11560                                   const ARMSubtarget *Subtarget) {
11561   if (!Subtarget->hasNEON())
11562     return SDValue();
11563 
11564   SDValue Op = N->getOperand(0);
11565   unsigned OpOpcode = Op.getNode()->getOpcode();
11566   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
11567       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
11568     return SDValue();
11569 
11570   SDValue ConstVec = N->getOperand(1);
11571   if (!isa<BuildVectorSDNode>(ConstVec))
11572     return SDValue();
11573 
11574   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11575   uint32_t FloatBits = FloatTy.getSizeInBits();
11576   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11577   uint32_t IntBits = IntTy.getSizeInBits();
11578   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11579   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11580     // These instructions only exist converting from i32 to f32. We can handle
11581     // smaller integers by generating an extra extend, but larger ones would
11582     // be lossy. We also can't handle more then 4 lanes, since these intructions
11583     // only support v2i32/v4i32 types.
11584     return SDValue();
11585   }
11586 
11587   BitVector UndefElements;
11588   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11589   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11590   if (C == -1 || C == 0 || C > 32)
11591     return SDValue();
11592 
11593   SDLoc dl(N);
11594   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
11595   SDValue ConvInput = Op.getOperand(0);
11596   if (IntBits < FloatBits)
11597     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
11598                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11599                             ConvInput);
11600 
11601   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
11602     Intrinsic::arm_neon_vcvtfxu2fp;
11603   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
11604                      Op.getValueType(),
11605                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
11606                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
11607 }
11608 
11609 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
11610 /// operand of a vector shift operation, where all the elements of the
11611 /// build_vector must have the same constant integer value.
11612 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
11613   // Ignore bit_converts.
11614   while (Op.getOpcode() == ISD::BITCAST)
11615     Op = Op.getOperand(0);
11616   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
11617   APInt SplatBits, SplatUndef;
11618   unsigned SplatBitSize;
11619   bool HasAnyUndefs;
11620   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
11621                                       HasAnyUndefs, ElementBits) ||
11622       SplatBitSize > ElementBits)
11623     return false;
11624   Cnt = SplatBits.getSExtValue();
11625   return true;
11626 }
11627 
11628 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
11629 /// operand of a vector shift left operation.  That value must be in the range:
11630 ///   0 <= Value < ElementBits for a left shift; or
11631 ///   0 <= Value <= ElementBits for a long left shift.
11632 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
11633   assert(VT.isVector() && "vector shift count is not a vector type");
11634   int64_t ElementBits = VT.getScalarSizeInBits();
11635   if (! getVShiftImm(Op, ElementBits, Cnt))
11636     return false;
11637   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
11638 }
11639 
11640 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
11641 /// operand of a vector shift right operation.  For a shift opcode, the value
11642 /// is positive, but for an intrinsic the value count must be negative. The
11643 /// absolute value must be in the range:
11644 ///   1 <= |Value| <= ElementBits for a right shift; or
11645 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
11646 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
11647                          int64_t &Cnt) {
11648   assert(VT.isVector() && "vector shift count is not a vector type");
11649   int64_t ElementBits = VT.getScalarSizeInBits();
11650   if (! getVShiftImm(Op, ElementBits, Cnt))
11651     return false;
11652   if (!isIntrinsic)
11653     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
11654   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
11655     Cnt = -Cnt;
11656     return true;
11657   }
11658   return false;
11659 }
11660 
11661 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
11662 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
11663   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11664   switch (IntNo) {
11665   default:
11666     // Don't do anything for most intrinsics.
11667     break;
11668 
11669   // Vector shifts: check for immediate versions and lower them.
11670   // Note: This is done during DAG combining instead of DAG legalizing because
11671   // the build_vectors for 64-bit vector element shift counts are generally
11672   // not legal, and it is hard to see their values after they get legalized to
11673   // loads from a constant pool.
11674   case Intrinsic::arm_neon_vshifts:
11675   case Intrinsic::arm_neon_vshiftu:
11676   case Intrinsic::arm_neon_vrshifts:
11677   case Intrinsic::arm_neon_vrshiftu:
11678   case Intrinsic::arm_neon_vrshiftn:
11679   case Intrinsic::arm_neon_vqshifts:
11680   case Intrinsic::arm_neon_vqshiftu:
11681   case Intrinsic::arm_neon_vqshiftsu:
11682   case Intrinsic::arm_neon_vqshiftns:
11683   case Intrinsic::arm_neon_vqshiftnu:
11684   case Intrinsic::arm_neon_vqshiftnsu:
11685   case Intrinsic::arm_neon_vqrshiftns:
11686   case Intrinsic::arm_neon_vqrshiftnu:
11687   case Intrinsic::arm_neon_vqrshiftnsu: {
11688     EVT VT = N->getOperand(1).getValueType();
11689     int64_t Cnt;
11690     unsigned VShiftOpc = 0;
11691 
11692     switch (IntNo) {
11693     case Intrinsic::arm_neon_vshifts:
11694     case Intrinsic::arm_neon_vshiftu:
11695       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
11696         VShiftOpc = ARMISD::VSHL;
11697         break;
11698       }
11699       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
11700         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
11701                      ARMISD::VSHRs : ARMISD::VSHRu);
11702         break;
11703       }
11704       return SDValue();
11705 
11706     case Intrinsic::arm_neon_vrshifts:
11707     case Intrinsic::arm_neon_vrshiftu:
11708       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
11709         break;
11710       return SDValue();
11711 
11712     case Intrinsic::arm_neon_vqshifts:
11713     case Intrinsic::arm_neon_vqshiftu:
11714       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11715         break;
11716       return SDValue();
11717 
11718     case Intrinsic::arm_neon_vqshiftsu:
11719       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11720         break;
11721       llvm_unreachable("invalid shift count for vqshlu intrinsic");
11722 
11723     case Intrinsic::arm_neon_vrshiftn:
11724     case Intrinsic::arm_neon_vqshiftns:
11725     case Intrinsic::arm_neon_vqshiftnu:
11726     case Intrinsic::arm_neon_vqshiftnsu:
11727     case Intrinsic::arm_neon_vqrshiftns:
11728     case Intrinsic::arm_neon_vqrshiftnu:
11729     case Intrinsic::arm_neon_vqrshiftnsu:
11730       // Narrowing shifts require an immediate right shift.
11731       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
11732         break;
11733       llvm_unreachable("invalid shift count for narrowing vector shift "
11734                        "intrinsic");
11735 
11736     default:
11737       llvm_unreachable("unhandled vector shift");
11738     }
11739 
11740     switch (IntNo) {
11741     case Intrinsic::arm_neon_vshifts:
11742     case Intrinsic::arm_neon_vshiftu:
11743       // Opcode already set above.
11744       break;
11745     case Intrinsic::arm_neon_vrshifts:
11746       VShiftOpc = ARMISD::VRSHRs; break;
11747     case Intrinsic::arm_neon_vrshiftu:
11748       VShiftOpc = ARMISD::VRSHRu; break;
11749     case Intrinsic::arm_neon_vrshiftn:
11750       VShiftOpc = ARMISD::VRSHRN; break;
11751     case Intrinsic::arm_neon_vqshifts:
11752       VShiftOpc = ARMISD::VQSHLs; break;
11753     case Intrinsic::arm_neon_vqshiftu:
11754       VShiftOpc = ARMISD::VQSHLu; break;
11755     case Intrinsic::arm_neon_vqshiftsu:
11756       VShiftOpc = ARMISD::VQSHLsu; break;
11757     case Intrinsic::arm_neon_vqshiftns:
11758       VShiftOpc = ARMISD::VQSHRNs; break;
11759     case Intrinsic::arm_neon_vqshiftnu:
11760       VShiftOpc = ARMISD::VQSHRNu; break;
11761     case Intrinsic::arm_neon_vqshiftnsu:
11762       VShiftOpc = ARMISD::VQSHRNsu; break;
11763     case Intrinsic::arm_neon_vqrshiftns:
11764       VShiftOpc = ARMISD::VQRSHRNs; break;
11765     case Intrinsic::arm_neon_vqrshiftnu:
11766       VShiftOpc = ARMISD::VQRSHRNu; break;
11767     case Intrinsic::arm_neon_vqrshiftnsu:
11768       VShiftOpc = ARMISD::VQRSHRNsu; break;
11769     }
11770 
11771     SDLoc dl(N);
11772     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11773                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
11774   }
11775 
11776   case Intrinsic::arm_neon_vshiftins: {
11777     EVT VT = N->getOperand(1).getValueType();
11778     int64_t Cnt;
11779     unsigned VShiftOpc = 0;
11780 
11781     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
11782       VShiftOpc = ARMISD::VSLI;
11783     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
11784       VShiftOpc = ARMISD::VSRI;
11785     else {
11786       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
11787     }
11788 
11789     SDLoc dl(N);
11790     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
11791                        N->getOperand(1), N->getOperand(2),
11792                        DAG.getConstant(Cnt, dl, MVT::i32));
11793   }
11794 
11795   case Intrinsic::arm_neon_vqrshifts:
11796   case Intrinsic::arm_neon_vqrshiftu:
11797     // No immediate versions of these to check for.
11798     break;
11799   }
11800 
11801   return SDValue();
11802 }
11803 
11804 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
11805 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
11806 /// combining instead of DAG legalizing because the build_vectors for 64-bit
11807 /// vector element shift counts are generally not legal, and it is hard to see
11808 /// their values after they get legalized to loads from a constant pool.
11809 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
11810                                    const ARMSubtarget *ST) {
11811   EVT VT = N->getValueType(0);
11812   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
11813     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
11814     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
11815     SDValue N1 = N->getOperand(1);
11816     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
11817       SDValue N0 = N->getOperand(0);
11818       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
11819           DAG.MaskedValueIsZero(N0.getOperand(0),
11820                                 APInt::getHighBitsSet(32, 16)))
11821         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
11822     }
11823   }
11824 
11825   // Nothing to be done for scalar shifts.
11826   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11827   if (!VT.isVector() || !TLI.isTypeLegal(VT))
11828     return SDValue();
11829 
11830   assert(ST->hasNEON() && "unexpected vector shift");
11831   int64_t Cnt;
11832 
11833   switch (N->getOpcode()) {
11834   default: llvm_unreachable("unexpected shift opcode");
11835 
11836   case ISD::SHL:
11837     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
11838       SDLoc dl(N);
11839       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
11840                          DAG.getConstant(Cnt, dl, MVT::i32));
11841     }
11842     break;
11843 
11844   case ISD::SRA:
11845   case ISD::SRL:
11846     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
11847       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
11848                             ARMISD::VSHRs : ARMISD::VSHRu);
11849       SDLoc dl(N);
11850       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
11851                          DAG.getConstant(Cnt, dl, MVT::i32));
11852     }
11853   }
11854   return SDValue();
11855 }
11856 
11857 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
11858 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
11859 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
11860                                     const ARMSubtarget *ST) {
11861   SDValue N0 = N->getOperand(0);
11862 
11863   // Check for sign- and zero-extensions of vector extract operations of 8-
11864   // and 16-bit vector elements.  NEON supports these directly.  They are
11865   // handled during DAG combining because type legalization will promote them
11866   // to 32-bit types and it is messy to recognize the operations after that.
11867   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11868     SDValue Vec = N0.getOperand(0);
11869     SDValue Lane = N0.getOperand(1);
11870     EVT VT = N->getValueType(0);
11871     EVT EltVT = N0.getValueType();
11872     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11873 
11874     if (VT == MVT::i32 &&
11875         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
11876         TLI.isTypeLegal(Vec.getValueType()) &&
11877         isa<ConstantSDNode>(Lane)) {
11878 
11879       unsigned Opc = 0;
11880       switch (N->getOpcode()) {
11881       default: llvm_unreachable("unexpected opcode");
11882       case ISD::SIGN_EXTEND:
11883         Opc = ARMISD::VGETLANEs;
11884         break;
11885       case ISD::ZERO_EXTEND:
11886       case ISD::ANY_EXTEND:
11887         Opc = ARMISD::VGETLANEu;
11888         break;
11889       }
11890       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
11891     }
11892   }
11893 
11894   return SDValue();
11895 }
11896 
11897 static const APInt *isPowerOf2Constant(SDValue V) {
11898   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11899   if (!C)
11900     return nullptr;
11901   const APInt *CV = &C->getAPIntValue();
11902   return CV->isPowerOf2() ? CV : nullptr;
11903 }
11904 
11905 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
11906   // If we have a CMOV, OR and AND combination such as:
11907   //   if (x & CN)
11908   //     y |= CM;
11909   //
11910   // And:
11911   //   * CN is a single bit;
11912   //   * All bits covered by CM are known zero in y
11913   //
11914   // Then we can convert this into a sequence of BFI instructions. This will
11915   // always be a win if CM is a single bit, will always be no worse than the
11916   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
11917   // three bits (due to the extra IT instruction).
11918 
11919   SDValue Op0 = CMOV->getOperand(0);
11920   SDValue Op1 = CMOV->getOperand(1);
11921   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
11922   auto CC = CCNode->getAPIntValue().getLimitedValue();
11923   SDValue CmpZ = CMOV->getOperand(4);
11924 
11925   // The compare must be against zero.
11926   if (!isNullConstant(CmpZ->getOperand(1)))
11927     return SDValue();
11928 
11929   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
11930   SDValue And = CmpZ->getOperand(0);
11931   if (And->getOpcode() != ISD::AND)
11932     return SDValue();
11933   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
11934   if (!AndC)
11935     return SDValue();
11936   SDValue X = And->getOperand(0);
11937 
11938   if (CC == ARMCC::EQ) {
11939     // We're performing an "equal to zero" compare. Swap the operands so we
11940     // canonicalize on a "not equal to zero" compare.
11941     std::swap(Op0, Op1);
11942   } else {
11943     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
11944   }
11945 
11946   if (Op1->getOpcode() != ISD::OR)
11947     return SDValue();
11948 
11949   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
11950   if (!OrC)
11951     return SDValue();
11952   SDValue Y = Op1->getOperand(0);
11953 
11954   if (Op0 != Y)
11955     return SDValue();
11956 
11957   // Now, is it profitable to continue?
11958   APInt OrCI = OrC->getAPIntValue();
11959   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
11960   if (OrCI.countPopulation() > Heuristic)
11961     return SDValue();
11962 
11963   // Lastly, can we determine that the bits defined by OrCI
11964   // are zero in Y?
11965   KnownBits Known;
11966   DAG.computeKnownBits(Y, Known);
11967   if ((OrCI & Known.Zero) != OrCI)
11968     return SDValue();
11969 
11970   // OK, we can do the combine.
11971   SDValue V = Y;
11972   SDLoc dl(X);
11973   EVT VT = X.getValueType();
11974   unsigned BitInX = AndC->logBase2();
11975 
11976   if (BitInX != 0) {
11977     // We must shift X first.
11978     X = DAG.getNode(ISD::SRL, dl, VT, X,
11979                     DAG.getConstant(BitInX, dl, VT));
11980   }
11981 
11982   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
11983        BitInY < NumActiveBits; ++BitInY) {
11984     if (OrCI[BitInY] == 0)
11985       continue;
11986     APInt Mask(VT.getSizeInBits(), 0);
11987     Mask.setBit(BitInY);
11988     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
11989                     // Confusingly, the operand is an *inverted* mask.
11990                     DAG.getConstant(~Mask, dl, VT));
11991   }
11992 
11993   return V;
11994 }
11995 
11996 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
11997 SDValue
11998 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
11999   SDValue Cmp = N->getOperand(4);
12000   if (Cmp.getOpcode() != ARMISD::CMPZ)
12001     // Only looking at NE cases.
12002     return SDValue();
12003 
12004   EVT VT = N->getValueType(0);
12005   SDLoc dl(N);
12006   SDValue LHS = Cmp.getOperand(0);
12007   SDValue RHS = Cmp.getOperand(1);
12008   SDValue Chain = N->getOperand(0);
12009   SDValue BB = N->getOperand(1);
12010   SDValue ARMcc = N->getOperand(2);
12011   ARMCC::CondCodes CC =
12012     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12013 
12014   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
12015   // -> (brcond Chain BB CC CPSR Cmp)
12016   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
12017       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
12018       LHS->getOperand(0)->hasOneUse()) {
12019     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
12020     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
12021     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12022     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12023     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
12024         (LHS01C && LHS01C->getZExtValue() == 1) &&
12025         (LHS1C && LHS1C->getZExtValue() == 1) &&
12026         (RHSC && RHSC->getZExtValue() == 0)) {
12027       return DAG.getNode(
12028           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
12029           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
12030     }
12031   }
12032 
12033   return SDValue();
12034 }
12035 
12036 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
12037 SDValue
12038 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
12039   SDValue Cmp = N->getOperand(4);
12040   if (Cmp.getOpcode() != ARMISD::CMPZ)
12041     // Only looking at EQ and NE cases.
12042     return SDValue();
12043 
12044   EVT VT = N->getValueType(0);
12045   SDLoc dl(N);
12046   SDValue LHS = Cmp.getOperand(0);
12047   SDValue RHS = Cmp.getOperand(1);
12048   SDValue FalseVal = N->getOperand(0);
12049   SDValue TrueVal = N->getOperand(1);
12050   SDValue ARMcc = N->getOperand(2);
12051   ARMCC::CondCodes CC =
12052     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12053 
12054   // BFI is only available on V6T2+.
12055   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
12056     SDValue R = PerformCMOVToBFICombine(N, DAG);
12057     if (R)
12058       return R;
12059   }
12060 
12061   // Simplify
12062   //   mov     r1, r0
12063   //   cmp     r1, x
12064   //   mov     r0, y
12065   //   moveq   r0, x
12066   // to
12067   //   cmp     r0, x
12068   //   movne   r0, y
12069   //
12070   //   mov     r1, r0
12071   //   cmp     r1, x
12072   //   mov     r0, x
12073   //   movne   r0, y
12074   // to
12075   //   cmp     r0, x
12076   //   movne   r0, y
12077   /// FIXME: Turn this into a target neutral optimization?
12078   SDValue Res;
12079   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
12080     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
12081                       N->getOperand(3), Cmp);
12082   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
12083     SDValue ARMcc;
12084     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
12085     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
12086                       N->getOperand(3), NewCmp);
12087   }
12088 
12089   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
12090   // -> (cmov F T CC CPSR Cmp)
12091   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
12092     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
12093     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12094     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12095     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
12096         (LHS1C && LHS1C->getZExtValue() == 1) &&
12097         (RHSC && RHSC->getZExtValue() == 0)) {
12098       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
12099                          LHS->getOperand(2), LHS->getOperand(3),
12100                          LHS->getOperand(4));
12101     }
12102   }
12103 
12104   if (Res.getNode()) {
12105     KnownBits Known;
12106     DAG.computeKnownBits(SDValue(N,0), Known);
12107     // Capture demanded bits information that would be otherwise lost.
12108     if (Known.Zero == 0xfffffffe)
12109       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12110                         DAG.getValueType(MVT::i1));
12111     else if (Known.Zero == 0xffffff00)
12112       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12113                         DAG.getValueType(MVT::i8));
12114     else if (Known.Zero == 0xffff0000)
12115       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12116                         DAG.getValueType(MVT::i16));
12117   }
12118 
12119   return Res;
12120 }
12121 
12122 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
12123                                              DAGCombinerInfo &DCI) const {
12124   switch (N->getOpcode()) {
12125   default: break;
12126   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
12127   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
12128   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
12129   case ISD::SUB:        return PerformSUBCombine(N, DCI);
12130   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
12131   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
12132   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
12133   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
12134   case ARMISD::ADDC:
12135   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
12136   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI.DAG, Subtarget);
12137   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
12138   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
12139   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
12140   case ISD::STORE:      return PerformSTORECombine(N, DCI);
12141   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
12142   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
12143   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
12144   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
12145   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
12146   case ISD::FP_TO_SINT:
12147   case ISD::FP_TO_UINT:
12148     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
12149   case ISD::FDIV:
12150     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
12151   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
12152   case ISD::SHL:
12153   case ISD::SRA:
12154   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
12155   case ISD::SIGN_EXTEND:
12156   case ISD::ZERO_EXTEND:
12157   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
12158   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
12159   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
12160   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
12161   case ARMISD::VLD1DUP:
12162   case ARMISD::VLD2DUP:
12163   case ARMISD::VLD3DUP:
12164   case ARMISD::VLD4DUP:
12165     return PerformVLDCombine(N, DCI);
12166   case ARMISD::BUILD_VECTOR:
12167     return PerformARMBUILD_VECTORCombine(N, DCI);
12168   case ARMISD::SMULWB: {
12169     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12170     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12171     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12172       return SDValue();
12173     break;
12174   }
12175   case ARMISD::SMULWT: {
12176     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12177     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12178     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12179       return SDValue();
12180     break;
12181   }
12182   case ARMISD::SMLALBB: {
12183     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12184     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12185     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12186         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12187       return SDValue();
12188     break;
12189   }
12190   case ARMISD::SMLALBT: {
12191     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12192     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12193     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12194     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12195     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12196         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12197       return SDValue();
12198     break;
12199   }
12200   case ARMISD::SMLALTB: {
12201     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12202     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12203     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12204     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12205     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12206         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12207       return SDValue();
12208     break;
12209   }
12210   case ARMISD::SMLALTT: {
12211     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12212     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12213     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12214         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12215       return SDValue();
12216     break;
12217   }
12218   case ISD::INTRINSIC_VOID:
12219   case ISD::INTRINSIC_W_CHAIN:
12220     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12221     case Intrinsic::arm_neon_vld1:
12222     case Intrinsic::arm_neon_vld2:
12223     case Intrinsic::arm_neon_vld3:
12224     case Intrinsic::arm_neon_vld4:
12225     case Intrinsic::arm_neon_vld2lane:
12226     case Intrinsic::arm_neon_vld3lane:
12227     case Intrinsic::arm_neon_vld4lane:
12228     case Intrinsic::arm_neon_vst1:
12229     case Intrinsic::arm_neon_vst2:
12230     case Intrinsic::arm_neon_vst3:
12231     case Intrinsic::arm_neon_vst4:
12232     case Intrinsic::arm_neon_vst2lane:
12233     case Intrinsic::arm_neon_vst3lane:
12234     case Intrinsic::arm_neon_vst4lane:
12235       return PerformVLDCombine(N, DCI);
12236     default: break;
12237     }
12238     break;
12239   }
12240   return SDValue();
12241 }
12242 
12243 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12244                                                           EVT VT) const {
12245   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12246 }
12247 
12248 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12249                                                        unsigned,
12250                                                        unsigned,
12251                                                        bool *Fast) const {
12252   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12253   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12254 
12255   switch (VT.getSimpleVT().SimpleTy) {
12256   default:
12257     return false;
12258   case MVT::i8:
12259   case MVT::i16:
12260   case MVT::i32: {
12261     // Unaligned access can use (for example) LRDB, LRDH, LDR
12262     if (AllowsUnaligned) {
12263       if (Fast)
12264         *Fast = Subtarget->hasV7Ops();
12265       return true;
12266     }
12267     return false;
12268   }
12269   case MVT::f64:
12270   case MVT::v2f64: {
12271     // For any little-endian targets with neon, we can support unaligned ld/st
12272     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12273     // A big-endian target may also explicitly support unaligned accesses
12274     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12275       if (Fast)
12276         *Fast = true;
12277       return true;
12278     }
12279     return false;
12280   }
12281   }
12282 }
12283 
12284 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12285                        unsigned AlignCheck) {
12286   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12287           (DstAlign == 0 || DstAlign % AlignCheck == 0));
12288 }
12289 
12290 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12291                                            unsigned DstAlign, unsigned SrcAlign,
12292                                            bool IsMemset, bool ZeroMemset,
12293                                            bool MemcpyStrSrc,
12294                                            MachineFunction &MF) const {
12295   const Function *F = MF.getFunction();
12296 
12297   // See if we can use NEON instructions for this...
12298   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12299       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
12300     bool Fast;
12301     if (Size >= 16 &&
12302         (memOpAlign(SrcAlign, DstAlign, 16) ||
12303          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12304       return MVT::v2f64;
12305     } else if (Size >= 8 &&
12306                (memOpAlign(SrcAlign, DstAlign, 8) ||
12307                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12308                  Fast))) {
12309       return MVT::f64;
12310     }
12311   }
12312 
12313   // Let the target-independent logic figure it out.
12314   return MVT::Other;
12315 }
12316 
12317 // 64-bit integers are split into their high and low parts and held in two
12318 // different registers, so the trunc is free since the low register can just
12319 // be used.
12320 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
12321   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
12322     return false;
12323   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
12324   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
12325   return (SrcBits == 64 && DestBits == 32);
12326 }
12327 
12328 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
12329   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
12330       !DstVT.isInteger())
12331     return false;
12332   unsigned SrcBits = SrcVT.getSizeInBits();
12333   unsigned DestBits = DstVT.getSizeInBits();
12334   return (SrcBits == 64 && DestBits == 32);
12335 }
12336 
12337 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12338   if (Val.getOpcode() != ISD::LOAD)
12339     return false;
12340 
12341   EVT VT1 = Val.getValueType();
12342   if (!VT1.isSimple() || !VT1.isInteger() ||
12343       !VT2.isSimple() || !VT2.isInteger())
12344     return false;
12345 
12346   switch (VT1.getSimpleVT().SimpleTy) {
12347   default: break;
12348   case MVT::i1:
12349   case MVT::i8:
12350   case MVT::i16:
12351     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
12352     return true;
12353   }
12354 
12355   return false;
12356 }
12357 
12358 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
12359   EVT VT = ExtVal.getValueType();
12360 
12361   if (!isTypeLegal(VT))
12362     return false;
12363 
12364   // Don't create a loadext if we can fold the extension into a wide/long
12365   // instruction.
12366   // If there's more than one user instruction, the loadext is desirable no
12367   // matter what.  There can be two uses by the same instruction.
12368   if (ExtVal->use_empty() ||
12369       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
12370     return true;
12371 
12372   SDNode *U = *ExtVal->use_begin();
12373   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
12374        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
12375     return false;
12376 
12377   return true;
12378 }
12379 
12380 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
12381   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12382     return false;
12383 
12384   if (!isTypeLegal(EVT::getEVT(Ty1)))
12385     return false;
12386 
12387   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
12388 
12389   // Assuming the caller doesn't have a zeroext or signext return parameter,
12390   // truncation all the way down to i1 is valid.
12391   return true;
12392 }
12393 
12394 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
12395                                                 const AddrMode &AM, Type *Ty,
12396                                                 unsigned AS) const {
12397   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
12398     if (Subtarget->hasFPAO())
12399       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
12400     return 0;
12401   }
12402   return -1;
12403 }
12404 
12405 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
12406   if (V < 0)
12407     return false;
12408 
12409   unsigned Scale = 1;
12410   switch (VT.getSimpleVT().SimpleTy) {
12411   default: return false;
12412   case MVT::i1:
12413   case MVT::i8:
12414     // Scale == 1;
12415     break;
12416   case MVT::i16:
12417     // Scale == 2;
12418     Scale = 2;
12419     break;
12420   case MVT::i32:
12421     // Scale == 4;
12422     Scale = 4;
12423     break;
12424   }
12425 
12426   if ((V & (Scale - 1)) != 0)
12427     return false;
12428   V /= Scale;
12429   return V == (V & ((1LL << 5) - 1));
12430 }
12431 
12432 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
12433                                       const ARMSubtarget *Subtarget) {
12434   bool isNeg = false;
12435   if (V < 0) {
12436     isNeg = true;
12437     V = - V;
12438   }
12439 
12440   switch (VT.getSimpleVT().SimpleTy) {
12441   default: return false;
12442   case MVT::i1:
12443   case MVT::i8:
12444   case MVT::i16:
12445   case MVT::i32:
12446     // + imm12 or - imm8
12447     if (isNeg)
12448       return V == (V & ((1LL << 8) - 1));
12449     return V == (V & ((1LL << 12) - 1));
12450   case MVT::f32:
12451   case MVT::f64:
12452     // Same as ARM mode. FIXME: NEON?
12453     if (!Subtarget->hasVFP2())
12454       return false;
12455     if ((V & 3) != 0)
12456       return false;
12457     V >>= 2;
12458     return V == (V & ((1LL << 8) - 1));
12459   }
12460 }
12461 
12462 /// isLegalAddressImmediate - Return true if the integer value can be used
12463 /// as the offset of the target addressing mode for load / store of the
12464 /// given type.
12465 static bool isLegalAddressImmediate(int64_t V, EVT VT,
12466                                     const ARMSubtarget *Subtarget) {
12467   if (V == 0)
12468     return true;
12469 
12470   if (!VT.isSimple())
12471     return false;
12472 
12473   if (Subtarget->isThumb1Only())
12474     return isLegalT1AddressImmediate(V, VT);
12475   else if (Subtarget->isThumb2())
12476     return isLegalT2AddressImmediate(V, VT, Subtarget);
12477 
12478   // ARM mode.
12479   if (V < 0)
12480     V = - V;
12481   switch (VT.getSimpleVT().SimpleTy) {
12482   default: return false;
12483   case MVT::i1:
12484   case MVT::i8:
12485   case MVT::i32:
12486     // +- imm12
12487     return V == (V & ((1LL << 12) - 1));
12488   case MVT::i16:
12489     // +- imm8
12490     return V == (V & ((1LL << 8) - 1));
12491   case MVT::f32:
12492   case MVT::f64:
12493     if (!Subtarget->hasVFP2()) // FIXME: NEON?
12494       return false;
12495     if ((V & 3) != 0)
12496       return false;
12497     V >>= 2;
12498     return V == (V & ((1LL << 8) - 1));
12499   }
12500 }
12501 
12502 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
12503                                                       EVT VT) const {
12504   int Scale = AM.Scale;
12505   if (Scale < 0)
12506     return false;
12507 
12508   switch (VT.getSimpleVT().SimpleTy) {
12509   default: return false;
12510   case MVT::i1:
12511   case MVT::i8:
12512   case MVT::i16:
12513   case MVT::i32:
12514     if (Scale == 1)
12515       return true;
12516     // r + r << imm
12517     Scale = Scale & ~1;
12518     return Scale == 2 || Scale == 4 || Scale == 8;
12519   case MVT::i64:
12520     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
12521     // version in Thumb mode.
12522     // r + r
12523     if (Scale == 1)
12524       return true;
12525     // r * 2 (this can be lowered to r + r).
12526     if (!AM.HasBaseReg && Scale == 2)
12527       return true;
12528     return false;
12529   case MVT::isVoid:
12530     // Note, we allow "void" uses (basically, uses that aren't loads or
12531     // stores), because arm allows folding a scale into many arithmetic
12532     // operations.  This should be made more precise and revisited later.
12533 
12534     // Allow r << imm, but the imm has to be a multiple of two.
12535     if (Scale & 1) return false;
12536     return isPowerOf2_32(Scale);
12537   }
12538 }
12539 
12540 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
12541                                                       EVT VT) const {
12542   const int Scale = AM.Scale;
12543 
12544   // Negative scales are not supported in Thumb1.
12545   if (Scale < 0)
12546     return false;
12547 
12548   // Thumb1 addressing modes do not support register scaling excepting the
12549   // following cases:
12550   // 1. Scale == 1 means no scaling.
12551   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
12552   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
12553 }
12554 
12555 /// isLegalAddressingMode - Return true if the addressing mode represented
12556 /// by AM is legal for this target, for a load/store of the specified type.
12557 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12558                                               const AddrMode &AM, Type *Ty,
12559                                               unsigned AS, Instruction *I) const {
12560   EVT VT = getValueType(DL, Ty, true);
12561   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
12562     return false;
12563 
12564   // Can never fold addr of global into load/store.
12565   if (AM.BaseGV)
12566     return false;
12567 
12568   switch (AM.Scale) {
12569   case 0:  // no scale reg, must be "r+i" or "r", or "i".
12570     break;
12571   default:
12572     // ARM doesn't support any R+R*scale+imm addr modes.
12573     if (AM.BaseOffs)
12574       return false;
12575 
12576     if (!VT.isSimple())
12577       return false;
12578 
12579     if (Subtarget->isThumb1Only())
12580       return isLegalT1ScaledAddressingMode(AM, VT);
12581 
12582     if (Subtarget->isThumb2())
12583       return isLegalT2ScaledAddressingMode(AM, VT);
12584 
12585     int Scale = AM.Scale;
12586     switch (VT.getSimpleVT().SimpleTy) {
12587     default: return false;
12588     case MVT::i1:
12589     case MVT::i8:
12590     case MVT::i32:
12591       if (Scale < 0) Scale = -Scale;
12592       if (Scale == 1)
12593         return true;
12594       // r + r << imm
12595       return isPowerOf2_32(Scale & ~1);
12596     case MVT::i16:
12597     case MVT::i64:
12598       // r +/- r
12599       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
12600         return true;
12601       // r * 2 (this can be lowered to r + r).
12602       if (!AM.HasBaseReg && Scale == 2)
12603         return true;
12604       return false;
12605 
12606     case MVT::isVoid:
12607       // Note, we allow "void" uses (basically, uses that aren't loads or
12608       // stores), because arm allows folding a scale into many arithmetic
12609       // operations.  This should be made more precise and revisited later.
12610 
12611       // Allow r << imm, but the imm has to be a multiple of two.
12612       if (Scale & 1) return false;
12613       return isPowerOf2_32(Scale);
12614     }
12615   }
12616   return true;
12617 }
12618 
12619 /// isLegalICmpImmediate - Return true if the specified immediate is legal
12620 /// icmp immediate, that is the target has icmp instructions which can compare
12621 /// a register against the immediate without having to materialize the
12622 /// immediate into a register.
12623 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12624   // Thumb2 and ARM modes can use cmn for negative immediates.
12625   if (!Subtarget->isThumb())
12626     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
12627   if (Subtarget->isThumb2())
12628     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
12629   // Thumb1 doesn't have cmn, and only 8-bit immediates.
12630   return Imm >= 0 && Imm <= 255;
12631 }
12632 
12633 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
12634 /// *or sub* immediate, that is the target has add or sub instructions which can
12635 /// add a register with the immediate without having to materialize the
12636 /// immediate into a register.
12637 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12638   // Same encoding for add/sub, just flip the sign.
12639   int64_t AbsImm = std::abs(Imm);
12640   if (!Subtarget->isThumb())
12641     return ARM_AM::getSOImmVal(AbsImm) != -1;
12642   if (Subtarget->isThumb2())
12643     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
12644   // Thumb1 only has 8-bit unsigned immediate.
12645   return AbsImm >= 0 && AbsImm <= 255;
12646 }
12647 
12648 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
12649                                       bool isSEXTLoad, SDValue &Base,
12650                                       SDValue &Offset, bool &isInc,
12651                                       SelectionDAG &DAG) {
12652   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12653     return false;
12654 
12655   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
12656     // AddressingMode 3
12657     Base = Ptr->getOperand(0);
12658     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12659       int RHSC = (int)RHS->getZExtValue();
12660       if (RHSC < 0 && RHSC > -256) {
12661         assert(Ptr->getOpcode() == ISD::ADD);
12662         isInc = false;
12663         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12664         return true;
12665       }
12666     }
12667     isInc = (Ptr->getOpcode() == ISD::ADD);
12668     Offset = Ptr->getOperand(1);
12669     return true;
12670   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
12671     // AddressingMode 2
12672     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12673       int RHSC = (int)RHS->getZExtValue();
12674       if (RHSC < 0 && RHSC > -0x1000) {
12675         assert(Ptr->getOpcode() == ISD::ADD);
12676         isInc = false;
12677         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12678         Base = Ptr->getOperand(0);
12679         return true;
12680       }
12681     }
12682 
12683     if (Ptr->getOpcode() == ISD::ADD) {
12684       isInc = true;
12685       ARM_AM::ShiftOpc ShOpcVal=
12686         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
12687       if (ShOpcVal != ARM_AM::no_shift) {
12688         Base = Ptr->getOperand(1);
12689         Offset = Ptr->getOperand(0);
12690       } else {
12691         Base = Ptr->getOperand(0);
12692         Offset = Ptr->getOperand(1);
12693       }
12694       return true;
12695     }
12696 
12697     isInc = (Ptr->getOpcode() == ISD::ADD);
12698     Base = Ptr->getOperand(0);
12699     Offset = Ptr->getOperand(1);
12700     return true;
12701   }
12702 
12703   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
12704   return false;
12705 }
12706 
12707 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
12708                                      bool isSEXTLoad, SDValue &Base,
12709                                      SDValue &Offset, bool &isInc,
12710                                      SelectionDAG &DAG) {
12711   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12712     return false;
12713 
12714   Base = Ptr->getOperand(0);
12715   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12716     int RHSC = (int)RHS->getZExtValue();
12717     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
12718       assert(Ptr->getOpcode() == ISD::ADD);
12719       isInc = false;
12720       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12721       return true;
12722     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
12723       isInc = Ptr->getOpcode() == ISD::ADD;
12724       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
12725       return true;
12726     }
12727   }
12728 
12729   return false;
12730 }
12731 
12732 /// getPreIndexedAddressParts - returns true by value, base pointer and
12733 /// offset pointer and addressing mode by reference if the node's address
12734 /// can be legally represented as pre-indexed load / store address.
12735 bool
12736 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
12737                                              SDValue &Offset,
12738                                              ISD::MemIndexedMode &AM,
12739                                              SelectionDAG &DAG) const {
12740   if (Subtarget->isThumb1Only())
12741     return false;
12742 
12743   EVT VT;
12744   SDValue Ptr;
12745   bool isSEXTLoad = false;
12746   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12747     Ptr = LD->getBasePtr();
12748     VT  = LD->getMemoryVT();
12749     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12750   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12751     Ptr = ST->getBasePtr();
12752     VT  = ST->getMemoryVT();
12753   } else
12754     return false;
12755 
12756   bool isInc;
12757   bool isLegal = false;
12758   if (Subtarget->isThumb2())
12759     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12760                                        Offset, isInc, DAG);
12761   else
12762     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
12763                                         Offset, isInc, DAG);
12764   if (!isLegal)
12765     return false;
12766 
12767   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
12768   return true;
12769 }
12770 
12771 /// getPostIndexedAddressParts - returns true by value, base pointer and
12772 /// offset pointer and addressing mode by reference if this node can be
12773 /// combined with a load / store to form a post-indexed load / store.
12774 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
12775                                                    SDValue &Base,
12776                                                    SDValue &Offset,
12777                                                    ISD::MemIndexedMode &AM,
12778                                                    SelectionDAG &DAG) const {
12779   EVT VT;
12780   SDValue Ptr;
12781   bool isSEXTLoad = false, isNonExt;
12782   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
12783     VT  = LD->getMemoryVT();
12784     Ptr = LD->getBasePtr();
12785     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
12786     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
12787   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
12788     VT  = ST->getMemoryVT();
12789     Ptr = ST->getBasePtr();
12790     isNonExt = !ST->isTruncatingStore();
12791   } else
12792     return false;
12793 
12794   if (Subtarget->isThumb1Only()) {
12795     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
12796     // must be non-extending/truncating, i32, with an offset of 4.
12797     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
12798     if (Op->getOpcode() != ISD::ADD || !isNonExt)
12799       return false;
12800     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
12801     if (!RHS || RHS->getZExtValue() != 4)
12802       return false;
12803 
12804     Offset = Op->getOperand(1);
12805     Base = Op->getOperand(0);
12806     AM = ISD::POST_INC;
12807     return true;
12808   }
12809 
12810   bool isInc;
12811   bool isLegal = false;
12812   if (Subtarget->isThumb2())
12813     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12814                                        isInc, DAG);
12815   else
12816     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
12817                                         isInc, DAG);
12818   if (!isLegal)
12819     return false;
12820 
12821   if (Ptr != Base) {
12822     // Swap base ptr and offset to catch more post-index load / store when
12823     // it's legal. In Thumb2 mode, offset must be an immediate.
12824     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
12825         !Subtarget->isThumb2())
12826       std::swap(Base, Offset);
12827 
12828     // Post-indexed load / store update the base pointer.
12829     if (Ptr != Base)
12830       return false;
12831   }
12832 
12833   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
12834   return true;
12835 }
12836 
12837 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
12838                                                       KnownBits &Known,
12839                                                       const APInt &DemandedElts,
12840                                                       const SelectionDAG &DAG,
12841                                                       unsigned Depth) const {
12842   unsigned BitWidth = Known.getBitWidth();
12843   Known.resetAll();
12844   switch (Op.getOpcode()) {
12845   default: break;
12846   case ARMISD::ADDC:
12847   case ARMISD::ADDE:
12848   case ARMISD::SUBC:
12849   case ARMISD::SUBE:
12850     // Special cases when we convert a carry to a boolean.
12851     if (Op.getResNo() == 0) {
12852       SDValue LHS = Op.getOperand(0);
12853       SDValue RHS = Op.getOperand(1);
12854       // (ADDE 0, 0, C) will give us a single bit.
12855       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
12856           isNullConstant(RHS)) {
12857         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
12858         return;
12859       }
12860     }
12861     break;
12862   case ARMISD::CMOV: {
12863     // Bits are known zero/one if known on the LHS and RHS.
12864     DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1);
12865     if (Known.isUnknown())
12866       return;
12867 
12868     KnownBits KnownRHS;
12869     DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1);
12870     Known.Zero &= KnownRHS.Zero;
12871     Known.One  &= KnownRHS.One;
12872     return;
12873   }
12874   case ISD::INTRINSIC_W_CHAIN: {
12875     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
12876     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
12877     switch (IntID) {
12878     default: return;
12879     case Intrinsic::arm_ldaex:
12880     case Intrinsic::arm_ldrex: {
12881       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
12882       unsigned MemBits = VT.getScalarSizeInBits();
12883       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
12884       return;
12885     }
12886     }
12887   }
12888   case ARMISD::BFI: {
12889     // Conservatively, we can recurse down the first operand
12890     // and just mask out all affected bits.
12891     DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1);
12892 
12893     // The operand to BFI is already a mask suitable for removing the bits it
12894     // sets.
12895     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
12896     const APInt &Mask = CI->getAPIntValue();
12897     Known.Zero &= Mask;
12898     Known.One &= Mask;
12899     return;
12900   }
12901   }
12902 }
12903 
12904 //===----------------------------------------------------------------------===//
12905 //                           ARM Inline Assembly Support
12906 //===----------------------------------------------------------------------===//
12907 
12908 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
12909   // Looking for "rev" which is V6+.
12910   if (!Subtarget->hasV6Ops())
12911     return false;
12912 
12913   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
12914   std::string AsmStr = IA->getAsmString();
12915   SmallVector<StringRef, 4> AsmPieces;
12916   SplitString(AsmStr, AsmPieces, ";\n");
12917 
12918   switch (AsmPieces.size()) {
12919   default: return false;
12920   case 1:
12921     AsmStr = AsmPieces[0];
12922     AsmPieces.clear();
12923     SplitString(AsmStr, AsmPieces, " \t,");
12924 
12925     // rev $0, $1
12926     if (AsmPieces.size() == 3 &&
12927         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
12928         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
12929       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
12930       if (Ty && Ty->getBitWidth() == 32)
12931         return IntrinsicLowering::LowerToByteSwap(CI);
12932     }
12933     break;
12934   }
12935 
12936   return false;
12937 }
12938 
12939 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
12940   // At this point, we have to lower this constraint to something else, so we
12941   // lower it to an "r" or "w". However, by doing this we will force the result
12942   // to be in register, while the X constraint is much more permissive.
12943   //
12944   // Although we are correct (we are free to emit anything, without
12945   // constraints), we might break use cases that would expect us to be more
12946   // efficient and emit something else.
12947   if (!Subtarget->hasVFP2())
12948     return "r";
12949   if (ConstraintVT.isFloatingPoint())
12950     return "w";
12951   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
12952      (ConstraintVT.getSizeInBits() == 64 ||
12953       ConstraintVT.getSizeInBits() == 128))
12954     return "w";
12955 
12956   return "r";
12957 }
12958 
12959 /// getConstraintType - Given a constraint letter, return the type of
12960 /// constraint it is for this target.
12961 ARMTargetLowering::ConstraintType
12962 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
12963   if (Constraint.size() == 1) {
12964     switch (Constraint[0]) {
12965     default:  break;
12966     case 'l': return C_RegisterClass;
12967     case 'w': return C_RegisterClass;
12968     case 'h': return C_RegisterClass;
12969     case 'x': return C_RegisterClass;
12970     case 't': return C_RegisterClass;
12971     case 'j': return C_Other; // Constant for movw.
12972       // An address with a single base register. Due to the way we
12973       // currently handle addresses it is the same as an 'r' memory constraint.
12974     case 'Q': return C_Memory;
12975     }
12976   } else if (Constraint.size() == 2) {
12977     switch (Constraint[0]) {
12978     default: break;
12979     // All 'U+' constraints are addresses.
12980     case 'U': return C_Memory;
12981     }
12982   }
12983   return TargetLowering::getConstraintType(Constraint);
12984 }
12985 
12986 /// Examine constraint type and operand type and determine a weight value.
12987 /// This object must already have been set up with the operand type
12988 /// and the current alternative constraint selected.
12989 TargetLowering::ConstraintWeight
12990 ARMTargetLowering::getSingleConstraintMatchWeight(
12991     AsmOperandInfo &info, const char *constraint) const {
12992   ConstraintWeight weight = CW_Invalid;
12993   Value *CallOperandVal = info.CallOperandVal;
12994     // If we don't have a value, we can't do a match,
12995     // but allow it at the lowest weight.
12996   if (!CallOperandVal)
12997     return CW_Default;
12998   Type *type = CallOperandVal->getType();
12999   // Look at the constraint type.
13000   switch (*constraint) {
13001   default:
13002     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13003     break;
13004   case 'l':
13005     if (type->isIntegerTy()) {
13006       if (Subtarget->isThumb())
13007         weight = CW_SpecificReg;
13008       else
13009         weight = CW_Register;
13010     }
13011     break;
13012   case 'w':
13013     if (type->isFloatingPointTy())
13014       weight = CW_Register;
13015     break;
13016   }
13017   return weight;
13018 }
13019 
13020 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
13021 
13022 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
13023     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
13024   if (Constraint.size() == 1) {
13025     // GCC ARM Constraint Letters
13026     switch (Constraint[0]) {
13027     case 'l': // Low regs or general regs.
13028       if (Subtarget->isThumb())
13029         return RCPair(0U, &ARM::tGPRRegClass);
13030       return RCPair(0U, &ARM::GPRRegClass);
13031     case 'h': // High regs or no regs.
13032       if (Subtarget->isThumb())
13033         return RCPair(0U, &ARM::hGPRRegClass);
13034       break;
13035     case 'r':
13036       if (Subtarget->isThumb1Only())
13037         return RCPair(0U, &ARM::tGPRRegClass);
13038       return RCPair(0U, &ARM::GPRRegClass);
13039     case 'w':
13040       if (VT == MVT::Other)
13041         break;
13042       if (VT == MVT::f32)
13043         return RCPair(0U, &ARM::SPRRegClass);
13044       if (VT.getSizeInBits() == 64)
13045         return RCPair(0U, &ARM::DPRRegClass);
13046       if (VT.getSizeInBits() == 128)
13047         return RCPair(0U, &ARM::QPRRegClass);
13048       break;
13049     case 'x':
13050       if (VT == MVT::Other)
13051         break;
13052       if (VT == MVT::f32)
13053         return RCPair(0U, &ARM::SPR_8RegClass);
13054       if (VT.getSizeInBits() == 64)
13055         return RCPair(0U, &ARM::DPR_8RegClass);
13056       if (VT.getSizeInBits() == 128)
13057         return RCPair(0U, &ARM::QPR_8RegClass);
13058       break;
13059     case 't':
13060       if (VT == MVT::f32)
13061         return RCPair(0U, &ARM::SPRRegClass);
13062       break;
13063     }
13064   }
13065   if (StringRef("{cc}").equals_lower(Constraint))
13066     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
13067 
13068   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13069 }
13070 
13071 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13072 /// vector.  If it is invalid, don't add anything to Ops.
13073 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13074                                                      std::string &Constraint,
13075                                                      std::vector<SDValue>&Ops,
13076                                                      SelectionDAG &DAG) const {
13077   SDValue Result;
13078 
13079   // Currently only support length 1 constraints.
13080   if (Constraint.length() != 1) return;
13081 
13082   char ConstraintLetter = Constraint[0];
13083   switch (ConstraintLetter) {
13084   default: break;
13085   case 'j':
13086   case 'I': case 'J': case 'K': case 'L':
13087   case 'M': case 'N': case 'O':
13088     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
13089     if (!C)
13090       return;
13091 
13092     int64_t CVal64 = C->getSExtValue();
13093     int CVal = (int) CVal64;
13094     // None of these constraints allow values larger than 32 bits.  Check
13095     // that the value fits in an int.
13096     if (CVal != CVal64)
13097       return;
13098 
13099     switch (ConstraintLetter) {
13100       case 'j':
13101         // Constant suitable for movw, must be between 0 and
13102         // 65535.
13103         if (Subtarget->hasV6T2Ops())
13104           if (CVal >= 0 && CVal <= 65535)
13105             break;
13106         return;
13107       case 'I':
13108         if (Subtarget->isThumb1Only()) {
13109           // This must be a constant between 0 and 255, for ADD
13110           // immediates.
13111           if (CVal >= 0 && CVal <= 255)
13112             break;
13113         } else if (Subtarget->isThumb2()) {
13114           // A constant that can be used as an immediate value in a
13115           // data-processing instruction.
13116           if (ARM_AM::getT2SOImmVal(CVal) != -1)
13117             break;
13118         } else {
13119           // A constant that can be used as an immediate value in a
13120           // data-processing instruction.
13121           if (ARM_AM::getSOImmVal(CVal) != -1)
13122             break;
13123         }
13124         return;
13125 
13126       case 'J':
13127         if (Subtarget->isThumb1Only()) {
13128           // This must be a constant between -255 and -1, for negated ADD
13129           // immediates. This can be used in GCC with an "n" modifier that
13130           // prints the negated value, for use with SUB instructions. It is
13131           // not useful otherwise but is implemented for compatibility.
13132           if (CVal >= -255 && CVal <= -1)
13133             break;
13134         } else {
13135           // This must be a constant between -4095 and 4095. It is not clear
13136           // what this constraint is intended for. Implemented for
13137           // compatibility with GCC.
13138           if (CVal >= -4095 && CVal <= 4095)
13139             break;
13140         }
13141         return;
13142 
13143       case 'K':
13144         if (Subtarget->isThumb1Only()) {
13145           // A 32-bit value where only one byte has a nonzero value. Exclude
13146           // zero to match GCC. This constraint is used by GCC internally for
13147           // constants that can be loaded with a move/shift combination.
13148           // It is not useful otherwise but is implemented for compatibility.
13149           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
13150             break;
13151         } else if (Subtarget->isThumb2()) {
13152           // A constant whose bitwise inverse can be used as an immediate
13153           // value in a data-processing instruction. This can be used in GCC
13154           // with a "B" modifier that prints the inverted value, for use with
13155           // BIC and MVN instructions. It is not useful otherwise but is
13156           // implemented for compatibility.
13157           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
13158             break;
13159         } else {
13160           // A constant whose bitwise inverse can be used as an immediate
13161           // value in a data-processing instruction. This can be used in GCC
13162           // with a "B" modifier that prints the inverted value, for use with
13163           // BIC and MVN instructions. It is not useful otherwise but is
13164           // implemented for compatibility.
13165           if (ARM_AM::getSOImmVal(~CVal) != -1)
13166             break;
13167         }
13168         return;
13169 
13170       case 'L':
13171         if (Subtarget->isThumb1Only()) {
13172           // This must be a constant between -7 and 7,
13173           // for 3-operand ADD/SUB immediate instructions.
13174           if (CVal >= -7 && CVal < 7)
13175             break;
13176         } else if (Subtarget->isThumb2()) {
13177           // A constant whose negation can be used as an immediate value in a
13178           // data-processing instruction. This can be used in GCC with an "n"
13179           // modifier that prints the negated value, for use with SUB
13180           // instructions. It is not useful otherwise but is implemented for
13181           // compatibility.
13182           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
13183             break;
13184         } else {
13185           // A constant whose negation can be used as an immediate value in a
13186           // data-processing instruction. This can be used in GCC with an "n"
13187           // modifier that prints the negated value, for use with SUB
13188           // instructions. It is not useful otherwise but is implemented for
13189           // compatibility.
13190           if (ARM_AM::getSOImmVal(-CVal) != -1)
13191             break;
13192         }
13193         return;
13194 
13195       case 'M':
13196         if (Subtarget->isThumb1Only()) {
13197           // This must be a multiple of 4 between 0 and 1020, for
13198           // ADD sp + immediate.
13199           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
13200             break;
13201         } else {
13202           // A power of two or a constant between 0 and 32.  This is used in
13203           // GCC for the shift amount on shifted register operands, but it is
13204           // useful in general for any shift amounts.
13205           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
13206             break;
13207         }
13208         return;
13209 
13210       case 'N':
13211         if (Subtarget->isThumb()) {  // FIXME thumb2
13212           // This must be a constant between 0 and 31, for shift amounts.
13213           if (CVal >= 0 && CVal <= 31)
13214             break;
13215         }
13216         return;
13217 
13218       case 'O':
13219         if (Subtarget->isThumb()) {  // FIXME thumb2
13220           // This must be a multiple of 4 between -508 and 508, for
13221           // ADD/SUB sp = sp + immediate.
13222           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
13223             break;
13224         }
13225         return;
13226     }
13227     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
13228     break;
13229   }
13230 
13231   if (Result.getNode()) {
13232     Ops.push_back(Result);
13233     return;
13234   }
13235   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13236 }
13237 
13238 static RTLIB::Libcall getDivRemLibcall(
13239     const SDNode *N, MVT::SimpleValueType SVT) {
13240   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13241           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13242          "Unhandled Opcode in getDivRemLibcall");
13243   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13244                   N->getOpcode() == ISD::SREM;
13245   RTLIB::Libcall LC;
13246   switch (SVT) {
13247   default: llvm_unreachable("Unexpected request for libcall!");
13248   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
13249   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
13250   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
13251   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
13252   }
13253   return LC;
13254 }
13255 
13256 static TargetLowering::ArgListTy getDivRemArgList(
13257     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
13258   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13259           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13260          "Unhandled Opcode in getDivRemArgList");
13261   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13262                   N->getOpcode() == ISD::SREM;
13263   TargetLowering::ArgListTy Args;
13264   TargetLowering::ArgListEntry Entry;
13265   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13266     EVT ArgVT = N->getOperand(i).getValueType();
13267     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
13268     Entry.Node = N->getOperand(i);
13269     Entry.Ty = ArgTy;
13270     Entry.IsSExt = isSigned;
13271     Entry.IsZExt = !isSigned;
13272     Args.push_back(Entry);
13273   }
13274   if (Subtarget->isTargetWindows() && Args.size() >= 2)
13275     std::swap(Args[0], Args[1]);
13276   return Args;
13277 }
13278 
13279 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
13280   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
13281           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
13282           Subtarget->isTargetWindows()) &&
13283          "Register-based DivRem lowering only");
13284   unsigned Opcode = Op->getOpcode();
13285   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
13286          "Invalid opcode for Div/Rem lowering");
13287   bool isSigned = (Opcode == ISD::SDIVREM);
13288   EVT VT = Op->getValueType(0);
13289   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
13290   SDLoc dl(Op);
13291 
13292   // If the target has hardware divide, use divide + multiply + subtract:
13293   //     div = a / b
13294   //     rem = a - b * div
13295   //     return {div, rem}
13296   // This should be lowered into UDIV/SDIV + MLS later on.
13297   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
13298                                         : Subtarget->hasDivideInARMMode();
13299   if (hasDivide && Op->getValueType(0).isSimple() &&
13300       Op->getSimpleValueType(0) == MVT::i32) {
13301     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
13302     const SDValue Dividend = Op->getOperand(0);
13303     const SDValue Divisor = Op->getOperand(1);
13304     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
13305     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
13306     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13307 
13308     SDValue Values[2] = {Div, Rem};
13309     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
13310   }
13311 
13312   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
13313                                        VT.getSimpleVT().SimpleTy);
13314   SDValue InChain = DAG.getEntryNode();
13315 
13316   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
13317                                                     DAG.getContext(),
13318                                                     Subtarget);
13319 
13320   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13321                                          getPointerTy(DAG.getDataLayout()));
13322 
13323   Type *RetTy = StructType::get(Ty, Ty);
13324 
13325   if (Subtarget->isTargetWindows())
13326     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
13327 
13328   TargetLowering::CallLoweringInfo CLI(DAG);
13329   CLI.setDebugLoc(dl).setChain(InChain)
13330     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
13331     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13332 
13333   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13334   return CallInfo.first;
13335 }
13336 
13337 // Lowers REM using divmod helpers
13338 // see RTABI section 4.2/4.3
13339 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
13340   // Build return types (div and rem)
13341   std::vector<Type*> RetTyParams;
13342   Type *RetTyElement;
13343 
13344   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
13345   default: llvm_unreachable("Unexpected request for libcall!");
13346   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
13347   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
13348   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
13349   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
13350   }
13351 
13352   RetTyParams.push_back(RetTyElement);
13353   RetTyParams.push_back(RetTyElement);
13354   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
13355   Type *RetTy = StructType::get(*DAG.getContext(), ret);
13356 
13357   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
13358                                                              SimpleTy);
13359   SDValue InChain = DAG.getEntryNode();
13360   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
13361                                                     Subtarget);
13362   bool isSigned = N->getOpcode() == ISD::SREM;
13363   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13364                                          getPointerTy(DAG.getDataLayout()));
13365 
13366   if (Subtarget->isTargetWindows())
13367     InChain = WinDBZCheckDenominator(DAG, N, InChain);
13368 
13369   // Lower call
13370   CallLoweringInfo CLI(DAG);
13371   CLI.setChain(InChain)
13372      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
13373      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
13374   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
13375 
13376   // Return second (rem) result operand (first contains div)
13377   SDNode *ResNode = CallResult.first.getNode();
13378   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
13379   return ResNode->getOperand(1);
13380 }
13381 
13382 SDValue
13383 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
13384   assert(Subtarget->isTargetWindows() && "unsupported target platform");
13385   SDLoc DL(Op);
13386 
13387   // Get the inputs.
13388   SDValue Chain = Op.getOperand(0);
13389   SDValue Size  = Op.getOperand(1);
13390 
13391   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
13392                               DAG.getConstant(2, DL, MVT::i32));
13393 
13394   SDValue Flag;
13395   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
13396   Flag = Chain.getValue(1);
13397 
13398   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13399   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
13400 
13401   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
13402   Chain = NewSP.getValue(1);
13403 
13404   SDValue Ops[2] = { NewSP, Chain };
13405   return DAG.getMergeValues(Ops, DL);
13406 }
13407 
13408 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
13409   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
13410          "Unexpected type for custom-lowering FP_EXTEND");
13411 
13412   RTLIB::Libcall LC;
13413   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
13414 
13415   SDValue SrcVal = Op.getOperand(0);
13416   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13417                      SDLoc(Op)).first;
13418 }
13419 
13420 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
13421   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
13422          Subtarget->isFPOnlySP() &&
13423          "Unexpected type for custom-lowering FP_ROUND");
13424 
13425   RTLIB::Libcall LC;
13426   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
13427 
13428   SDValue SrcVal = Op.getOperand(0);
13429   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13430                      SDLoc(Op)).first;
13431 }
13432 
13433 bool
13434 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13435   // The ARM target isn't yet aware of offsets.
13436   return false;
13437 }
13438 
13439 bool ARM::isBitFieldInvertedMask(unsigned v) {
13440   if (v == 0xffffffff)
13441     return false;
13442 
13443   // there can be 1's on either or both "outsides", all the "inside"
13444   // bits must be 0's
13445   return isShiftedMask_32(~v);
13446 }
13447 
13448 /// isFPImmLegal - Returns true if the target can instruction select the
13449 /// specified FP immediate natively. If false, the legalizer will
13450 /// materialize the FP immediate as a load from a constant pool.
13451 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13452   if (!Subtarget->hasVFP3())
13453     return false;
13454   if (VT == MVT::f32)
13455     return ARM_AM::getFP32Imm(Imm) != -1;
13456   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
13457     return ARM_AM::getFP64Imm(Imm) != -1;
13458   return false;
13459 }
13460 
13461 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
13462 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
13463 /// specified in the intrinsic calls.
13464 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13465                                            const CallInst &I,
13466                                            unsigned Intrinsic) const {
13467   switch (Intrinsic) {
13468   case Intrinsic::arm_neon_vld1:
13469   case Intrinsic::arm_neon_vld2:
13470   case Intrinsic::arm_neon_vld3:
13471   case Intrinsic::arm_neon_vld4:
13472   case Intrinsic::arm_neon_vld2lane:
13473   case Intrinsic::arm_neon_vld3lane:
13474   case Intrinsic::arm_neon_vld4lane: {
13475     Info.opc = ISD::INTRINSIC_W_CHAIN;
13476     // Conservatively set memVT to the entire set of vectors loaded.
13477     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13478     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
13479     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13480     Info.ptrVal = I.getArgOperand(0);
13481     Info.offset = 0;
13482     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13483     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13484     Info.vol = false; // volatile loads with NEON intrinsics not supported
13485     Info.readMem = true;
13486     Info.writeMem = false;
13487     return true;
13488   }
13489   case Intrinsic::arm_neon_vst1:
13490   case Intrinsic::arm_neon_vst2:
13491   case Intrinsic::arm_neon_vst3:
13492   case Intrinsic::arm_neon_vst4:
13493   case Intrinsic::arm_neon_vst2lane:
13494   case Intrinsic::arm_neon_vst3lane:
13495   case Intrinsic::arm_neon_vst4lane: {
13496     Info.opc = ISD::INTRINSIC_VOID;
13497     // Conservatively set memVT to the entire set of vectors stored.
13498     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13499     unsigned NumElts = 0;
13500     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
13501       Type *ArgTy = I.getArgOperand(ArgI)->getType();
13502       if (!ArgTy->isVectorTy())
13503         break;
13504       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
13505     }
13506     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13507     Info.ptrVal = I.getArgOperand(0);
13508     Info.offset = 0;
13509     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13510     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13511     Info.vol = false; // volatile stores with NEON intrinsics not supported
13512     Info.readMem = false;
13513     Info.writeMem = true;
13514     return true;
13515   }
13516   case Intrinsic::arm_ldaex:
13517   case Intrinsic::arm_ldrex: {
13518     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13519     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
13520     Info.opc = ISD::INTRINSIC_W_CHAIN;
13521     Info.memVT = MVT::getVT(PtrTy->getElementType());
13522     Info.ptrVal = I.getArgOperand(0);
13523     Info.offset = 0;
13524     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13525     Info.vol = true;
13526     Info.readMem = true;
13527     Info.writeMem = false;
13528     return true;
13529   }
13530   case Intrinsic::arm_stlex:
13531   case Intrinsic::arm_strex: {
13532     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13533     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
13534     Info.opc = ISD::INTRINSIC_W_CHAIN;
13535     Info.memVT = MVT::getVT(PtrTy->getElementType());
13536     Info.ptrVal = I.getArgOperand(1);
13537     Info.offset = 0;
13538     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13539     Info.vol = true;
13540     Info.readMem = false;
13541     Info.writeMem = true;
13542     return true;
13543   }
13544   case Intrinsic::arm_stlexd:
13545   case Intrinsic::arm_strexd:
13546     Info.opc = ISD::INTRINSIC_W_CHAIN;
13547     Info.memVT = MVT::i64;
13548     Info.ptrVal = I.getArgOperand(2);
13549     Info.offset = 0;
13550     Info.align = 8;
13551     Info.vol = true;
13552     Info.readMem = false;
13553     Info.writeMem = true;
13554     return true;
13555 
13556   case Intrinsic::arm_ldaexd:
13557   case Intrinsic::arm_ldrexd:
13558     Info.opc = ISD::INTRINSIC_W_CHAIN;
13559     Info.memVT = MVT::i64;
13560     Info.ptrVal = I.getArgOperand(0);
13561     Info.offset = 0;
13562     Info.align = 8;
13563     Info.vol = true;
13564     Info.readMem = true;
13565     Info.writeMem = false;
13566     return true;
13567 
13568   default:
13569     break;
13570   }
13571 
13572   return false;
13573 }
13574 
13575 /// \brief Returns true if it is beneficial to convert a load of a constant
13576 /// to just the constant itself.
13577 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13578                                                           Type *Ty) const {
13579   assert(Ty->isIntegerTy());
13580 
13581   unsigned Bits = Ty->getPrimitiveSizeInBits();
13582   if (Bits == 0 || Bits > 32)
13583     return false;
13584   return true;
13585 }
13586 
13587 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
13588                                                 unsigned Index) const {
13589   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
13590     return false;
13591 
13592   return (Index == 0 || Index == ResVT.getVectorNumElements());
13593 }
13594 
13595 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
13596                                         ARM_MB::MemBOpt Domain) const {
13597   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13598 
13599   // First, if the target has no DMB, see what fallback we can use.
13600   if (!Subtarget->hasDataBarrier()) {
13601     // Some ARMv6 cpus can support data barriers with an mcr instruction.
13602     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
13603     // here.
13604     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
13605       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
13606       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
13607                         Builder.getInt32(0), Builder.getInt32(7),
13608                         Builder.getInt32(10), Builder.getInt32(5)};
13609       return Builder.CreateCall(MCR, args);
13610     } else {
13611       // Instead of using barriers, atomic accesses on these subtargets use
13612       // libcalls.
13613       llvm_unreachable("makeDMB on a target so old that it has no barriers");
13614     }
13615   } else {
13616     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
13617     // Only a full system barrier exists in the M-class architectures.
13618     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
13619     Constant *CDomain = Builder.getInt32(Domain);
13620     return Builder.CreateCall(DMB, CDomain);
13621   }
13622 }
13623 
13624 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13625 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
13626                                                  Instruction *Inst,
13627                                                  AtomicOrdering Ord) const {
13628   switch (Ord) {
13629   case AtomicOrdering::NotAtomic:
13630   case AtomicOrdering::Unordered:
13631     llvm_unreachable("Invalid fence: unordered/non-atomic");
13632   case AtomicOrdering::Monotonic:
13633   case AtomicOrdering::Acquire:
13634     return nullptr; // Nothing to do
13635   case AtomicOrdering::SequentiallyConsistent:
13636     if (!Inst->hasAtomicStore())
13637       return nullptr; // Nothing to do
13638     /*FALLTHROUGH*/
13639   case AtomicOrdering::Release:
13640   case AtomicOrdering::AcquireRelease:
13641     if (Subtarget->preferISHSTBarriers())
13642       return makeDMB(Builder, ARM_MB::ISHST);
13643     // FIXME: add a comment with a link to documentation justifying this.
13644     else
13645       return makeDMB(Builder, ARM_MB::ISH);
13646   }
13647   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
13648 }
13649 
13650 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
13651                                                   Instruction *Inst,
13652                                                   AtomicOrdering Ord) const {
13653   switch (Ord) {
13654   case AtomicOrdering::NotAtomic:
13655   case AtomicOrdering::Unordered:
13656     llvm_unreachable("Invalid fence: unordered/not-atomic");
13657   case AtomicOrdering::Monotonic:
13658   case AtomicOrdering::Release:
13659     return nullptr; // Nothing to do
13660   case AtomicOrdering::Acquire:
13661   case AtomicOrdering::AcquireRelease:
13662   case AtomicOrdering::SequentiallyConsistent:
13663     return makeDMB(Builder, ARM_MB::ISH);
13664   }
13665   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
13666 }
13667 
13668 // Loads and stores less than 64-bits are already atomic; ones above that
13669 // are doomed anyway, so defer to the default libcall and blame the OS when
13670 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13671 // anything for those.
13672 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13673   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13674   return (Size == 64) && !Subtarget->isMClass();
13675 }
13676 
13677 // Loads and stores less than 64-bits are already atomic; ones above that
13678 // are doomed anyway, so defer to the default libcall and blame the OS when
13679 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13680 // anything for those.
13681 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
13682 // guarantee, see DDI0406C ARM architecture reference manual,
13683 // sections A8.8.72-74 LDRD)
13684 TargetLowering::AtomicExpansionKind
13685 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13686   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13687   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
13688                                                   : AtomicExpansionKind::None;
13689 }
13690 
13691 // For the real atomic operations, we have ldrex/strex up to 32 bits,
13692 // and up to 64 bits on the non-M profiles
13693 TargetLowering::AtomicExpansionKind
13694 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13695   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13696   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13697   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
13698              ? AtomicExpansionKind::LLSC
13699              : AtomicExpansionKind::None;
13700 }
13701 
13702 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
13703     AtomicCmpXchgInst *AI) const {
13704   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13705   // implement cmpxchg without spilling. If the address being exchanged is also
13706   // on the stack and close enough to the spill slot, this can lead to a
13707   // situation where the monitor always gets cleared and the atomic operation
13708   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13709   bool hasAtomicCmpXchg =
13710       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13711   return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg;
13712 }
13713 
13714 bool ARMTargetLowering::shouldInsertFencesForAtomic(
13715     const Instruction *I) const {
13716   return InsertFencesForAtomic;
13717 }
13718 
13719 // This has so far only been implemented for MachO.
13720 bool ARMTargetLowering::useLoadStackGuardNode() const {
13721   return Subtarget->isTargetMachO();
13722 }
13723 
13724 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
13725                                                   unsigned &Cost) const {
13726   // If we do not have NEON, vector types are not natively supported.
13727   if (!Subtarget->hasNEON())
13728     return false;
13729 
13730   // Floating point values and vector values map to the same register file.
13731   // Therefore, although we could do a store extract of a vector type, this is
13732   // better to leave at float as we have more freedom in the addressing mode for
13733   // those.
13734   if (VectorTy->isFPOrFPVectorTy())
13735     return false;
13736 
13737   // If the index is unknown at compile time, this is very expensive to lower
13738   // and it is not possible to combine the store with the extract.
13739   if (!isa<ConstantInt>(Idx))
13740     return false;
13741 
13742   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
13743   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
13744   // We can do a store + vector extract on any vector that fits perfectly in a D
13745   // or Q register.
13746   if (BitWidth == 64 || BitWidth == 128) {
13747     Cost = 0;
13748     return true;
13749   }
13750   return false;
13751 }
13752 
13753 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
13754   return Subtarget->hasV6T2Ops();
13755 }
13756 
13757 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
13758   return Subtarget->hasV6T2Ops();
13759 }
13760 
13761 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
13762                                          AtomicOrdering Ord) const {
13763   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13764   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
13765   bool IsAcquire = isAcquireOrStronger(Ord);
13766 
13767   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
13768   // intrinsic must return {i32, i32} and we have to recombine them into a
13769   // single i64 here.
13770   if (ValTy->getPrimitiveSizeInBits() == 64) {
13771     Intrinsic::ID Int =
13772         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
13773     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
13774 
13775     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13776     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
13777 
13778     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
13779     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
13780     if (!Subtarget->isLittle())
13781       std::swap (Lo, Hi);
13782     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
13783     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
13784     return Builder.CreateOr(
13785         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
13786   }
13787 
13788   Type *Tys[] = { Addr->getType() };
13789   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
13790   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
13791 
13792   return Builder.CreateTruncOrBitCast(
13793       Builder.CreateCall(Ldrex, Addr),
13794       cast<PointerType>(Addr->getType())->getElementType());
13795 }
13796 
13797 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
13798     IRBuilder<> &Builder) const {
13799   if (!Subtarget->hasV7Ops())
13800     return;
13801   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13802   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
13803 }
13804 
13805 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
13806                                                Value *Addr,
13807                                                AtomicOrdering Ord) const {
13808   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13809   bool IsRelease = isReleaseOrStronger(Ord);
13810 
13811   // Since the intrinsics must have legal type, the i64 intrinsics take two
13812   // parameters: "i32, i32". We must marshal Val into the appropriate form
13813   // before the call.
13814   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
13815     Intrinsic::ID Int =
13816         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
13817     Function *Strex = Intrinsic::getDeclaration(M, Int);
13818     Type *Int32Ty = Type::getInt32Ty(M->getContext());
13819 
13820     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
13821     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
13822     if (!Subtarget->isLittle())
13823       std::swap(Lo, Hi);
13824     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
13825     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
13826   }
13827 
13828   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
13829   Type *Tys[] = { Addr->getType() };
13830   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
13831 
13832   return Builder.CreateCall(
13833       Strex, {Builder.CreateZExtOrBitCast(
13834                   Val, Strex->getFunctionType()->getParamType(0)),
13835               Addr});
13836 }
13837 
13838 /// A helper function for determining the number of interleaved accesses we
13839 /// will generate when lowering accesses of the given type.
13840 unsigned
13841 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
13842                                              const DataLayout &DL) const {
13843   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
13844 }
13845 
13846 bool ARMTargetLowering::isLegalInterleavedAccessType(
13847     VectorType *VecTy, const DataLayout &DL) const {
13848 
13849   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
13850   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
13851 
13852   // Ensure the vector doesn't have f16 elements. Even though we could do an
13853   // i16 vldN, we can't hold the f16 vectors and will end up converting via
13854   // f32.
13855   if (VecTy->getElementType()->isHalfTy())
13856     return false;
13857 
13858   // Ensure the number of vector elements is greater than 1.
13859   if (VecTy->getNumElements() < 2)
13860     return false;
13861 
13862   // Ensure the element type is legal.
13863   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
13864     return false;
13865 
13866   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
13867   // 128 will be split into multiple interleaved accesses.
13868   return VecSize == 64 || VecSize % 128 == 0;
13869 }
13870 
13871 /// \brief Lower an interleaved load into a vldN intrinsic.
13872 ///
13873 /// E.g. Lower an interleaved load (Factor = 2):
13874 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
13875 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
13876 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
13877 ///
13878 ///      Into:
13879 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
13880 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
13881 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
13882 bool ARMTargetLowering::lowerInterleavedLoad(
13883     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
13884     ArrayRef<unsigned> Indices, unsigned Factor) const {
13885   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
13886          "Invalid interleave factor");
13887   assert(!Shuffles.empty() && "Empty shufflevector input");
13888   assert(Shuffles.size() == Indices.size() &&
13889          "Unmatched number of shufflevectors and indices");
13890 
13891   VectorType *VecTy = Shuffles[0]->getType();
13892   Type *EltTy = VecTy->getVectorElementType();
13893 
13894   const DataLayout &DL = LI->getModule()->getDataLayout();
13895 
13896   // Skip if we do not have NEON and skip illegal vector types. We can
13897   // "legalize" wide vector types into multiple interleaved accesses as long as
13898   // the vector types are divisible by 128.
13899   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
13900     return false;
13901 
13902   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
13903 
13904   // A pointer vector can not be the return type of the ldN intrinsics. Need to
13905   // load integer vectors first and then convert to pointer vectors.
13906   if (EltTy->isPointerTy())
13907     VecTy =
13908         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
13909 
13910   IRBuilder<> Builder(LI);
13911 
13912   // The base address of the load.
13913   Value *BaseAddr = LI->getPointerOperand();
13914 
13915   if (NumLoads > 1) {
13916     // If we're going to generate more than one load, reset the sub-vector type
13917     // to something legal.
13918     VecTy = VectorType::get(VecTy->getVectorElementType(),
13919                             VecTy->getVectorNumElements() / NumLoads);
13920 
13921     // We will compute the pointer operand of each load from the original base
13922     // address using GEPs. Cast the base address to a pointer to the scalar
13923     // element type.
13924     BaseAddr = Builder.CreateBitCast(
13925         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
13926                       LI->getPointerAddressSpace()));
13927   }
13928 
13929   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
13930 
13931   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
13932   Type *Tys[] = {VecTy, Int8Ptr};
13933   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
13934                                             Intrinsic::arm_neon_vld3,
13935                                             Intrinsic::arm_neon_vld4};
13936   Function *VldnFunc =
13937       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
13938 
13939   // Holds sub-vectors extracted from the load intrinsic return values. The
13940   // sub-vectors are associated with the shufflevector instructions they will
13941   // replace.
13942   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
13943 
13944   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
13945     // If we're generating more than one load, compute the base address of
13946     // subsequent loads as an offset from the previous.
13947     if (LoadCount > 0)
13948       BaseAddr = Builder.CreateConstGEP1_32(
13949           BaseAddr, VecTy->getVectorNumElements() * Factor);
13950 
13951     SmallVector<Value *, 2> Ops;
13952     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
13953     Ops.push_back(Builder.getInt32(LI->getAlignment()));
13954 
13955     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
13956 
13957     // Replace uses of each shufflevector with the corresponding vector loaded
13958     // by ldN.
13959     for (unsigned i = 0; i < Shuffles.size(); i++) {
13960       ShuffleVectorInst *SV = Shuffles[i];
13961       unsigned Index = Indices[i];
13962 
13963       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
13964 
13965       // Convert the integer vector to pointer vector if the element is pointer.
13966       if (EltTy->isPointerTy())
13967         SubVec = Builder.CreateIntToPtr(
13968             SubVec, VectorType::get(SV->getType()->getVectorElementType(),
13969                                     VecTy->getVectorNumElements()));
13970 
13971       SubVecs[SV].push_back(SubVec);
13972     }
13973   }
13974 
13975   // Replace uses of the shufflevector instructions with the sub-vectors
13976   // returned by the load intrinsic. If a shufflevector instruction is
13977   // associated with more than one sub-vector, those sub-vectors will be
13978   // concatenated into a single wide vector.
13979   for (ShuffleVectorInst *SVI : Shuffles) {
13980     auto &SubVec = SubVecs[SVI];
13981     auto *WideVec =
13982         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
13983     SVI->replaceAllUsesWith(WideVec);
13984   }
13985 
13986   return true;
13987 }
13988 
13989 /// \brief Lower an interleaved store into a vstN intrinsic.
13990 ///
13991 /// E.g. Lower an interleaved store (Factor = 3):
13992 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
13993 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
13994 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
13995 ///
13996 ///      Into:
13997 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
13998 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
13999 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
14000 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14001 ///
14002 /// Note that the new shufflevectors will be removed and we'll only generate one
14003 /// vst3 instruction in CodeGen.
14004 ///
14005 /// Example for a more general valid mask (Factor 3). Lower:
14006 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
14007 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
14008 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
14009 ///
14010 ///      Into:
14011 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
14012 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
14013 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
14014 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14015 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
14016                                               ShuffleVectorInst *SVI,
14017                                               unsigned Factor) const {
14018   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14019          "Invalid interleave factor");
14020 
14021   VectorType *VecTy = SVI->getType();
14022   assert(VecTy->getVectorNumElements() % Factor == 0 &&
14023          "Invalid interleaved store");
14024 
14025   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
14026   Type *EltTy = VecTy->getVectorElementType();
14027   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
14028 
14029   const DataLayout &DL = SI->getModule()->getDataLayout();
14030 
14031   // Skip if we do not have NEON and skip illegal vector types. We can
14032   // "legalize" wide vector types into multiple interleaved accesses as long as
14033   // the vector types are divisible by 128.
14034   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
14035     return false;
14036 
14037   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
14038 
14039   Value *Op0 = SVI->getOperand(0);
14040   Value *Op1 = SVI->getOperand(1);
14041   IRBuilder<> Builder(SI);
14042 
14043   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
14044   // vectors to integer vectors.
14045   if (EltTy->isPointerTy()) {
14046     Type *IntTy = DL.getIntPtrType(EltTy);
14047 
14048     // Convert to the corresponding integer vector.
14049     Type *IntVecTy =
14050         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
14051     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
14052     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
14053 
14054     SubVecTy = VectorType::get(IntTy, LaneLen);
14055   }
14056 
14057   // The base address of the store.
14058   Value *BaseAddr = SI->getPointerOperand();
14059 
14060   if (NumStores > 1) {
14061     // If we're going to generate more than one store, reset the lane length
14062     // and sub-vector type to something legal.
14063     LaneLen /= NumStores;
14064     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
14065 
14066     // We will compute the pointer operand of each store from the original base
14067     // address using GEPs. Cast the base address to a pointer to the scalar
14068     // element type.
14069     BaseAddr = Builder.CreateBitCast(
14070         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
14071                       SI->getPointerAddressSpace()));
14072   }
14073 
14074   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
14075 
14076   auto Mask = SVI->getShuffleMask();
14077 
14078   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
14079   Type *Tys[] = {Int8Ptr, SubVecTy};
14080   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
14081                                              Intrinsic::arm_neon_vst3,
14082                                              Intrinsic::arm_neon_vst4};
14083 
14084   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
14085     // If we generating more than one store, we compute the base address of
14086     // subsequent stores as an offset from the previous.
14087     if (StoreCount > 0)
14088       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
14089 
14090     SmallVector<Value *, 6> Ops;
14091     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14092 
14093     Function *VstNFunc =
14094         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
14095 
14096     // Split the shufflevector operands into sub vectors for the new vstN call.
14097     for (unsigned i = 0; i < Factor; i++) {
14098       unsigned IdxI = StoreCount * LaneLen * Factor + i;
14099       if (Mask[IdxI] >= 0) {
14100         Ops.push_back(Builder.CreateShuffleVector(
14101             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
14102       } else {
14103         unsigned StartMask = 0;
14104         for (unsigned j = 1; j < LaneLen; j++) {
14105           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
14106           if (Mask[IdxJ * Factor + IdxI] >= 0) {
14107             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
14108             break;
14109           }
14110         }
14111         // Note: If all elements in a chunk are undefs, StartMask=0!
14112         // Note: Filling undef gaps with random elements is ok, since
14113         // those elements were being written anyway (with undefs).
14114         // In the case of all undefs we're defaulting to using elems from 0
14115         // Note: StartMask cannot be negative, it's checked in
14116         // isReInterleaveMask
14117         Ops.push_back(Builder.CreateShuffleVector(
14118             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
14119       }
14120     }
14121 
14122     Ops.push_back(Builder.getInt32(SI->getAlignment()));
14123     Builder.CreateCall(VstNFunc, Ops);
14124   }
14125   return true;
14126 }
14127 
14128 enum HABaseType {
14129   HA_UNKNOWN = 0,
14130   HA_FLOAT,
14131   HA_DOUBLE,
14132   HA_VECT64,
14133   HA_VECT128
14134 };
14135 
14136 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
14137                                    uint64_t &Members) {
14138   if (auto *ST = dyn_cast<StructType>(Ty)) {
14139     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
14140       uint64_t SubMembers = 0;
14141       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
14142         return false;
14143       Members += SubMembers;
14144     }
14145   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
14146     uint64_t SubMembers = 0;
14147     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
14148       return false;
14149     Members += SubMembers * AT->getNumElements();
14150   } else if (Ty->isFloatTy()) {
14151     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
14152       return false;
14153     Members = 1;
14154     Base = HA_FLOAT;
14155   } else if (Ty->isDoubleTy()) {
14156     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
14157       return false;
14158     Members = 1;
14159     Base = HA_DOUBLE;
14160   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
14161     Members = 1;
14162     switch (Base) {
14163     case HA_FLOAT:
14164     case HA_DOUBLE:
14165       return false;
14166     case HA_VECT64:
14167       return VT->getBitWidth() == 64;
14168     case HA_VECT128:
14169       return VT->getBitWidth() == 128;
14170     case HA_UNKNOWN:
14171       switch (VT->getBitWidth()) {
14172       case 64:
14173         Base = HA_VECT64;
14174         return true;
14175       case 128:
14176         Base = HA_VECT128;
14177         return true;
14178       default:
14179         return false;
14180       }
14181     }
14182   }
14183 
14184   return (Members > 0 && Members <= 4);
14185 }
14186 
14187 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
14188 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
14189 /// passing according to AAPCS rules.
14190 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
14191     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
14192   if (getEffectiveCallingConv(CallConv, isVarArg) !=
14193       CallingConv::ARM_AAPCS_VFP)
14194     return false;
14195 
14196   HABaseType Base = HA_UNKNOWN;
14197   uint64_t Members = 0;
14198   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
14199   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
14200 
14201   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
14202   return IsHA || IsIntArray;
14203 }
14204 
14205 unsigned ARMTargetLowering::getExceptionPointerRegister(
14206     const Constant *PersonalityFn) const {
14207   // Platforms which do not use SjLj EH may return values in these registers
14208   // via the personality function.
14209   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
14210 }
14211 
14212 unsigned ARMTargetLowering::getExceptionSelectorRegister(
14213     const Constant *PersonalityFn) const {
14214   // Platforms which do not use SjLj EH may return values in these registers
14215   // via the personality function.
14216   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
14217 }
14218 
14219 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14220   // Update IsSplitCSR in ARMFunctionInfo.
14221   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
14222   AFI->setIsSplitCSR(true);
14223 }
14224 
14225 void ARMTargetLowering::insertCopiesSplitCSR(
14226     MachineBasicBlock *Entry,
14227     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14228   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
14229   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14230   if (!IStart)
14231     return;
14232 
14233   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
14234   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14235   MachineBasicBlock::iterator MBBI = Entry->begin();
14236   for (const MCPhysReg *I = IStart; *I; ++I) {
14237     const TargetRegisterClass *RC = nullptr;
14238     if (ARM::GPRRegClass.contains(*I))
14239       RC = &ARM::GPRRegClass;
14240     else if (ARM::DPRRegClass.contains(*I))
14241       RC = &ARM::DPRRegClass;
14242     else
14243       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14244 
14245     unsigned NewVR = MRI->createVirtualRegister(RC);
14246     // Create copy from CSR to a virtual register.
14247     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14248     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14249     // nounwind. If we want to generalize this later, we may need to emit
14250     // CFI pseudo-instructions.
14251     assert(Entry->getParent()->getFunction()->hasFnAttribute(
14252                Attribute::NoUnwind) &&
14253            "Function should be nounwind in insertCopiesSplitCSR!");
14254     Entry->addLiveIn(*I);
14255     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14256         .addReg(*I);
14257 
14258     // Insert the copy-back instructions right before the terminator.
14259     for (auto *Exit : Exits)
14260       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14261               TII->get(TargetOpcode::COPY), *I)
14262           .addReg(NewVR);
14263   }
14264 }
14265 
14266 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
14267   MF.getFrameInfo().computeMaxCallFrameSize(MF);
14268   TargetLoweringBase::finalizeLowering(MF);
14269 }
14270