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/TargetInstrInfo.h"
61 #include "llvm/CodeGen/TargetLowering.h"
62 #include "llvm/CodeGen/TargetOpcodes.h"
63 #include "llvm/CodeGen/TargetRegisterInfo.h"
64 #include "llvm/CodeGen/TargetSubtargetInfo.h"
65 #include "llvm/CodeGen/ValueTypes.h"
66 #include "llvm/IR/Attributes.h"
67 #include "llvm/IR/CallingConv.h"
68 #include "llvm/IR/Constant.h"
69 #include "llvm/IR/Constants.h"
70 #include "llvm/IR/DataLayout.h"
71 #include "llvm/IR/DebugLoc.h"
72 #include "llvm/IR/DerivedTypes.h"
73 #include "llvm/IR/Function.h"
74 #include "llvm/IR/GlobalAlias.h"
75 #include "llvm/IR/GlobalValue.h"
76 #include "llvm/IR/GlobalVariable.h"
77 #include "llvm/IR/IRBuilder.h"
78 #include "llvm/IR/InlineAsm.h"
79 #include "llvm/IR/Instruction.h"
80 #include "llvm/IR/Instructions.h"
81 #include "llvm/IR/IntrinsicInst.h"
82 #include "llvm/IR/Intrinsics.h"
83 #include "llvm/IR/Module.h"
84 #include "llvm/IR/Type.h"
85 #include "llvm/IR/User.h"
86 #include "llvm/IR/Value.h"
87 #include "llvm/MC/MCInstrDesc.h"
88 #include "llvm/MC/MCInstrItineraries.h"
89 #include "llvm/MC/MCRegisterInfo.h"
90 #include "llvm/MC/MCSchedule.h"
91 #include "llvm/Support/AtomicOrdering.h"
92 #include "llvm/Support/BranchProbability.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CodeGen.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/ErrorHandling.h"
99 #include "llvm/Support/KnownBits.h"
100 #include "llvm/Support/MathExtras.h"
101 #include "llvm/Support/raw_ostream.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.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     bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
235     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
236       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
237                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
238                                        : CallingConv::ARM_AAPCS);
239   }
240 
241   if (Subtarget->isTargetMachO()) {
242     // Uses VFP for Thumb libfuncs if available.
243     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
244         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
245       static const struct {
246         const RTLIB::Libcall Op;
247         const char * const Name;
248         const ISD::CondCode Cond;
249       } LibraryCalls[] = {
250         // Single-precision floating-point arithmetic.
251         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
252         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
253         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
254         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
255 
256         // Double-precision floating-point arithmetic.
257         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
258         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
259         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
260         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
261 
262         // Single-precision comparisons.
263         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
264         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
265         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
266         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
267         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
268         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
269         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
270         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
271 
272         // Double-precision comparisons.
273         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
274         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
275         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
276         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
277         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
278         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
279         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
280         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
281 
282         // Floating-point to integer conversions.
283         // i64 conversions are done via library routines even when generating VFP
284         // instructions, so use the same ones.
285         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
286         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
287         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
288         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
289 
290         // Conversions between floating types.
291         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
292         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
293 
294         // Integer to floating-point conversions.
295         // i64 conversions are done via library routines even when generating VFP
296         // instructions, so use the same ones.
297         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
298         // e.g., __floatunsidf vs. __floatunssidfvfp.
299         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
300         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
301         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
302         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
303       };
304 
305       for (const auto &LC : LibraryCalls) {
306         setLibcallName(LC.Op, LC.Name);
307         if (LC.Cond != ISD::SETCC_INVALID)
308           setCmpLibcallCC(LC.Op, LC.Cond);
309       }
310     }
311 
312     // Set the correct calling convention for ARMv7k WatchOS. It's just
313     // AAPCS_VFP for functions as simple as libcalls.
314     if (Subtarget->isTargetWatchABI()) {
315       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
316         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
317     }
318   }
319 
320   // These libcalls are not available in 32-bit.
321   setLibcallName(RTLIB::SHL_I128, nullptr);
322   setLibcallName(RTLIB::SRL_I128, nullptr);
323   setLibcallName(RTLIB::SRA_I128, nullptr);
324 
325   // RTLIB
326   if (Subtarget->isAAPCS_ABI() &&
327       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
328        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
329     static const struct {
330       const RTLIB::Libcall Op;
331       const char * const Name;
332       const CallingConv::ID CC;
333       const ISD::CondCode Cond;
334     } LibraryCalls[] = {
335       // Double-precision floating-point arithmetic helper functions
336       // RTABI chapter 4.1.2, Table 2
337       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 
342       // Double-precision floating-point comparison helper functions
343       // RTABI chapter 4.1.2, Table 3
344       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
345       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
346       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
347       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
348       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
349       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
350       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
351       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
352 
353       // Single-precision floating-point arithmetic helper functions
354       // RTABI chapter 4.1.2, Table 4
355       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
356       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
357       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
358       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
359 
360       // Single-precision floating-point comparison helper functions
361       // RTABI chapter 4.1.2, Table 5
362       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
363       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
364       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
365       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
366       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
367       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
368       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
369       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
370 
371       // Floating-point to integer conversions.
372       // RTABI chapter 4.1.2, Table 6
373       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
374       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
375       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
376       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
377       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
378       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
379       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
381 
382       // Conversions between floating types.
383       // RTABI chapter 4.1.2, Table 7
384       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
385       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
386       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
387 
388       // Integer to floating-point conversions.
389       // RTABI chapter 4.1.2, Table 8
390       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
391       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
392       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
393       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
394       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
395       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
396       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
397       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
398 
399       // Long long helper functions
400       // RTABI chapter 4.2, Table 9
401       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
402       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
403       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
404       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405 
406       // Integer division functions
407       // RTABI chapter 4.3.1
408       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
409       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
410       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
411       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
412       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
413       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
414       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
415       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
416     };
417 
418     for (const auto &LC : LibraryCalls) {
419       setLibcallName(LC.Op, LC.Name);
420       setLibcallCallingConv(LC.Op, LC.CC);
421       if (LC.Cond != ISD::SETCC_INVALID)
422         setCmpLibcallCC(LC.Op, LC.Cond);
423     }
424 
425     // EABI dependent RTLIB
426     if (TM.Options.EABIVersion == EABI::EABI4 ||
427         TM.Options.EABIVersion == EABI::EABI5) {
428       static const struct {
429         const RTLIB::Libcall Op;
430         const char *const Name;
431         const CallingConv::ID CC;
432         const ISD::CondCode Cond;
433       } MemOpsLibraryCalls[] = {
434         // Memory operations
435         // RTABI chapter 4.3.4
436         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
437         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
438         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
439       };
440 
441       for (const auto &LC : MemOpsLibraryCalls) {
442         setLibcallName(LC.Op, LC.Name);
443         setLibcallCallingConv(LC.Op, LC.CC);
444         if (LC.Cond != ISD::SETCC_INVALID)
445           setCmpLibcallCC(LC.Op, LC.Cond);
446       }
447     }
448   }
449 
450   if (Subtarget->isTargetWindows()) {
451     static const struct {
452       const RTLIB::Libcall Op;
453       const char * const Name;
454       const CallingConv::ID CC;
455     } LibraryCalls[] = {
456       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
457       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
458       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
459       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
460       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
461       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
462       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
463       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
464     };
465 
466     for (const auto &LC : LibraryCalls) {
467       setLibcallName(LC.Op, LC.Name);
468       setLibcallCallingConv(LC.Op, LC.CC);
469     }
470   }
471 
472   // Use divmod compiler-rt calls for iOS 5.0 and later.
473   if (Subtarget->isTargetMachO() &&
474       !(Subtarget->isTargetIOS() &&
475         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
476     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
477     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
478   }
479 
480   // The half <-> float conversion functions are always soft-float on
481   // non-watchos platforms, but are needed for some targets which use a
482   // hard-float calling convention by default.
483   if (!Subtarget->isTargetWatchABI()) {
484     if (Subtarget->isAAPCS_ABI()) {
485       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
486       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
487       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
488     } else {
489       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
490       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
491       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
492     }
493   }
494 
495   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
496   // a __gnu_ prefix (which is the default).
497   if (Subtarget->isTargetAEABI()) {
498     static const struct {
499       const RTLIB::Libcall Op;
500       const char * const Name;
501       const CallingConv::ID CC;
502     } LibraryCalls[] = {
503       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
504       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
505       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
506     };
507 
508     for (const auto &LC : LibraryCalls) {
509       setLibcallName(LC.Op, LC.Name);
510       setLibcallCallingConv(LC.Op, LC.CC);
511     }
512   }
513 
514   if (Subtarget->isThumb1Only())
515     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
516   else
517     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
518 
519   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
520       !Subtarget->isThumb1Only()) {
521     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
522     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
523   }
524 
525   if (Subtarget->hasFullFP16()) {
526     addRegisterClass(MVT::f16, &ARM::HPRRegClass);
527     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
528     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
529     setOperationAction(ISD::BITCAST, MVT::f16, Custom);
530   }
531 
532   for (MVT VT : MVT::vector_valuetypes()) {
533     for (MVT InnerVT : MVT::vector_valuetypes()) {
534       setTruncStoreAction(VT, InnerVT, Expand);
535       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
536       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
537       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
538     }
539 
540     setOperationAction(ISD::MULHS, VT, Expand);
541     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
542     setOperationAction(ISD::MULHU, VT, Expand);
543     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
544 
545     setOperationAction(ISD::BSWAP, VT, Expand);
546   }
547 
548   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
549   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
550 
551   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
552   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
553 
554   if (Subtarget->hasNEON()) {
555     addDRTypeForNEON(MVT::v2f32);
556     addDRTypeForNEON(MVT::v8i8);
557     addDRTypeForNEON(MVT::v4i16);
558     addDRTypeForNEON(MVT::v2i32);
559     addDRTypeForNEON(MVT::v1i64);
560 
561     addQRTypeForNEON(MVT::v4f32);
562     addQRTypeForNEON(MVT::v2f64);
563     addQRTypeForNEON(MVT::v16i8);
564     addQRTypeForNEON(MVT::v8i16);
565     addQRTypeForNEON(MVT::v4i32);
566     addQRTypeForNEON(MVT::v2i64);
567 
568     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
569     // neither Neon nor VFP support any arithmetic operations on it.
570     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
571     // supported for v4f32.
572     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
573     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
574     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
575     // FIXME: Code duplication: FDIV and FREM are expanded always, see
576     // ARMTargetLowering::addTypeForNEON method for details.
577     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
578     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
579     // FIXME: Create unittest.
580     // In another words, find a way when "copysign" appears in DAG with vector
581     // operands.
582     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
583     // FIXME: Code duplication: SETCC has custom operation action, see
584     // ARMTargetLowering::addTypeForNEON method for details.
585     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
586     // FIXME: Create unittest for FNEG and for FABS.
587     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
588     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
589     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
590     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
591     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
592     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
593     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
594     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
595     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
596     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
597     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
598     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
599     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
600     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
601     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
602     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
603     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
604     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
605 
606     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
607     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
608     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
609     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
610     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
611     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
612     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
613     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
614     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
615     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
616     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
617     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
618     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
619     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
620 
621     // Mark v2f32 intrinsics.
622     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
623     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
624     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
625     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
626     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
627     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
628     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
629     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
630     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
631     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
632     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
633     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
634     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
635     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
636 
637     // Neon does not support some operations on v1i64 and v2i64 types.
638     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
639     // Custom handling for some quad-vector types to detect VMULL.
640     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
641     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
642     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
643     // Custom handling for some vector types to avoid expensive expansions
644     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
645     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
646     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
647     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
648     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
649     // a destination type that is wider than the source, and nor does
650     // it have a FP_TO_[SU]INT instruction with a narrower destination than
651     // source.
652     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
653     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
654     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
655     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
656 
657     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
658     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
659 
660     // NEON does not have single instruction CTPOP for vectors with element
661     // types wider than 8-bits.  However, custom lowering can leverage the
662     // v8i8/v16i8 vcnt instruction.
663     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
664     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
665     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
666     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
667     setOperationAction(ISD::CTPOP,      MVT::v1i64, Expand);
668     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
669 
670     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
671     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
672 
673     // NEON does not have single instruction CTTZ for vectors.
674     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
675     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
676     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
677     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
678 
679     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
680     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
681     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
682     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
683 
684     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
685     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
686     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
687     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
688 
689     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
690     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
691     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
692     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
693 
694     // NEON only has FMA instructions as of VFP4.
695     if (!Subtarget->hasVFP4()) {
696       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
697       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
698     }
699 
700     setTargetDAGCombine(ISD::INTRINSIC_VOID);
701     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
702     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
703     setTargetDAGCombine(ISD::SHL);
704     setTargetDAGCombine(ISD::SRL);
705     setTargetDAGCombine(ISD::SRA);
706     setTargetDAGCombine(ISD::SIGN_EXTEND);
707     setTargetDAGCombine(ISD::ZERO_EXTEND);
708     setTargetDAGCombine(ISD::ANY_EXTEND);
709     setTargetDAGCombine(ISD::BUILD_VECTOR);
710     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
711     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
712     setTargetDAGCombine(ISD::STORE);
713     setTargetDAGCombine(ISD::FP_TO_SINT);
714     setTargetDAGCombine(ISD::FP_TO_UINT);
715     setTargetDAGCombine(ISD::FDIV);
716     setTargetDAGCombine(ISD::LOAD);
717 
718     // It is legal to extload from v4i8 to v4i16 or v4i32.
719     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
720                    MVT::v2i32}) {
721       for (MVT VT : MVT::integer_vector_valuetypes()) {
722         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
723         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
724         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
725       }
726     }
727   }
728 
729   if (Subtarget->isFPOnlySP()) {
730     // When targeting a floating-point unit with only single-precision
731     // operations, f64 is legal for the few double-precision instructions which
732     // are present However, no double-precision operations other than moves,
733     // loads and stores are provided by the hardware.
734     setOperationAction(ISD::FADD,       MVT::f64, Expand);
735     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
736     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
737     setOperationAction(ISD::FMA,        MVT::f64, Expand);
738     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
739     setOperationAction(ISD::FREM,       MVT::f64, Expand);
740     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
741     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
742     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
743     setOperationAction(ISD::FABS,       MVT::f64, Expand);
744     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
745     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
746     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
747     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
748     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
749     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
750     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
751     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
752     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
753     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
754     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
755     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
756     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
757     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
758     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
759     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
760     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
761     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
762     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
763     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
764     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
765     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
766   }
767 
768   computeRegisterProperties(Subtarget->getRegisterInfo());
769 
770   // ARM does not have floating-point extending loads.
771   for (MVT VT : MVT::fp_valuetypes()) {
772     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
773     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
774   }
775 
776   // ... or truncating stores
777   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
778   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
779   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
780 
781   // ARM does not have i1 sign extending load.
782   for (MVT VT : MVT::integer_valuetypes())
783     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
784 
785   // ARM supports all 4 flavors of integer indexed load / store.
786   if (!Subtarget->isThumb1Only()) {
787     for (unsigned im = (unsigned)ISD::PRE_INC;
788          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
789       setIndexedLoadAction(im,  MVT::i1,  Legal);
790       setIndexedLoadAction(im,  MVT::i8,  Legal);
791       setIndexedLoadAction(im,  MVT::i16, Legal);
792       setIndexedLoadAction(im,  MVT::i32, Legal);
793       setIndexedStoreAction(im, MVT::i1,  Legal);
794       setIndexedStoreAction(im, MVT::i8,  Legal);
795       setIndexedStoreAction(im, MVT::i16, Legal);
796       setIndexedStoreAction(im, MVT::i32, Legal);
797     }
798   } else {
799     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
800     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
801     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
802   }
803 
804   setOperationAction(ISD::SADDO, MVT::i32, Custom);
805   setOperationAction(ISD::UADDO, MVT::i32, Custom);
806   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
807   setOperationAction(ISD::USUBO, MVT::i32, Custom);
808 
809   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
810   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
811 
812   // i64 operation support.
813   setOperationAction(ISD::MUL,     MVT::i64, Expand);
814   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
815   if (Subtarget->isThumb1Only()) {
816     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
817     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
818   }
819   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
820       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
821     setOperationAction(ISD::MULHS, MVT::i32, Expand);
822 
823   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
824   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
825   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
826   setOperationAction(ISD::SRL,       MVT::i64, Custom);
827   setOperationAction(ISD::SRA,       MVT::i64, Custom);
828   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
829 
830   // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
831   if (Subtarget->isThumb1Only()) {
832     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
833     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
834     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
835   }
836 
837   setOperationAction(ISD::ADDC,      MVT::i32, Custom);
838   setOperationAction(ISD::ADDE,      MVT::i32, Custom);
839   setOperationAction(ISD::SUBC,      MVT::i32, Custom);
840   setOperationAction(ISD::SUBE,      MVT::i32, Custom);
841 
842   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
843     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
844 
845   // ARM does not have ROTL.
846   setOperationAction(ISD::ROTL, MVT::i32, Expand);
847   for (MVT VT : MVT::vector_valuetypes()) {
848     setOperationAction(ISD::ROTL, VT, Expand);
849     setOperationAction(ISD::ROTR, VT, Expand);
850   }
851   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
852   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
853   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
854     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
855 
856   // @llvm.readcyclecounter requires the Performance Monitors extension.
857   // Default to the 0 expansion on unsupported platforms.
858   // FIXME: Technically there are older ARM CPUs that have
859   // implementation-specific ways of obtaining this information.
860   if (Subtarget->hasPerfMon())
861     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
862 
863   // Only ARMv6 has BSWAP.
864   if (!Subtarget->hasV6Ops())
865     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
866 
867   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
868                                         : Subtarget->hasDivideInARMMode();
869   if (!hasDivide) {
870     // These are expanded into libcalls if the cpu doesn't have HW divider.
871     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
872     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
873   }
874 
875   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
876     setOperationAction(ISD::SDIV, MVT::i32, Custom);
877     setOperationAction(ISD::UDIV, MVT::i32, Custom);
878 
879     setOperationAction(ISD::SDIV, MVT::i64, Custom);
880     setOperationAction(ISD::UDIV, MVT::i64, Custom);
881   }
882 
883   setOperationAction(ISD::SREM,  MVT::i32, Expand);
884   setOperationAction(ISD::UREM,  MVT::i32, Expand);
885 
886   // Register based DivRem for AEABI (RTABI 4.2)
887   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
888       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
889       Subtarget->isTargetWindows()) {
890     setOperationAction(ISD::SREM, MVT::i64, Custom);
891     setOperationAction(ISD::UREM, MVT::i64, Custom);
892     HasStandaloneRem = false;
893 
894     if (Subtarget->isTargetWindows()) {
895       const struct {
896         const RTLIB::Libcall Op;
897         const char * const Name;
898         const CallingConv::ID CC;
899       } LibraryCalls[] = {
900         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
901         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
902         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
903         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
904 
905         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
906         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
907         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
908         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
909       };
910 
911       for (const auto &LC : LibraryCalls) {
912         setLibcallName(LC.Op, LC.Name);
913         setLibcallCallingConv(LC.Op, LC.CC);
914       }
915     } else {
916       const struct {
917         const RTLIB::Libcall Op;
918         const char * const Name;
919         const CallingConv::ID CC;
920       } LibraryCalls[] = {
921         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
922         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
923         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
924         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
925 
926         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
927         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
928         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
929         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
930       };
931 
932       for (const auto &LC : LibraryCalls) {
933         setLibcallName(LC.Op, LC.Name);
934         setLibcallCallingConv(LC.Op, LC.CC);
935       }
936     }
937 
938     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
939     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
940     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
941     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
942   } else {
943     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
944     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
945   }
946 
947   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
948     for (auto &VT : {MVT::f32, MVT::f64})
949       setOperationAction(ISD::FPOWI, VT, Custom);
950 
951   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
952   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
953   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
954   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
955 
956   setOperationAction(ISD::TRAP, MVT::Other, Legal);
957 
958   // Use the default implementation.
959   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
960   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
961   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
962   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
963   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
964   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
965 
966   if (Subtarget->isTargetWindows())
967     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
968   else
969     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
970 
971   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
972   // the default expansion.
973   InsertFencesForAtomic = false;
974   if (Subtarget->hasAnyDataBarrier() &&
975       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
976     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
977     // to ldrex/strex loops already.
978     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
979     if (!Subtarget->isThumb() || !Subtarget->isMClass())
980       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
981 
982     // On v8, we have particularly efficient implementations of atomic fences
983     // if they can be combined with nearby atomic loads and stores.
984     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
985       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
986       InsertFencesForAtomic = true;
987     }
988   } else {
989     // If there's anything we can use as a barrier, go through custom lowering
990     // for ATOMIC_FENCE.
991     // If target has DMB in thumb, Fences can be inserted.
992     if (Subtarget->hasDataBarrier())
993       InsertFencesForAtomic = true;
994 
995     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
996                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
997 
998     // Set them all for expansion, which will force libcalls.
999     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1000     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1001     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1002     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1003     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1004     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1005     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1006     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1007     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1008     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1009     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1010     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1011     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1012     // Unordered/Monotonic case.
1013     if (!InsertFencesForAtomic) {
1014       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1015       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1016     }
1017   }
1018 
1019   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1020 
1021   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1022   if (!Subtarget->hasV6Ops()) {
1023     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1024     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1025   }
1026   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1027 
1028   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1029       !Subtarget->isThumb1Only()) {
1030     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1031     // iff target supports vfp2.
1032     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1033     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1034   }
1035 
1036   // We want to custom lower some of our intrinsics.
1037   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1038   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1039   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1040   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1041   if (Subtarget->useSjLjEH())
1042     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1043 
1044   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1045   setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1046   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1047   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1048   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1049   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1050   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1051   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1052   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1053   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1054 
1055   // Thumb-1 cannot currently select ARMISD::SUBE.
1056   if (!Subtarget->isThumb1Only())
1057     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1058 
1059   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1060   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1061   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1062   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1063   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1064 
1065   // We don't support sin/cos/fmod/copysign/pow
1066   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1067   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1068   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1069   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1070   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1071   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1072   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1073   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1074   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1075       !Subtarget->isThumb1Only()) {
1076     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1077     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1078   }
1079   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1080   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1081 
1082   if (!Subtarget->hasVFP4()) {
1083     setOperationAction(ISD::FMA, MVT::f64, Expand);
1084     setOperationAction(ISD::FMA, MVT::f32, Expand);
1085   }
1086 
1087   // Various VFP goodness
1088   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1089     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1090     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1091       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1092       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1093     }
1094 
1095     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1096     if (!Subtarget->hasFP16()) {
1097       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1098       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1099     }
1100   }
1101 
1102   // Use __sincos_stret if available.
1103   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1104       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1105     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1106     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1107   }
1108 
1109   // FP-ARMv8 implements a lot of rounding-like FP operations.
1110   if (Subtarget->hasFPARMv8()) {
1111     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1112     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1113     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1114     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1115     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1116     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1117     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1118     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1119     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1120     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1121     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1122     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1123 
1124     if (!Subtarget->isFPOnlySP()) {
1125       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1126       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1127       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1128       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1129       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1130       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1131       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1132       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1133     }
1134   }
1135 
1136   if (Subtarget->hasNEON()) {
1137     // vmin and vmax aren't available in a scalar form, so we use
1138     // a NEON instruction with an undef lane instead.
1139     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1140     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1141     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1142     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1143     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1144     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1145   }
1146 
1147   // We have target-specific dag combine patterns for the following nodes:
1148   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1149   setTargetDAGCombine(ISD::ADD);
1150   setTargetDAGCombine(ISD::SUB);
1151   setTargetDAGCombine(ISD::MUL);
1152   setTargetDAGCombine(ISD::AND);
1153   setTargetDAGCombine(ISD::OR);
1154   setTargetDAGCombine(ISD::XOR);
1155 
1156   if (Subtarget->hasV6Ops())
1157     setTargetDAGCombine(ISD::SRL);
1158 
1159   setStackPointerRegisterToSaveRestore(ARM::SP);
1160 
1161   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1162       !Subtarget->hasVFP2())
1163     setSchedulingPreference(Sched::RegPressure);
1164   else
1165     setSchedulingPreference(Sched::Hybrid);
1166 
1167   //// temporary - rewrite interface to use type
1168   MaxStoresPerMemset = 8;
1169   MaxStoresPerMemsetOptSize = 4;
1170   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1171   MaxStoresPerMemcpyOptSize = 2;
1172   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1173   MaxStoresPerMemmoveOptSize = 2;
1174 
1175   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1176   // are at least 4 bytes aligned.
1177   setMinStackArgumentAlignment(4);
1178 
1179   // Prefer likely predicted branches to selects on out-of-order cores.
1180   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1181 
1182   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1183 }
1184 
1185 bool ARMTargetLowering::useSoftFloat() const {
1186   return Subtarget->useSoftFloat();
1187 }
1188 
1189 // FIXME: It might make sense to define the representative register class as the
1190 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1191 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1192 // SPR's representative would be DPR_VFP2. This should work well if register
1193 // pressure tracking were modified such that a register use would increment the
1194 // pressure of the register class's representative and all of it's super
1195 // classes' representatives transitively. We have not implemented this because
1196 // of the difficulty prior to coalescing of modeling operand register classes
1197 // due to the common occurrence of cross class copies and subregister insertions
1198 // and extractions.
1199 std::pair<const TargetRegisterClass *, uint8_t>
1200 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1201                                            MVT VT) const {
1202   const TargetRegisterClass *RRC = nullptr;
1203   uint8_t Cost = 1;
1204   switch (VT.SimpleTy) {
1205   default:
1206     return TargetLowering::findRepresentativeClass(TRI, VT);
1207   // Use DPR as representative register class for all floating point
1208   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1209   // the cost is 1 for both f32 and f64.
1210   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1211   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1212     RRC = &ARM::DPRRegClass;
1213     // When NEON is used for SP, only half of the register file is available
1214     // because operations that define both SP and DP results will be constrained
1215     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1216     // coalescing by double-counting the SP regs. See the FIXME above.
1217     if (Subtarget->useNEONForSinglePrecisionFP())
1218       Cost = 2;
1219     break;
1220   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1221   case MVT::v4f32: case MVT::v2f64:
1222     RRC = &ARM::DPRRegClass;
1223     Cost = 2;
1224     break;
1225   case MVT::v4i64:
1226     RRC = &ARM::DPRRegClass;
1227     Cost = 4;
1228     break;
1229   case MVT::v8i64:
1230     RRC = &ARM::DPRRegClass;
1231     Cost = 8;
1232     break;
1233   }
1234   return std::make_pair(RRC, Cost);
1235 }
1236 
1237 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1238   switch ((ARMISD::NodeType)Opcode) {
1239   case ARMISD::FIRST_NUMBER:  break;
1240   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1241   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1242   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1243   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1244   case ARMISD::CALL:          return "ARMISD::CALL";
1245   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1246   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1247   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1248   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1249   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1250   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1251   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1252   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1253   case ARMISD::CMP:           return "ARMISD::CMP";
1254   case ARMISD::CMN:           return "ARMISD::CMN";
1255   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1256   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1257   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1258   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1259   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1260 
1261   case ARMISD::CMOV:          return "ARMISD::CMOV";
1262 
1263   case ARMISD::SSAT:          return "ARMISD::SSAT";
1264   case ARMISD::USAT:          return "ARMISD::USAT";
1265 
1266   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1267   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1268   case ARMISD::RRX:           return "ARMISD::RRX";
1269 
1270   case ARMISD::ADDC:          return "ARMISD::ADDC";
1271   case ARMISD::ADDE:          return "ARMISD::ADDE";
1272   case ARMISD::SUBC:          return "ARMISD::SUBC";
1273   case ARMISD::SUBE:          return "ARMISD::SUBE";
1274 
1275   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1276   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1277   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
1278   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
1279 
1280   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1281   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1282   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1283 
1284   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1285 
1286   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1287 
1288   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1289 
1290   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1291 
1292   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1293 
1294   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1295   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1296 
1297   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1298   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1299   case ARMISD::VCGE:          return "ARMISD::VCGE";
1300   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1301   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1302   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1303   case ARMISD::VCGT:          return "ARMISD::VCGT";
1304   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1305   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1306   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1307   case ARMISD::VTST:          return "ARMISD::VTST";
1308 
1309   case ARMISD::VSHL:          return "ARMISD::VSHL";
1310   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1311   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1312   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1313   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1314   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1315   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1316   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1317   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1318   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1319   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1320   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1321   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1322   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1323   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1324   case ARMISD::VSLI:          return "ARMISD::VSLI";
1325   case ARMISD::VSRI:          return "ARMISD::VSRI";
1326   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1327   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1328   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1329   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1330   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1331   case ARMISD::VDUP:          return "ARMISD::VDUP";
1332   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1333   case ARMISD::VEXT:          return "ARMISD::VEXT";
1334   case ARMISD::VREV64:        return "ARMISD::VREV64";
1335   case ARMISD::VREV32:        return "ARMISD::VREV32";
1336   case ARMISD::VREV16:        return "ARMISD::VREV16";
1337   case ARMISD::VZIP:          return "ARMISD::VZIP";
1338   case ARMISD::VUZP:          return "ARMISD::VUZP";
1339   case ARMISD::VTRN:          return "ARMISD::VTRN";
1340   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1341   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1342   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1343   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1344   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1345   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1346   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1347   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1348   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1349   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1350   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1351   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1352   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1353   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1354   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1355   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1356   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1357   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1358   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1359   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1360   case ARMISD::BFI:           return "ARMISD::BFI";
1361   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1362   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1363   case ARMISD::VBSL:          return "ARMISD::VBSL";
1364   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1365   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1366   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1367   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1368   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1369   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1370   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1371   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1372   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1373   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1374   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1375   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1376   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1377   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1378   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1379   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1380   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1381   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1382   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1383   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1384   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1385   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1386   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1387   }
1388   return nullptr;
1389 }
1390 
1391 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1392                                           EVT VT) const {
1393   if (!VT.isVector())
1394     return getPointerTy(DL);
1395   return VT.changeVectorElementTypeToInteger();
1396 }
1397 
1398 /// getRegClassFor - Return the register class that should be used for the
1399 /// specified value type.
1400 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1401   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1402   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1403   // load / store 4 to 8 consecutive D registers.
1404   if (Subtarget->hasNEON()) {
1405     if (VT == MVT::v4i64)
1406       return &ARM::QQPRRegClass;
1407     if (VT == MVT::v8i64)
1408       return &ARM::QQQQPRRegClass;
1409   }
1410   return TargetLowering::getRegClassFor(VT);
1411 }
1412 
1413 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1414 // source/dest is aligned and the copy size is large enough. We therefore want
1415 // to align such objects passed to memory intrinsics.
1416 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1417                                                unsigned &PrefAlign) const {
1418   if (!isa<MemIntrinsic>(CI))
1419     return false;
1420   MinSize = 8;
1421   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1422   // cycle faster than 4-byte aligned LDM.
1423   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1424   return true;
1425 }
1426 
1427 // Create a fast isel object.
1428 FastISel *
1429 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1430                                   const TargetLibraryInfo *libInfo) const {
1431   return ARM::createFastISel(funcInfo, libInfo);
1432 }
1433 
1434 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1435   unsigned NumVals = N->getNumValues();
1436   if (!NumVals)
1437     return Sched::RegPressure;
1438 
1439   for (unsigned i = 0; i != NumVals; ++i) {
1440     EVT VT = N->getValueType(i);
1441     if (VT == MVT::Glue || VT == MVT::Other)
1442       continue;
1443     if (VT.isFloatingPoint() || VT.isVector())
1444       return Sched::ILP;
1445   }
1446 
1447   if (!N->isMachineOpcode())
1448     return Sched::RegPressure;
1449 
1450   // Load are scheduled for latency even if there instruction itinerary
1451   // is not available.
1452   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1453   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1454 
1455   if (MCID.getNumDefs() == 0)
1456     return Sched::RegPressure;
1457   if (!Itins->isEmpty() &&
1458       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1459     return Sched::ILP;
1460 
1461   return Sched::RegPressure;
1462 }
1463 
1464 //===----------------------------------------------------------------------===//
1465 // Lowering Code
1466 //===----------------------------------------------------------------------===//
1467 
1468 static bool isSRL16(const SDValue &Op) {
1469   if (Op.getOpcode() != ISD::SRL)
1470     return false;
1471   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1472     return Const->getZExtValue() == 16;
1473   return false;
1474 }
1475 
1476 static bool isSRA16(const SDValue &Op) {
1477   if (Op.getOpcode() != ISD::SRA)
1478     return false;
1479   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1480     return Const->getZExtValue() == 16;
1481   return false;
1482 }
1483 
1484 static bool isSHL16(const SDValue &Op) {
1485   if (Op.getOpcode() != ISD::SHL)
1486     return false;
1487   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1488     return Const->getZExtValue() == 16;
1489   return false;
1490 }
1491 
1492 // Check for a signed 16-bit value. We special case SRA because it makes it
1493 // more simple when also looking for SRAs that aren't sign extending a
1494 // smaller value. Without the check, we'd need to take extra care with
1495 // checking order for some operations.
1496 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1497   if (isSRA16(Op))
1498     return isSHL16(Op.getOperand(0));
1499   return DAG.ComputeNumSignBits(Op) == 17;
1500 }
1501 
1502 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1503 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1504   switch (CC) {
1505   default: llvm_unreachable("Unknown condition code!");
1506   case ISD::SETNE:  return ARMCC::NE;
1507   case ISD::SETEQ:  return ARMCC::EQ;
1508   case ISD::SETGT:  return ARMCC::GT;
1509   case ISD::SETGE:  return ARMCC::GE;
1510   case ISD::SETLT:  return ARMCC::LT;
1511   case ISD::SETLE:  return ARMCC::LE;
1512   case ISD::SETUGT: return ARMCC::HI;
1513   case ISD::SETUGE: return ARMCC::HS;
1514   case ISD::SETULT: return ARMCC::LO;
1515   case ISD::SETULE: return ARMCC::LS;
1516   }
1517 }
1518 
1519 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1520 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1521                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1522   CondCode2 = ARMCC::AL;
1523   InvalidOnQNaN = true;
1524   switch (CC) {
1525   default: llvm_unreachable("Unknown FP condition!");
1526   case ISD::SETEQ:
1527   case ISD::SETOEQ:
1528     CondCode = ARMCC::EQ;
1529     InvalidOnQNaN = false;
1530     break;
1531   case ISD::SETGT:
1532   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1533   case ISD::SETGE:
1534   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1535   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1536   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1537   case ISD::SETONE:
1538     CondCode = ARMCC::MI;
1539     CondCode2 = ARMCC::GT;
1540     InvalidOnQNaN = false;
1541     break;
1542   case ISD::SETO:   CondCode = ARMCC::VC; break;
1543   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1544   case ISD::SETUEQ:
1545     CondCode = ARMCC::EQ;
1546     CondCode2 = ARMCC::VS;
1547     InvalidOnQNaN = false;
1548     break;
1549   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1550   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1551   case ISD::SETLT:
1552   case ISD::SETULT: CondCode = ARMCC::LT; break;
1553   case ISD::SETLE:
1554   case ISD::SETULE: CondCode = ARMCC::LE; break;
1555   case ISD::SETNE:
1556   case ISD::SETUNE:
1557     CondCode = ARMCC::NE;
1558     InvalidOnQNaN = false;
1559     break;
1560   }
1561 }
1562 
1563 //===----------------------------------------------------------------------===//
1564 //                      Calling Convention Implementation
1565 //===----------------------------------------------------------------------===//
1566 
1567 #include "ARMGenCallingConv.inc"
1568 
1569 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1570 /// account presence of floating point hardware and calling convention
1571 /// limitations, such as support for variadic functions.
1572 CallingConv::ID
1573 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1574                                            bool isVarArg) const {
1575   switch (CC) {
1576   default:
1577     report_fatal_error("Unsupported calling convention");
1578   case CallingConv::ARM_AAPCS:
1579   case CallingConv::ARM_APCS:
1580   case CallingConv::GHC:
1581     return CC;
1582   case CallingConv::PreserveMost:
1583     return CallingConv::PreserveMost;
1584   case CallingConv::ARM_AAPCS_VFP:
1585   case CallingConv::Swift:
1586     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1587   case CallingConv::C:
1588     if (!Subtarget->isAAPCS_ABI())
1589       return CallingConv::ARM_APCS;
1590     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1591              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1592              !isVarArg)
1593       return CallingConv::ARM_AAPCS_VFP;
1594     else
1595       return CallingConv::ARM_AAPCS;
1596   case CallingConv::Fast:
1597   case CallingConv::CXX_FAST_TLS:
1598     if (!Subtarget->isAAPCS_ABI()) {
1599       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1600         return CallingConv::Fast;
1601       return CallingConv::ARM_APCS;
1602     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1603       return CallingConv::ARM_AAPCS_VFP;
1604     else
1605       return CallingConv::ARM_AAPCS;
1606   }
1607 }
1608 
1609 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1610                                                  bool isVarArg) const {
1611   return CCAssignFnForNode(CC, false, isVarArg);
1612 }
1613 
1614 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1615                                                    bool isVarArg) const {
1616   return CCAssignFnForNode(CC, true, isVarArg);
1617 }
1618 
1619 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1620 /// CallingConvention.
1621 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1622                                                  bool Return,
1623                                                  bool isVarArg) const {
1624   switch (getEffectiveCallingConv(CC, isVarArg)) {
1625   default:
1626     report_fatal_error("Unsupported calling convention");
1627   case CallingConv::ARM_APCS:
1628     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1629   case CallingConv::ARM_AAPCS:
1630     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1631   case CallingConv::ARM_AAPCS_VFP:
1632     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1633   case CallingConv::Fast:
1634     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1635   case CallingConv::GHC:
1636     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1637   case CallingConv::PreserveMost:
1638     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1639   }
1640 }
1641 
1642 /// LowerCallResult - Lower the result values of a call into the
1643 /// appropriate copies out of appropriate physical registers.
1644 SDValue ARMTargetLowering::LowerCallResult(
1645     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1646     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1647     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1648     SDValue ThisVal) const {
1649   // Assign locations to each value returned by this call.
1650   SmallVector<CCValAssign, 16> RVLocs;
1651   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1652                  *DAG.getContext());
1653   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1654 
1655   // Copy all of the result registers out of their specified physreg.
1656   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1657     CCValAssign VA = RVLocs[i];
1658 
1659     // Pass 'this' value directly from the argument to return value, to avoid
1660     // reg unit interference
1661     if (i == 0 && isThisReturn) {
1662       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1663              "unexpected return calling convention register assignment");
1664       InVals.push_back(ThisVal);
1665       continue;
1666     }
1667 
1668     SDValue Val;
1669     if (VA.needsCustom()) {
1670       // Handle f64 or half of a v2f64.
1671       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1672                                       InFlag);
1673       Chain = Lo.getValue(1);
1674       InFlag = Lo.getValue(2);
1675       VA = RVLocs[++i]; // skip ahead to next loc
1676       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1677                                       InFlag);
1678       Chain = Hi.getValue(1);
1679       InFlag = Hi.getValue(2);
1680       if (!Subtarget->isLittle())
1681         std::swap (Lo, Hi);
1682       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1683 
1684       if (VA.getLocVT() == MVT::v2f64) {
1685         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1686         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1687                           DAG.getConstant(0, dl, MVT::i32));
1688 
1689         VA = RVLocs[++i]; // skip ahead to next loc
1690         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1691         Chain = Lo.getValue(1);
1692         InFlag = Lo.getValue(2);
1693         VA = RVLocs[++i]; // skip ahead to next loc
1694         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1695         Chain = Hi.getValue(1);
1696         InFlag = Hi.getValue(2);
1697         if (!Subtarget->isLittle())
1698           std::swap (Lo, Hi);
1699         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1700         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1701                           DAG.getConstant(1, dl, MVT::i32));
1702       }
1703     } else {
1704       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1705                                InFlag);
1706       Chain = Val.getValue(1);
1707       InFlag = Val.getValue(2);
1708     }
1709 
1710     switch (VA.getLocInfo()) {
1711     default: llvm_unreachable("Unknown loc info!");
1712     case CCValAssign::Full: break;
1713     case CCValAssign::BCvt:
1714       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1715       break;
1716     }
1717 
1718     InVals.push_back(Val);
1719   }
1720 
1721   return Chain;
1722 }
1723 
1724 /// LowerMemOpCallTo - Store the argument to the stack.
1725 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1726                                             SDValue Arg, const SDLoc &dl,
1727                                             SelectionDAG &DAG,
1728                                             const CCValAssign &VA,
1729                                             ISD::ArgFlagsTy Flags) const {
1730   unsigned LocMemOffset = VA.getLocMemOffset();
1731   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1732   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1733                        StackPtr, PtrOff);
1734   return DAG.getStore(
1735       Chain, dl, Arg, PtrOff,
1736       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1737 }
1738 
1739 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1740                                          SDValue Chain, SDValue &Arg,
1741                                          RegsToPassVector &RegsToPass,
1742                                          CCValAssign &VA, CCValAssign &NextVA,
1743                                          SDValue &StackPtr,
1744                                          SmallVectorImpl<SDValue> &MemOpChains,
1745                                          ISD::ArgFlagsTy Flags) const {
1746   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1747                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1748   unsigned id = Subtarget->isLittle() ? 0 : 1;
1749   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1750 
1751   if (NextVA.isRegLoc())
1752     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1753   else {
1754     assert(NextVA.isMemLoc());
1755     if (!StackPtr.getNode())
1756       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1757                                     getPointerTy(DAG.getDataLayout()));
1758 
1759     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1760                                            dl, DAG, NextVA,
1761                                            Flags));
1762   }
1763 }
1764 
1765 /// LowerCall - Lowering a call into a callseq_start <-
1766 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1767 /// nodes.
1768 SDValue
1769 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1770                              SmallVectorImpl<SDValue> &InVals) const {
1771   SelectionDAG &DAG                     = CLI.DAG;
1772   SDLoc &dl                             = CLI.DL;
1773   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1774   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1775   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1776   SDValue Chain                         = CLI.Chain;
1777   SDValue Callee                        = CLI.Callee;
1778   bool &isTailCall                      = CLI.IsTailCall;
1779   CallingConv::ID CallConv              = CLI.CallConv;
1780   bool doesNotRet                       = CLI.DoesNotReturn;
1781   bool isVarArg                         = CLI.IsVarArg;
1782 
1783   MachineFunction &MF = DAG.getMachineFunction();
1784   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1785   bool isThisReturn   = false;
1786   bool isSibCall      = false;
1787   auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
1788 
1789   // Disable tail calls if they're not supported.
1790   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1791     isTailCall = false;
1792 
1793   if (isTailCall) {
1794     // Check if it's really possible to do a tail call.
1795     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1796                     isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(),
1797                                                    Outs, OutVals, Ins, DAG);
1798     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1799       report_fatal_error("failed to perform tail call elimination on a call "
1800                          "site marked musttail");
1801     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1802     // detected sibcalls.
1803     if (isTailCall) {
1804       ++NumTailCalls;
1805       isSibCall = true;
1806     }
1807   }
1808 
1809   // Analyze operands of the call, assigning locations to each operand.
1810   SmallVector<CCValAssign, 16> ArgLocs;
1811   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1812                  *DAG.getContext());
1813   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1814 
1815   // Get a count of how many bytes are to be pushed on the stack.
1816   unsigned NumBytes = CCInfo.getNextStackOffset();
1817 
1818   // For tail calls, memory operands are available in our caller's stack.
1819   if (isSibCall)
1820     NumBytes = 0;
1821 
1822   // Adjust the stack pointer for the new arguments...
1823   // These operations are automatically eliminated by the prolog/epilog pass
1824   if (!isSibCall)
1825     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1826 
1827   SDValue StackPtr =
1828       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1829 
1830   RegsToPassVector RegsToPass;
1831   SmallVector<SDValue, 8> MemOpChains;
1832 
1833   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1834   // of tail call optimization, arguments are handled later.
1835   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1836        i != e;
1837        ++i, ++realArgIdx) {
1838     CCValAssign &VA = ArgLocs[i];
1839     SDValue Arg = OutVals[realArgIdx];
1840     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1841     bool isByVal = Flags.isByVal();
1842 
1843     // Promote the value if needed.
1844     switch (VA.getLocInfo()) {
1845     default: llvm_unreachable("Unknown loc info!");
1846     case CCValAssign::Full: break;
1847     case CCValAssign::SExt:
1848       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1849       break;
1850     case CCValAssign::ZExt:
1851       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1852       break;
1853     case CCValAssign::AExt:
1854       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1855       break;
1856     case CCValAssign::BCvt:
1857       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1858       break;
1859     }
1860 
1861     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1862     if (VA.needsCustom()) {
1863       if (VA.getLocVT() == MVT::v2f64) {
1864         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1865                                   DAG.getConstant(0, dl, MVT::i32));
1866         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1867                                   DAG.getConstant(1, dl, MVT::i32));
1868 
1869         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1870                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1871 
1872         VA = ArgLocs[++i]; // skip ahead to next loc
1873         if (VA.isRegLoc()) {
1874           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1875                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1876         } else {
1877           assert(VA.isMemLoc());
1878 
1879           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1880                                                  dl, DAG, VA, Flags));
1881         }
1882       } else {
1883         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1884                          StackPtr, MemOpChains, Flags);
1885       }
1886     } else if (VA.isRegLoc()) {
1887       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1888           Outs[0].VT == MVT::i32) {
1889         assert(VA.getLocVT() == MVT::i32 &&
1890                "unexpected calling convention register assignment");
1891         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1892                "unexpected use of 'returned'");
1893         isThisReturn = true;
1894       }
1895       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1896     } else if (isByVal) {
1897       assert(VA.isMemLoc());
1898       unsigned offset = 0;
1899 
1900       // True if this byval aggregate will be split between registers
1901       // and memory.
1902       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1903       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1904 
1905       if (CurByValIdx < ByValArgsCount) {
1906 
1907         unsigned RegBegin, RegEnd;
1908         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1909 
1910         EVT PtrVT =
1911             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1912         unsigned int i, j;
1913         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1914           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1915           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1916           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1917                                      MachinePointerInfo(),
1918                                      DAG.InferPtrAlignment(AddArg));
1919           MemOpChains.push_back(Load.getValue(1));
1920           RegsToPass.push_back(std::make_pair(j, Load));
1921         }
1922 
1923         // If parameter size outsides register area, "offset" value
1924         // helps us to calculate stack slot for remained part properly.
1925         offset = RegEnd - RegBegin;
1926 
1927         CCInfo.nextInRegsParam();
1928       }
1929 
1930       if (Flags.getByValSize() > 4*offset) {
1931         auto PtrVT = getPointerTy(DAG.getDataLayout());
1932         unsigned LocMemOffset = VA.getLocMemOffset();
1933         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1934         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1935         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1936         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1937         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1938                                            MVT::i32);
1939         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1940                                             MVT::i32);
1941 
1942         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1943         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1944         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1945                                           Ops));
1946       }
1947     } else if (!isSibCall) {
1948       assert(VA.isMemLoc());
1949 
1950       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1951                                              dl, DAG, VA, Flags));
1952     }
1953   }
1954 
1955   if (!MemOpChains.empty())
1956     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1957 
1958   // Build a sequence of copy-to-reg nodes chained together with token chain
1959   // and flag operands which copy the outgoing args into the appropriate regs.
1960   SDValue InFlag;
1961   // Tail call byval lowering might overwrite argument registers so in case of
1962   // tail call optimization the copies to registers are lowered later.
1963   if (!isTailCall)
1964     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1965       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1966                                RegsToPass[i].second, InFlag);
1967       InFlag = Chain.getValue(1);
1968     }
1969 
1970   // For tail calls lower the arguments to the 'real' stack slot.
1971   if (isTailCall) {
1972     // Force all the incoming stack arguments to be loaded from the stack
1973     // before any new outgoing arguments are stored to the stack, because the
1974     // outgoing stack slots may alias the incoming argument stack slots, and
1975     // the alias isn't otherwise explicit. This is slightly more conservative
1976     // than necessary, because it means that each store effectively depends
1977     // on every argument instead of just those arguments it would clobber.
1978 
1979     // Do not flag preceding copytoreg stuff together with the following stuff.
1980     InFlag = SDValue();
1981     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1982       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1983                                RegsToPass[i].second, InFlag);
1984       InFlag = Chain.getValue(1);
1985     }
1986     InFlag = SDValue();
1987   }
1988 
1989   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1990   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1991   // node so that legalize doesn't hack it.
1992   bool isDirect = false;
1993 
1994   const TargetMachine &TM = getTargetMachine();
1995   const Module *Mod = MF.getFunction().getParent();
1996   const GlobalValue *GV = nullptr;
1997   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1998     GV = G->getGlobal();
1999   bool isStub =
2000       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2001 
2002   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2003   bool isLocalARMFunc = false;
2004   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2005   auto PtrVt = getPointerTy(DAG.getDataLayout());
2006 
2007   if (Subtarget->genLongCalls()) {
2008     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2009            "long-calls codegen is not position independent!");
2010     // Handle a global address or an external symbol. If it's not one of
2011     // those, the target's already in a register, so we don't need to do
2012     // anything extra.
2013     if (isa<GlobalAddressSDNode>(Callee)) {
2014       // Create a constant pool entry for the callee address
2015       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2016       ARMConstantPoolValue *CPV =
2017         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2018 
2019       // Get the address of the callee into a register
2020       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2021       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2022       Callee = DAG.getLoad(
2023           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2024           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2025     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2026       const char *Sym = S->getSymbol();
2027 
2028       // Create a constant pool entry for the callee address
2029       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2030       ARMConstantPoolValue *CPV =
2031         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2032                                       ARMPCLabelIndex, 0);
2033       // Get the address of the callee into a register
2034       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2035       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2036       Callee = DAG.getLoad(
2037           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2038           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2039     }
2040   } else if (isa<GlobalAddressSDNode>(Callee)) {
2041     // If we're optimizing for minimum size and the function is called three or
2042     // more times in this block, we can improve codesize by calling indirectly
2043     // as BLXr has a 16-bit encoding.
2044     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2045     auto *BB = CLI.CS.getParent();
2046     bool PreferIndirect =
2047         Subtarget->isThumb() && MF.getFunction().optForMinSize() &&
2048         count_if(GV->users(), [&BB](const User *U) {
2049           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2050         }) > 2;
2051 
2052     if (!PreferIndirect) {
2053       isDirect = true;
2054       bool isDef = GV->isStrongDefinitionForLinker();
2055 
2056       // ARM call to a local ARM function is predicable.
2057       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2058       // tBX takes a register source operand.
2059       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2060         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2061         Callee = DAG.getNode(
2062             ARMISD::WrapperPIC, dl, PtrVt,
2063             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2064         Callee = DAG.getLoad(
2065             PtrVt, dl, DAG.getEntryNode(), Callee,
2066             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2067             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2068                                      MachineMemOperand::MOInvariant);
2069       } else if (Subtarget->isTargetCOFF()) {
2070         assert(Subtarget->isTargetWindows() &&
2071                "Windows is the only supported COFF target");
2072         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2073                                    ? ARMII::MO_DLLIMPORT
2074                                    : ARMII::MO_NO_FLAG;
2075         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2076                                             TargetFlags);
2077         if (GV->hasDLLImportStorageClass())
2078           Callee =
2079               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2080                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2081                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2082       } else {
2083         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2084       }
2085     }
2086   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2087     isDirect = true;
2088     // tBX takes a register source operand.
2089     const char *Sym = S->getSymbol();
2090     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2091       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2092       ARMConstantPoolValue *CPV =
2093         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2094                                       ARMPCLabelIndex, 4);
2095       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2096       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2097       Callee = DAG.getLoad(
2098           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2099           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2100       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2101       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2102     } else {
2103       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2104     }
2105   }
2106 
2107   // FIXME: handle tail calls differently.
2108   unsigned CallOpc;
2109   if (Subtarget->isThumb()) {
2110     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2111       CallOpc = ARMISD::CALL_NOLINK;
2112     else
2113       CallOpc = ARMISD::CALL;
2114   } else {
2115     if (!isDirect && !Subtarget->hasV5TOps())
2116       CallOpc = ARMISD::CALL_NOLINK;
2117     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2118              // Emit regular call when code size is the priority
2119              !MF.getFunction().optForMinSize())
2120       // "mov lr, pc; b _foo" to avoid confusing the RSP
2121       CallOpc = ARMISD::CALL_NOLINK;
2122     else
2123       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2124   }
2125 
2126   std::vector<SDValue> Ops;
2127   Ops.push_back(Chain);
2128   Ops.push_back(Callee);
2129 
2130   // Add argument registers to the end of the list so that they are known live
2131   // into the call.
2132   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2133     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2134                                   RegsToPass[i].second.getValueType()));
2135 
2136   // Add a register mask operand representing the call-preserved registers.
2137   if (!isTailCall) {
2138     const uint32_t *Mask;
2139     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2140     if (isThisReturn) {
2141       // For 'this' returns, use the R0-preserving mask if applicable
2142       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2143       if (!Mask) {
2144         // Set isThisReturn to false if the calling convention is not one that
2145         // allows 'returned' to be modeled in this way, so LowerCallResult does
2146         // not try to pass 'this' straight through
2147         isThisReturn = false;
2148         Mask = ARI->getCallPreservedMask(MF, CallConv);
2149       }
2150     } else
2151       Mask = ARI->getCallPreservedMask(MF, CallConv);
2152 
2153     assert(Mask && "Missing call preserved mask for calling convention");
2154     Ops.push_back(DAG.getRegisterMask(Mask));
2155   }
2156 
2157   if (InFlag.getNode())
2158     Ops.push_back(InFlag);
2159 
2160   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2161   if (isTailCall) {
2162     MF.getFrameInfo().setHasTailCall();
2163     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2164   }
2165 
2166   // Returns a chain and a flag for retval copy to use.
2167   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2168   InFlag = Chain.getValue(1);
2169 
2170   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2171                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2172   if (!Ins.empty())
2173     InFlag = Chain.getValue(1);
2174 
2175   // Handle result values, copying them out of physregs into vregs that we
2176   // return.
2177   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2178                          InVals, isThisReturn,
2179                          isThisReturn ? OutVals[0] : SDValue());
2180 }
2181 
2182 /// HandleByVal - Every parameter *after* a byval parameter is passed
2183 /// on the stack.  Remember the next parameter register to allocate,
2184 /// and then confiscate the rest of the parameter registers to insure
2185 /// this.
2186 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2187                                     unsigned Align) const {
2188   // Byval (as with any stack) slots are always at least 4 byte aligned.
2189   Align = std::max(Align, 4U);
2190 
2191   unsigned Reg = State->AllocateReg(GPRArgRegs);
2192   if (!Reg)
2193     return;
2194 
2195   unsigned AlignInRegs = Align / 4;
2196   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2197   for (unsigned i = 0; i < Waste; ++i)
2198     Reg = State->AllocateReg(GPRArgRegs);
2199 
2200   if (!Reg)
2201     return;
2202 
2203   unsigned Excess = 4 * (ARM::R4 - Reg);
2204 
2205   // Special case when NSAA != SP and parameter size greater than size of
2206   // all remained GPR regs. In that case we can't split parameter, we must
2207   // send it to stack. We also must set NCRN to R4, so waste all
2208   // remained registers.
2209   const unsigned NSAAOffset = State->getNextStackOffset();
2210   if (NSAAOffset != 0 && Size > Excess) {
2211     while (State->AllocateReg(GPRArgRegs))
2212       ;
2213     return;
2214   }
2215 
2216   // First register for byval parameter is the first register that wasn't
2217   // allocated before this method call, so it would be "reg".
2218   // If parameter is small enough to be saved in range [reg, r4), then
2219   // the end (first after last) register would be reg + param-size-in-regs,
2220   // else parameter would be splitted between registers and stack,
2221   // end register would be r4 in this case.
2222   unsigned ByValRegBegin = Reg;
2223   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2224   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2225   // Note, first register is allocated in the beginning of function already,
2226   // allocate remained amount of registers we need.
2227   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2228     State->AllocateReg(GPRArgRegs);
2229   // A byval parameter that is split between registers and memory needs its
2230   // size truncated here.
2231   // In the case where the entire structure fits in registers, we set the
2232   // size in memory to zero.
2233   Size = std::max<int>(Size - Excess, 0);
2234 }
2235 
2236 /// MatchingStackOffset - Return true if the given stack call argument is
2237 /// already available in the same position (relatively) of the caller's
2238 /// incoming argument stack.
2239 static
2240 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2241                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2242                          const TargetInstrInfo *TII) {
2243   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2244   int FI = std::numeric_limits<int>::max();
2245   if (Arg.getOpcode() == ISD::CopyFromReg) {
2246     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2247     if (!TargetRegisterInfo::isVirtualRegister(VR))
2248       return false;
2249     MachineInstr *Def = MRI->getVRegDef(VR);
2250     if (!Def)
2251       return false;
2252     if (!Flags.isByVal()) {
2253       if (!TII->isLoadFromStackSlot(*Def, FI))
2254         return false;
2255     } else {
2256       return false;
2257     }
2258   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2259     if (Flags.isByVal())
2260       // ByVal argument is passed in as a pointer but it's now being
2261       // dereferenced. e.g.
2262       // define @foo(%struct.X* %A) {
2263       //   tail call @bar(%struct.X* byval %A)
2264       // }
2265       return false;
2266     SDValue Ptr = Ld->getBasePtr();
2267     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2268     if (!FINode)
2269       return false;
2270     FI = FINode->getIndex();
2271   } else
2272     return false;
2273 
2274   assert(FI != std::numeric_limits<int>::max());
2275   if (!MFI.isFixedObjectIndex(FI))
2276     return false;
2277   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2278 }
2279 
2280 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2281 /// for tail call optimization. Targets which want to do tail call
2282 /// optimization should implement this function.
2283 bool
2284 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2285                                                      CallingConv::ID CalleeCC,
2286                                                      bool isVarArg,
2287                                                      bool isCalleeStructRet,
2288                                                      bool isCallerStructRet,
2289                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2290                                     const SmallVectorImpl<SDValue> &OutVals,
2291                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2292                                                      SelectionDAG& DAG) const {
2293   MachineFunction &MF = DAG.getMachineFunction();
2294   const Function &CallerF = MF.getFunction();
2295   CallingConv::ID CallerCC = CallerF.getCallingConv();
2296 
2297   assert(Subtarget->supportsTailCall());
2298 
2299   // Tail calls to function pointers cannot be optimized for Thumb1 if the args
2300   // to the call take up r0-r3. The reason is that there are no legal registers
2301   // left to hold the pointer to the function to be called.
2302   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2303       !isa<GlobalAddressSDNode>(Callee.getNode()))
2304       return false;
2305 
2306   // Look for obvious safe cases to perform tail call optimization that do not
2307   // require ABI changes. This is what gcc calls sibcall.
2308 
2309   // Exception-handling functions need a special set of instructions to indicate
2310   // a return to the hardware. Tail-calling another function would probably
2311   // break this.
2312   if (CallerF.hasFnAttribute("interrupt"))
2313     return false;
2314 
2315   // Also avoid sibcall optimization if either caller or callee uses struct
2316   // return semantics.
2317   if (isCalleeStructRet || isCallerStructRet)
2318     return false;
2319 
2320   // Externally-defined functions with weak linkage should not be
2321   // tail-called on ARM when the OS does not support dynamic
2322   // pre-emption of symbols, as the AAELF spec requires normal calls
2323   // to undefined weak functions to be replaced with a NOP or jump to the
2324   // next instruction. The behaviour of branch instructions in this
2325   // situation (as used for tail calls) is implementation-defined, so we
2326   // cannot rely on the linker replacing the tail call with a return.
2327   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2328     const GlobalValue *GV = G->getGlobal();
2329     const Triple &TT = getTargetMachine().getTargetTriple();
2330     if (GV->hasExternalWeakLinkage() &&
2331         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2332       return false;
2333   }
2334 
2335   // Check that the call results are passed in the same way.
2336   LLVMContext &C = *DAG.getContext();
2337   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2338                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2339                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2340     return false;
2341   // The callee has to preserve all registers the caller needs to preserve.
2342   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2343   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2344   if (CalleeCC != CallerCC) {
2345     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2346     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2347       return false;
2348   }
2349 
2350   // If Caller's vararg or byval argument has been split between registers and
2351   // stack, do not perform tail call, since part of the argument is in caller's
2352   // local frame.
2353   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2354   if (AFI_Caller->getArgRegsSaveSize())
2355     return false;
2356 
2357   // If the callee takes no arguments then go on to check the results of the
2358   // call.
2359   if (!Outs.empty()) {
2360     // Check if stack adjustment is needed. For now, do not do this if any
2361     // argument is passed on the stack.
2362     SmallVector<CCValAssign, 16> ArgLocs;
2363     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2364     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2365     if (CCInfo.getNextStackOffset()) {
2366       // Check if the arguments are already laid out in the right way as
2367       // the caller's fixed stack objects.
2368       MachineFrameInfo &MFI = MF.getFrameInfo();
2369       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2370       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2371       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2372            i != e;
2373            ++i, ++realArgIdx) {
2374         CCValAssign &VA = ArgLocs[i];
2375         EVT RegVT = VA.getLocVT();
2376         SDValue Arg = OutVals[realArgIdx];
2377         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2378         if (VA.getLocInfo() == CCValAssign::Indirect)
2379           return false;
2380         if (VA.needsCustom()) {
2381           // f64 and vector types are split into multiple registers or
2382           // register/stack-slot combinations.  The types will not match
2383           // the registers; give up on memory f64 refs until we figure
2384           // out what to do about this.
2385           if (!VA.isRegLoc())
2386             return false;
2387           if (!ArgLocs[++i].isRegLoc())
2388             return false;
2389           if (RegVT == MVT::v2f64) {
2390             if (!ArgLocs[++i].isRegLoc())
2391               return false;
2392             if (!ArgLocs[++i].isRegLoc())
2393               return false;
2394           }
2395         } else if (!VA.isRegLoc()) {
2396           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2397                                    MFI, MRI, TII))
2398             return false;
2399         }
2400       }
2401     }
2402 
2403     const MachineRegisterInfo &MRI = MF.getRegInfo();
2404     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2405       return false;
2406   }
2407 
2408   return true;
2409 }
2410 
2411 bool
2412 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2413                                   MachineFunction &MF, bool isVarArg,
2414                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2415                                   LLVMContext &Context) const {
2416   SmallVector<CCValAssign, 16> RVLocs;
2417   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2418   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2419 }
2420 
2421 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2422                                     const SDLoc &DL, SelectionDAG &DAG) {
2423   const MachineFunction &MF = DAG.getMachineFunction();
2424   const Function &F = MF.getFunction();
2425 
2426   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2427 
2428   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2429   // version of the "preferred return address". These offsets affect the return
2430   // instruction if this is a return from PL1 without hypervisor extensions.
2431   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2432   //    SWI:     0      "subs pc, lr, #0"
2433   //    ABORT:   +4     "subs pc, lr, #4"
2434   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2435   // UNDEF varies depending on where the exception came from ARM or Thumb
2436   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2437 
2438   int64_t LROffset;
2439   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2440       IntKind == "ABORT")
2441     LROffset = 4;
2442   else if (IntKind == "SWI" || IntKind == "UNDEF")
2443     LROffset = 0;
2444   else
2445     report_fatal_error("Unsupported interrupt attribute. If present, value "
2446                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2447 
2448   RetOps.insert(RetOps.begin() + 1,
2449                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2450 
2451   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2452 }
2453 
2454 SDValue
2455 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2456                                bool isVarArg,
2457                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2458                                const SmallVectorImpl<SDValue> &OutVals,
2459                                const SDLoc &dl, SelectionDAG &DAG) const {
2460   // CCValAssign - represent the assignment of the return value to a location.
2461   SmallVector<CCValAssign, 16> RVLocs;
2462 
2463   // CCState - Info about the registers and stack slots.
2464   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2465                  *DAG.getContext());
2466 
2467   // Analyze outgoing return values.
2468   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2469 
2470   SDValue Flag;
2471   SmallVector<SDValue, 4> RetOps;
2472   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2473   bool isLittleEndian = Subtarget->isLittle();
2474 
2475   MachineFunction &MF = DAG.getMachineFunction();
2476   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2477   AFI->setReturnRegsCount(RVLocs.size());
2478 
2479   // Copy the result values into the output registers.
2480   for (unsigned i = 0, realRVLocIdx = 0;
2481        i != RVLocs.size();
2482        ++i, ++realRVLocIdx) {
2483     CCValAssign &VA = RVLocs[i];
2484     assert(VA.isRegLoc() && "Can only return in registers!");
2485 
2486     SDValue Arg = OutVals[realRVLocIdx];
2487     bool ReturnF16 = false;
2488 
2489     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2490       // Half-precision return values can be returned like this:
2491       //
2492       // t11 f16 = fadd ...
2493       // t12: i16 = bitcast t11
2494       //   t13: i32 = zero_extend t12
2495       // t14: f32 = bitcast t13  <~~~~~~~ Arg
2496       //
2497       // to avoid code generation for bitcasts, we simply set Arg to the node
2498       // that produces the f16 value, t11 in this case.
2499       //
2500       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2501         SDValue ZE = Arg.getOperand(0);
2502         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2503           SDValue BC = ZE.getOperand(0);
2504           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2505             Arg = BC.getOperand(0);
2506             ReturnF16 = true;
2507           }
2508         }
2509       }
2510     }
2511 
2512     switch (VA.getLocInfo()) {
2513     default: llvm_unreachable("Unknown loc info!");
2514     case CCValAssign::Full: break;
2515     case CCValAssign::BCvt:
2516       if (!ReturnF16)
2517         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2518       break;
2519     }
2520 
2521     if (VA.needsCustom()) {
2522       if (VA.getLocVT() == MVT::v2f64) {
2523         // Extract the first half and return it in two registers.
2524         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2525                                    DAG.getConstant(0, dl, MVT::i32));
2526         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2527                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2528 
2529         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2530                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2531                                  Flag);
2532         Flag = Chain.getValue(1);
2533         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2534         VA = RVLocs[++i]; // skip ahead to next loc
2535         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2536                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2537                                  Flag);
2538         Flag = Chain.getValue(1);
2539         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2540         VA = RVLocs[++i]; // skip ahead to next loc
2541 
2542         // Extract the 2nd half and fall through to handle it as an f64 value.
2543         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2544                           DAG.getConstant(1, dl, MVT::i32));
2545       }
2546       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2547       // available.
2548       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2549                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2550       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2551                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2552                                Flag);
2553       Flag = Chain.getValue(1);
2554       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2555       VA = RVLocs[++i]; // skip ahead to next loc
2556       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2557                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2558                                Flag);
2559     } else
2560       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2561 
2562     // Guarantee that all emitted copies are
2563     // stuck together, avoiding something bad.
2564     Flag = Chain.getValue(1);
2565     RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2566                                      ReturnF16 ? MVT::f16 : VA.getLocVT()));
2567   }
2568   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2569   const MCPhysReg *I =
2570       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2571   if (I) {
2572     for (; *I; ++I) {
2573       if (ARM::GPRRegClass.contains(*I))
2574         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2575       else if (ARM::DPRRegClass.contains(*I))
2576         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2577       else
2578         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2579     }
2580   }
2581 
2582   // Update chain and glue.
2583   RetOps[0] = Chain;
2584   if (Flag.getNode())
2585     RetOps.push_back(Flag);
2586 
2587   // CPUs which aren't M-class use a special sequence to return from
2588   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2589   // though we use "subs pc, lr, #N").
2590   //
2591   // M-class CPUs actually use a normal return sequence with a special
2592   // (hardware-provided) value in LR, so the normal code path works.
2593   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2594       !Subtarget->isMClass()) {
2595     if (Subtarget->isThumb1Only())
2596       report_fatal_error("interrupt attribute is not supported in Thumb1");
2597     return LowerInterruptReturn(RetOps, dl, DAG);
2598   }
2599 
2600   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2601 }
2602 
2603 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2604   if (N->getNumValues() != 1)
2605     return false;
2606   if (!N->hasNUsesOfValue(1, 0))
2607     return false;
2608 
2609   SDValue TCChain = Chain;
2610   SDNode *Copy = *N->use_begin();
2611   if (Copy->getOpcode() == ISD::CopyToReg) {
2612     // If the copy has a glue operand, we conservatively assume it isn't safe to
2613     // perform a tail call.
2614     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2615       return false;
2616     TCChain = Copy->getOperand(0);
2617   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2618     SDNode *VMov = Copy;
2619     // f64 returned in a pair of GPRs.
2620     SmallPtrSet<SDNode*, 2> Copies;
2621     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2622          UI != UE; ++UI) {
2623       if (UI->getOpcode() != ISD::CopyToReg)
2624         return false;
2625       Copies.insert(*UI);
2626     }
2627     if (Copies.size() > 2)
2628       return false;
2629 
2630     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2631          UI != UE; ++UI) {
2632       SDValue UseChain = UI->getOperand(0);
2633       if (Copies.count(UseChain.getNode()))
2634         // Second CopyToReg
2635         Copy = *UI;
2636       else {
2637         // We are at the top of this chain.
2638         // If the copy has a glue operand, we conservatively assume it
2639         // isn't safe to perform a tail call.
2640         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2641           return false;
2642         // First CopyToReg
2643         TCChain = UseChain;
2644       }
2645     }
2646   } else if (Copy->getOpcode() == ISD::BITCAST) {
2647     // f32 returned in a single GPR.
2648     if (!Copy->hasOneUse())
2649       return false;
2650     Copy = *Copy->use_begin();
2651     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2652       return false;
2653     // If the copy has a glue operand, we conservatively assume it isn't safe to
2654     // perform a tail call.
2655     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2656       return false;
2657     TCChain = Copy->getOperand(0);
2658   } else {
2659     return false;
2660   }
2661 
2662   bool HasRet = false;
2663   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2664        UI != UE; ++UI) {
2665     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2666         UI->getOpcode() != ARMISD::INTRET_FLAG)
2667       return false;
2668     HasRet = true;
2669   }
2670 
2671   if (!HasRet)
2672     return false;
2673 
2674   Chain = TCChain;
2675   return true;
2676 }
2677 
2678 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2679   if (!Subtarget->supportsTailCall())
2680     return false;
2681 
2682   auto Attr =
2683       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2684   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2685     return false;
2686 
2687   return true;
2688 }
2689 
2690 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2691 // and pass the lower and high parts through.
2692 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2693   SDLoc DL(Op);
2694   SDValue WriteValue = Op->getOperand(2);
2695 
2696   // This function is only supposed to be called for i64 type argument.
2697   assert(WriteValue.getValueType() == MVT::i64
2698           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2699 
2700   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2701                            DAG.getConstant(0, DL, MVT::i32));
2702   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2703                            DAG.getConstant(1, DL, MVT::i32));
2704   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2705   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2706 }
2707 
2708 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2709 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2710 // one of the above mentioned nodes. It has to be wrapped because otherwise
2711 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2712 // be used to form addressing mode. These wrapped nodes will be selected
2713 // into MOVi.
2714 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2715                                              SelectionDAG &DAG) const {
2716   EVT PtrVT = Op.getValueType();
2717   // FIXME there is no actual debug info here
2718   SDLoc dl(Op);
2719   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2720   SDValue Res;
2721 
2722   // When generating execute-only code Constant Pools must be promoted to the
2723   // global data section. It's a bit ugly that we can't share them across basic
2724   // blocks, but this way we guarantee that execute-only behaves correct with
2725   // position-independent addressing modes.
2726   if (Subtarget->genExecuteOnly()) {
2727     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2728     auto T = const_cast<Type*>(CP->getType());
2729     auto C = const_cast<Constant*>(CP->getConstVal());
2730     auto M = const_cast<Module*>(DAG.getMachineFunction().
2731                                  getFunction().getParent());
2732     auto GV = new GlobalVariable(
2733                     *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2734                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2735                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2736                     Twine(AFI->createPICLabelUId())
2737                   );
2738     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2739                                             dl, PtrVT);
2740     return LowerGlobalAddress(GA, DAG);
2741   }
2742 
2743   if (CP->isMachineConstantPoolEntry())
2744     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2745                                     CP->getAlignment());
2746   else
2747     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2748                                     CP->getAlignment());
2749   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2750 }
2751 
2752 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2753   return MachineJumpTableInfo::EK_Inline;
2754 }
2755 
2756 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2757                                              SelectionDAG &DAG) const {
2758   MachineFunction &MF = DAG.getMachineFunction();
2759   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2760   unsigned ARMPCLabelIndex = 0;
2761   SDLoc DL(Op);
2762   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2763   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2764   SDValue CPAddr;
2765   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2766   if (!IsPositionIndependent) {
2767     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2768   } else {
2769     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2770     ARMPCLabelIndex = AFI->createPICLabelUId();
2771     ARMConstantPoolValue *CPV =
2772       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2773                                       ARMCP::CPBlockAddress, PCAdj);
2774     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2775   }
2776   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2777   SDValue Result = DAG.getLoad(
2778       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2779       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2780   if (!IsPositionIndependent)
2781     return Result;
2782   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2783   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2784 }
2785 
2786 /// \brief Convert a TLS address reference into the correct sequence of loads
2787 /// and calls to compute the variable's address for Darwin, and return an
2788 /// SDValue containing the final node.
2789 
2790 /// Darwin only has one TLS scheme which must be capable of dealing with the
2791 /// fully general situation, in the worst case. This means:
2792 ///     + "extern __thread" declaration.
2793 ///     + Defined in a possibly unknown dynamic library.
2794 ///
2795 /// The general system is that each __thread variable has a [3 x i32] descriptor
2796 /// which contains information used by the runtime to calculate the address. The
2797 /// only part of this the compiler needs to know about is the first word, which
2798 /// contains a function pointer that must be called with the address of the
2799 /// entire descriptor in "r0".
2800 ///
2801 /// Since this descriptor may be in a different unit, in general access must
2802 /// proceed along the usual ARM rules. A common sequence to produce is:
2803 ///
2804 ///     movw rT1, :lower16:_var$non_lazy_ptr
2805 ///     movt rT1, :upper16:_var$non_lazy_ptr
2806 ///     ldr r0, [rT1]
2807 ///     ldr rT2, [r0]
2808 ///     blx rT2
2809 ///     [...address now in r0...]
2810 SDValue
2811 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2812                                                SelectionDAG &DAG) const {
2813   assert(Subtarget->isTargetDarwin() &&
2814          "This function expects a Darwin target");
2815   SDLoc DL(Op);
2816 
2817   // First step is to get the address of the actua global symbol. This is where
2818   // the TLS descriptor lives.
2819   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2820 
2821   // The first entry in the descriptor is a function pointer that we must call
2822   // to obtain the address of the variable.
2823   SDValue Chain = DAG.getEntryNode();
2824   SDValue FuncTLVGet = DAG.getLoad(
2825       MVT::i32, DL, Chain, DescAddr,
2826       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2827       /* Alignment = */ 4,
2828       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2829           MachineMemOperand::MOInvariant);
2830   Chain = FuncTLVGet.getValue(1);
2831 
2832   MachineFunction &F = DAG.getMachineFunction();
2833   MachineFrameInfo &MFI = F.getFrameInfo();
2834   MFI.setAdjustsStack(true);
2835 
2836   // TLS calls preserve all registers except those that absolutely must be
2837   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2838   // silly).
2839   auto TRI =
2840       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
2841   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2842   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2843 
2844   // Finally, we can make the call. This is just a degenerate version of a
2845   // normal AArch64 call node: r0 takes the address of the descriptor, and
2846   // returns the address of the variable in this thread.
2847   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2848   Chain =
2849       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2850                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2851                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2852   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2853 }
2854 
2855 SDValue
2856 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2857                                                 SelectionDAG &DAG) const {
2858   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2859 
2860   SDValue Chain = DAG.getEntryNode();
2861   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2862   SDLoc DL(Op);
2863 
2864   // Load the current TEB (thread environment block)
2865   SDValue Ops[] = {Chain,
2866                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2867                    DAG.getConstant(15, DL, MVT::i32),
2868                    DAG.getConstant(0, DL, MVT::i32),
2869                    DAG.getConstant(13, DL, MVT::i32),
2870                    DAG.getConstant(0, DL, MVT::i32),
2871                    DAG.getConstant(2, DL, MVT::i32)};
2872   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2873                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2874 
2875   SDValue TEB = CurrentTEB.getValue(0);
2876   Chain = CurrentTEB.getValue(1);
2877 
2878   // Load the ThreadLocalStoragePointer from the TEB
2879   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2880   SDValue TLSArray =
2881       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2882   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2883 
2884   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2885   // offset into the TLSArray.
2886 
2887   // Load the TLS index from the C runtime
2888   SDValue TLSIndex =
2889       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2890   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2891   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2892 
2893   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2894                               DAG.getConstant(2, DL, MVT::i32));
2895   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2896                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2897                             MachinePointerInfo());
2898 
2899   // Get the offset of the start of the .tls section (section base)
2900   const auto *GA = cast<GlobalAddressSDNode>(Op);
2901   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2902   SDValue Offset = DAG.getLoad(
2903       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2904                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2905       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2906 
2907   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2908 }
2909 
2910 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2911 SDValue
2912 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2913                                                  SelectionDAG &DAG) const {
2914   SDLoc dl(GA);
2915   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2916   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2917   MachineFunction &MF = DAG.getMachineFunction();
2918   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2919   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2920   ARMConstantPoolValue *CPV =
2921     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2922                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2923   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2924   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2925   Argument = DAG.getLoad(
2926       PtrVT, dl, DAG.getEntryNode(), Argument,
2927       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2928   SDValue Chain = Argument.getValue(1);
2929 
2930   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2931   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2932 
2933   // call __tls_get_addr.
2934   ArgListTy Args;
2935   ArgListEntry Entry;
2936   Entry.Node = Argument;
2937   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2938   Args.push_back(Entry);
2939 
2940   // FIXME: is there useful debug info available here?
2941   TargetLowering::CallLoweringInfo CLI(DAG);
2942   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2943       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2944       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2945 
2946   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2947   return CallResult.first;
2948 }
2949 
2950 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2951 // "local exec" model.
2952 SDValue
2953 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2954                                         SelectionDAG &DAG,
2955                                         TLSModel::Model model) const {
2956   const GlobalValue *GV = GA->getGlobal();
2957   SDLoc dl(GA);
2958   SDValue Offset;
2959   SDValue Chain = DAG.getEntryNode();
2960   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2961   // Get the Thread Pointer
2962   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2963 
2964   if (model == TLSModel::InitialExec) {
2965     MachineFunction &MF = DAG.getMachineFunction();
2966     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2967     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2968     // Initial exec model.
2969     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2970     ARMConstantPoolValue *CPV =
2971       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2972                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2973                                       true);
2974     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2975     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2976     Offset = DAG.getLoad(
2977         PtrVT, dl, Chain, Offset,
2978         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2979     Chain = Offset.getValue(1);
2980 
2981     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2982     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2983 
2984     Offset = DAG.getLoad(
2985         PtrVT, dl, Chain, Offset,
2986         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2987   } else {
2988     // local exec model
2989     assert(model == TLSModel::LocalExec);
2990     ARMConstantPoolValue *CPV =
2991       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2992     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2993     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2994     Offset = DAG.getLoad(
2995         PtrVT, dl, Chain, Offset,
2996         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2997   }
2998 
2999   // The address of the thread local variable is the add of the thread
3000   // pointer with the offset of the variable.
3001   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3002 }
3003 
3004 SDValue
3005 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3006   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3007   if (DAG.getTarget().Options.EmulatedTLS)
3008     return LowerToTLSEmulatedModel(GA, DAG);
3009 
3010   if (Subtarget->isTargetDarwin())
3011     return LowerGlobalTLSAddressDarwin(Op, DAG);
3012 
3013   if (Subtarget->isTargetWindows())
3014     return LowerGlobalTLSAddressWindows(Op, DAG);
3015 
3016   // TODO: implement the "local dynamic" model
3017   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3018   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3019 
3020   switch (model) {
3021     case TLSModel::GeneralDynamic:
3022     case TLSModel::LocalDynamic:
3023       return LowerToTLSGeneralDynamicModel(GA, DAG);
3024     case TLSModel::InitialExec:
3025     case TLSModel::LocalExec:
3026       return LowerToTLSExecModels(GA, DAG, model);
3027   }
3028   llvm_unreachable("bogus TLS model");
3029 }
3030 
3031 /// Return true if all users of V are within function F, looking through
3032 /// ConstantExprs.
3033 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3034   SmallVector<const User*,4> Worklist;
3035   for (auto *U : V->users())
3036     Worklist.push_back(U);
3037   while (!Worklist.empty()) {
3038     auto *U = Worklist.pop_back_val();
3039     if (isa<ConstantExpr>(U)) {
3040       for (auto *UU : U->users())
3041         Worklist.push_back(UU);
3042       continue;
3043     }
3044 
3045     auto *I = dyn_cast<Instruction>(U);
3046     if (!I || I->getParent()->getParent() != F)
3047       return false;
3048   }
3049   return true;
3050 }
3051 
3052 /// Return true if all users of V are within some (any) function, looking through
3053 /// ConstantExprs. In other words, are there any global constant users?
3054 static bool allUsersAreInFunctions(const Value *V) {
3055   SmallVector<const User*,4> Worklist;
3056   for (auto *U : V->users())
3057     Worklist.push_back(U);
3058   while (!Worklist.empty()) {
3059     auto *U = Worklist.pop_back_val();
3060     if (isa<ConstantExpr>(U)) {
3061       for (auto *UU : U->users())
3062         Worklist.push_back(UU);
3063       continue;
3064     }
3065 
3066     if (!isa<Instruction>(U))
3067       return false;
3068   }
3069   return true;
3070 }
3071 
3072 // Return true if T is an integer, float or an array/vector of either.
3073 static bool isSimpleType(Type *T) {
3074   if (T->isIntegerTy() || T->isFloatingPointTy())
3075     return true;
3076   Type *SubT = nullptr;
3077   if (T->isArrayTy())
3078     SubT = T->getArrayElementType();
3079   else if (T->isVectorTy())
3080     SubT = T->getVectorElementType();
3081   else
3082     return false;
3083   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3084 }
3085 
3086 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3087                                      EVT PtrVT, const SDLoc &dl) {
3088   // If we're creating a pool entry for a constant global with unnamed address,
3089   // and the global is small enough, we can emit it inline into the constant pool
3090   // to save ourselves an indirection.
3091   //
3092   // This is a win if the constant is only used in one function (so it doesn't
3093   // need to be duplicated) or duplicating the constant wouldn't increase code
3094   // size (implying the constant is no larger than 4 bytes).
3095   const Function &F = DAG.getMachineFunction().getFunction();
3096 
3097   // We rely on this decision to inline being idemopotent and unrelated to the
3098   // use-site. We know that if we inline a variable at one use site, we'll
3099   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3100   // doesn't know about this optimization, so bail out if it's enabled else
3101   // we could decide to inline here (and thus never emit the GV) but require
3102   // the GV from fast-isel generated code.
3103   if (!EnableConstpoolPromotion ||
3104       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3105       return SDValue();
3106 
3107   auto *GVar = dyn_cast<GlobalVariable>(GV);
3108   if (!GVar || !GVar->hasInitializer() ||
3109       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3110       !GVar->hasLocalLinkage())
3111     return SDValue();
3112 
3113   // Ensure that we don't try and inline any type that contains pointers. If
3114   // we inline a value that contains relocations, we move the relocations from
3115   // .data to .text which is not ideal.
3116   auto *Init = GVar->getInitializer();
3117   if (!isSimpleType(Init->getType()))
3118     return SDValue();
3119 
3120   // The constant islands pass can only really deal with alignment requests
3121   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3122   // any type wanting greater alignment requirements than 4 bytes. We also
3123   // can only promote constants that are multiples of 4 bytes in size or
3124   // are paddable to a multiple of 4. Currently we only try and pad constants
3125   // that are strings for simplicity.
3126   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3127   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3128   unsigned Align = GVar->getAlignment();
3129   unsigned RequiredPadding = 4 - (Size % 4);
3130   bool PaddingPossible =
3131     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3132   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3133       Size == 0)
3134     return SDValue();
3135 
3136   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3137   MachineFunction &MF = DAG.getMachineFunction();
3138   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3139 
3140   // We can't bloat the constant pool too much, else the ConstantIslands pass
3141   // may fail to converge. If we haven't promoted this global yet (it may have
3142   // multiple uses), and promoting it would increase the constant pool size (Sz
3143   // > 4), ensure we have space to do so up to MaxTotal.
3144   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3145     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3146         ConstpoolPromotionMaxTotal)
3147       return SDValue();
3148 
3149   // This is only valid if all users are in a single function OR it has users
3150   // in multiple functions but it no larger than a pointer. We also check if
3151   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3152   // address taken.
3153   if (!allUsersAreInFunction(GVar, &F) &&
3154       !(Size <= 4 && allUsersAreInFunctions(GVar)))
3155     return SDValue();
3156 
3157   // We're going to inline this global. Pad it out if needed.
3158   if (RequiredPadding != 4) {
3159     StringRef S = CDAInit->getAsString();
3160 
3161     SmallVector<uint8_t,16> V(S.size());
3162     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3163     while (RequiredPadding--)
3164       V.push_back(0);
3165     Init = ConstantDataArray::get(*DAG.getContext(), V);
3166   }
3167 
3168   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3169   SDValue CPAddr =
3170     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3171   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3172     AFI->markGlobalAsPromotedToConstantPool(GVar);
3173     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3174                                       PaddedSize - 4);
3175   }
3176   ++NumConstpoolPromoted;
3177   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3178 }
3179 
3180 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3181   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3182     GV = GA->getBaseObject();
3183   return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3184          isa<Function>(GV);
3185 }
3186 
3187 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3188                                               SelectionDAG &DAG) const {
3189   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3190   default: llvm_unreachable("unknown object format");
3191   case Triple::COFF:
3192     return LowerGlobalAddressWindows(Op, DAG);
3193   case Triple::ELF:
3194     return LowerGlobalAddressELF(Op, DAG);
3195   case Triple::MachO:
3196     return LowerGlobalAddressDarwin(Op, DAG);
3197   }
3198 }
3199 
3200 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3201                                                  SelectionDAG &DAG) const {
3202   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3203   SDLoc dl(Op);
3204   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3205   const TargetMachine &TM = getTargetMachine();
3206   bool IsRO = isReadOnly(GV);
3207 
3208   // promoteToConstantPool only if not generating XO text section
3209   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3210     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3211       return V;
3212 
3213   if (isPositionIndependent()) {
3214     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3215     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3216                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3217     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3218     if (UseGOT_PREL)
3219       Result =
3220           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3221                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3222     return Result;
3223   } else if (Subtarget->isROPI() && IsRO) {
3224     // PC-relative.
3225     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3226     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3227     return Result;
3228   } else if (Subtarget->isRWPI() && !IsRO) {
3229     // SB-relative.
3230     SDValue RelAddr;
3231     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3232       ++NumMovwMovt;
3233       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3234       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3235     } else { // use literal pool for address constant
3236       ARMConstantPoolValue *CPV =
3237         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3238       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3239       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3240       RelAddr = DAG.getLoad(
3241           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3242           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3243     }
3244     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3245     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3246     return Result;
3247   }
3248 
3249   // If we have T2 ops, we can materialize the address directly via movt/movw
3250   // pair. This is always cheaper.
3251   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3252     ++NumMovwMovt;
3253     // FIXME: Once remat is capable of dealing with instructions with register
3254     // operands, expand this into two nodes.
3255     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3256                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3257   } else {
3258     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3259     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3260     return DAG.getLoad(
3261         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3262         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3263   }
3264 }
3265 
3266 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3267                                                     SelectionDAG &DAG) const {
3268   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3269          "ROPI/RWPI not currently supported for Darwin");
3270   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3271   SDLoc dl(Op);
3272   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3273 
3274   if (Subtarget->useMovt(DAG.getMachineFunction()))
3275     ++NumMovwMovt;
3276 
3277   // FIXME: Once remat is capable of dealing with instructions with register
3278   // operands, expand this into multiple nodes
3279   unsigned Wrapper =
3280       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3281 
3282   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3283   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3284 
3285   if (Subtarget->isGVIndirectSymbol(GV))
3286     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3287                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3288   return Result;
3289 }
3290 
3291 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3292                                                      SelectionDAG &DAG) const {
3293   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3294   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3295          "Windows on ARM expects to use movw/movt");
3296   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3297          "ROPI/RWPI not currently supported for Windows");
3298 
3299   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3300   const ARMII::TOF TargetFlags =
3301     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3302   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3303   SDValue Result;
3304   SDLoc DL(Op);
3305 
3306   ++NumMovwMovt;
3307 
3308   // FIXME: Once remat is capable of dealing with instructions with register
3309   // operands, expand this into two nodes.
3310   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3311                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3312                                                   TargetFlags));
3313   if (GV->hasDLLImportStorageClass())
3314     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3315                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3316   return Result;
3317 }
3318 
3319 SDValue
3320 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3321   SDLoc dl(Op);
3322   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3323   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3324                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3325                      Op.getOperand(1), Val);
3326 }
3327 
3328 SDValue
3329 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3330   SDLoc dl(Op);
3331   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3332                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3333 }
3334 
3335 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3336                                                       SelectionDAG &DAG) const {
3337   SDLoc dl(Op);
3338   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3339                      Op.getOperand(0));
3340 }
3341 
3342 SDValue
3343 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3344                                           const ARMSubtarget *Subtarget) const {
3345   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3346   SDLoc dl(Op);
3347   switch (IntNo) {
3348   default: return SDValue();    // Don't custom lower most intrinsics.
3349   case Intrinsic::thread_pointer: {
3350     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3351     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3352   }
3353   case Intrinsic::eh_sjlj_lsda: {
3354     MachineFunction &MF = DAG.getMachineFunction();
3355     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3356     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3357     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3358     SDValue CPAddr;
3359     bool IsPositionIndependent = isPositionIndependent();
3360     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3361     ARMConstantPoolValue *CPV =
3362       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3363                                       ARMCP::CPLSDA, PCAdj);
3364     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3365     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3366     SDValue Result = DAG.getLoad(
3367         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3368         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3369 
3370     if (IsPositionIndependent) {
3371       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3372       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3373     }
3374     return Result;
3375   }
3376   case Intrinsic::arm_neon_vabs:
3377     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3378                         Op.getOperand(1));
3379   case Intrinsic::arm_neon_vmulls:
3380   case Intrinsic::arm_neon_vmullu: {
3381     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3382       ? ARMISD::VMULLs : ARMISD::VMULLu;
3383     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3384                        Op.getOperand(1), Op.getOperand(2));
3385   }
3386   case Intrinsic::arm_neon_vminnm:
3387   case Intrinsic::arm_neon_vmaxnm: {
3388     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3389       ? ISD::FMINNUM : ISD::FMAXNUM;
3390     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3391                        Op.getOperand(1), Op.getOperand(2));
3392   }
3393   case Intrinsic::arm_neon_vminu:
3394   case Intrinsic::arm_neon_vmaxu: {
3395     if (Op.getValueType().isFloatingPoint())
3396       return SDValue();
3397     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3398       ? ISD::UMIN : ISD::UMAX;
3399     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3400                          Op.getOperand(1), Op.getOperand(2));
3401   }
3402   case Intrinsic::arm_neon_vmins:
3403   case Intrinsic::arm_neon_vmaxs: {
3404     // v{min,max}s is overloaded between signed integers and floats.
3405     if (!Op.getValueType().isFloatingPoint()) {
3406       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3407         ? ISD::SMIN : ISD::SMAX;
3408       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3409                          Op.getOperand(1), Op.getOperand(2));
3410     }
3411     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3412       ? ISD::FMINNAN : ISD::FMAXNAN;
3413     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3414                        Op.getOperand(1), Op.getOperand(2));
3415   }
3416   case Intrinsic::arm_neon_vtbl1:
3417     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3418                        Op.getOperand(1), Op.getOperand(2));
3419   case Intrinsic::arm_neon_vtbl2:
3420     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3421                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3422   }
3423 }
3424 
3425 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3426                                  const ARMSubtarget *Subtarget) {
3427   SDLoc dl(Op);
3428   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3429   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3430   if (SSID == SyncScope::SingleThread)
3431     return Op;
3432 
3433   if (!Subtarget->hasDataBarrier()) {
3434     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3435     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3436     // here.
3437     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3438            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3439     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3440                        DAG.getConstant(0, dl, MVT::i32));
3441   }
3442 
3443   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3444   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3445   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3446   if (Subtarget->isMClass()) {
3447     // Only a full system barrier exists in the M-class architectures.
3448     Domain = ARM_MB::SY;
3449   } else if (Subtarget->preferISHSTBarriers() &&
3450              Ord == AtomicOrdering::Release) {
3451     // Swift happens to implement ISHST barriers in a way that's compatible with
3452     // Release semantics but weaker than ISH so we'd be fools not to use
3453     // it. Beware: other processors probably don't!
3454     Domain = ARM_MB::ISHST;
3455   }
3456 
3457   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3458                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3459                      DAG.getConstant(Domain, dl, MVT::i32));
3460 }
3461 
3462 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3463                              const ARMSubtarget *Subtarget) {
3464   // ARM pre v5TE and Thumb1 does not have preload instructions.
3465   if (!(Subtarget->isThumb2() ||
3466         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3467     // Just preserve the chain.
3468     return Op.getOperand(0);
3469 
3470   SDLoc dl(Op);
3471   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3472   if (!isRead &&
3473       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3474     // ARMv7 with MP extension has PLDW.
3475     return Op.getOperand(0);
3476 
3477   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3478   if (Subtarget->isThumb()) {
3479     // Invert the bits.
3480     isRead = ~isRead & 1;
3481     isData = ~isData & 1;
3482   }
3483 
3484   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3485                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3486                      DAG.getConstant(isData, dl, MVT::i32));
3487 }
3488 
3489 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3490   MachineFunction &MF = DAG.getMachineFunction();
3491   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3492 
3493   // vastart just stores the address of the VarArgsFrameIndex slot into the
3494   // memory location argument.
3495   SDLoc dl(Op);
3496   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3497   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3498   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3499   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3500                       MachinePointerInfo(SV));
3501 }
3502 
3503 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3504                                                 CCValAssign &NextVA,
3505                                                 SDValue &Root,
3506                                                 SelectionDAG &DAG,
3507                                                 const SDLoc &dl) const {
3508   MachineFunction &MF = DAG.getMachineFunction();
3509   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3510 
3511   const TargetRegisterClass *RC;
3512   if (AFI->isThumb1OnlyFunction())
3513     RC = &ARM::tGPRRegClass;
3514   else
3515     RC = &ARM::GPRRegClass;
3516 
3517   // Transform the arguments stored in physical registers into virtual ones.
3518   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3519   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3520 
3521   SDValue ArgValue2;
3522   if (NextVA.isMemLoc()) {
3523     MachineFrameInfo &MFI = MF.getFrameInfo();
3524     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3525 
3526     // Create load node to retrieve arguments from the stack.
3527     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3528     ArgValue2 = DAG.getLoad(
3529         MVT::i32, dl, Root, FIN,
3530         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3531   } else {
3532     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3533     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3534   }
3535   if (!Subtarget->isLittle())
3536     std::swap (ArgValue, ArgValue2);
3537   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3538 }
3539 
3540 // The remaining GPRs hold either the beginning of variable-argument
3541 // data, or the beginning of an aggregate passed by value (usually
3542 // byval).  Either way, we allocate stack slots adjacent to the data
3543 // provided by our caller, and store the unallocated registers there.
3544 // If this is a variadic function, the va_list pointer will begin with
3545 // these values; otherwise, this reassembles a (byval) structure that
3546 // was split between registers and memory.
3547 // Return: The frame index registers were stored into.
3548 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3549                                       const SDLoc &dl, SDValue &Chain,
3550                                       const Value *OrigArg,
3551                                       unsigned InRegsParamRecordIdx,
3552                                       int ArgOffset, unsigned ArgSize) const {
3553   // Currently, two use-cases possible:
3554   // Case #1. Non-var-args function, and we meet first byval parameter.
3555   //          Setup first unallocated register as first byval register;
3556   //          eat all remained registers
3557   //          (these two actions are performed by HandleByVal method).
3558   //          Then, here, we initialize stack frame with
3559   //          "store-reg" instructions.
3560   // Case #2. Var-args function, that doesn't contain byval parameters.
3561   //          The same: eat all remained unallocated registers,
3562   //          initialize stack frame.
3563 
3564   MachineFunction &MF = DAG.getMachineFunction();
3565   MachineFrameInfo &MFI = MF.getFrameInfo();
3566   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3567   unsigned RBegin, REnd;
3568   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3569     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3570   } else {
3571     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3572     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3573     REnd = ARM::R4;
3574   }
3575 
3576   if (REnd != RBegin)
3577     ArgOffset = -4 * (ARM::R4 - RBegin);
3578 
3579   auto PtrVT = getPointerTy(DAG.getDataLayout());
3580   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3581   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3582 
3583   SmallVector<SDValue, 4> MemOps;
3584   const TargetRegisterClass *RC =
3585       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3586 
3587   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3588     unsigned VReg = MF.addLiveIn(Reg, RC);
3589     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3590     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3591                                  MachinePointerInfo(OrigArg, 4 * i));
3592     MemOps.push_back(Store);
3593     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3594   }
3595 
3596   if (!MemOps.empty())
3597     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3598   return FrameIndex;
3599 }
3600 
3601 // Setup stack frame, the va_list pointer will start from.
3602 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3603                                              const SDLoc &dl, SDValue &Chain,
3604                                              unsigned ArgOffset,
3605                                              unsigned TotalArgRegsSaveSize,
3606                                              bool ForceMutable) const {
3607   MachineFunction &MF = DAG.getMachineFunction();
3608   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3609 
3610   // Try to store any remaining integer argument regs
3611   // to their spots on the stack so that they may be loaded by dereferencing
3612   // the result of va_next.
3613   // If there is no regs to be stored, just point address after last
3614   // argument passed via stack.
3615   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3616                                   CCInfo.getInRegsParamsCount(),
3617                                   CCInfo.getNextStackOffset(), 4);
3618   AFI->setVarArgsFrameIndex(FrameIndex);
3619 }
3620 
3621 SDValue ARMTargetLowering::LowerFormalArguments(
3622     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3623     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3624     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3625   MachineFunction &MF = DAG.getMachineFunction();
3626   MachineFrameInfo &MFI = MF.getFrameInfo();
3627 
3628   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3629 
3630   // Assign locations to all of the incoming arguments.
3631   SmallVector<CCValAssign, 16> ArgLocs;
3632   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3633                  *DAG.getContext());
3634   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3635 
3636   SmallVector<SDValue, 16> ArgValues;
3637   SDValue ArgValue;
3638   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3639   unsigned CurArgIdx = 0;
3640 
3641   // Initially ArgRegsSaveSize is zero.
3642   // Then we increase this value each time we meet byval parameter.
3643   // We also increase this value in case of varargs function.
3644   AFI->setArgRegsSaveSize(0);
3645 
3646   // Calculate the amount of stack space that we need to allocate to store
3647   // byval and variadic arguments that are passed in registers.
3648   // We need to know this before we allocate the first byval or variadic
3649   // argument, as they will be allocated a stack slot below the CFA (Canonical
3650   // Frame Address, the stack pointer at entry to the function).
3651   unsigned ArgRegBegin = ARM::R4;
3652   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3653     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3654       break;
3655 
3656     CCValAssign &VA = ArgLocs[i];
3657     unsigned Index = VA.getValNo();
3658     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3659     if (!Flags.isByVal())
3660       continue;
3661 
3662     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3663     unsigned RBegin, REnd;
3664     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3665     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3666 
3667     CCInfo.nextInRegsParam();
3668   }
3669   CCInfo.rewindByValRegsInfo();
3670 
3671   int lastInsIndex = -1;
3672   if (isVarArg && MFI.hasVAStart()) {
3673     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3674     if (RegIdx != array_lengthof(GPRArgRegs))
3675       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3676   }
3677 
3678   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3679   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3680   auto PtrVT = getPointerTy(DAG.getDataLayout());
3681 
3682   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3683     CCValAssign &VA = ArgLocs[i];
3684     if (Ins[VA.getValNo()].isOrigArg()) {
3685       std::advance(CurOrigArg,
3686                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3687       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3688     }
3689     // Arguments stored in registers.
3690     if (VA.isRegLoc()) {
3691       EVT RegVT = VA.getLocVT();
3692 
3693       if (VA.needsCustom()) {
3694         // f64 and vector types are split up into multiple registers or
3695         // combinations of registers and stack slots.
3696         if (VA.getLocVT() == MVT::v2f64) {
3697           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3698                                                    Chain, DAG, dl);
3699           VA = ArgLocs[++i]; // skip ahead to next loc
3700           SDValue ArgValue2;
3701           if (VA.isMemLoc()) {
3702             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3703             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3704             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3705                                     MachinePointerInfo::getFixedStack(
3706                                         DAG.getMachineFunction(), FI));
3707           } else {
3708             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3709                                              Chain, DAG, dl);
3710           }
3711           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3712           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3713                                  ArgValue, ArgValue1,
3714                                  DAG.getIntPtrConstant(0, dl));
3715           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3716                                  ArgValue, ArgValue2,
3717                                  DAG.getIntPtrConstant(1, dl));
3718         } else
3719           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3720       } else {
3721         const TargetRegisterClass *RC;
3722 
3723 
3724         if (RegVT == MVT::f16)
3725           RC = &ARM::HPRRegClass;
3726         else if (RegVT == MVT::f32)
3727           RC = &ARM::SPRRegClass;
3728         else if (RegVT == MVT::f64)
3729           RC = &ARM::DPRRegClass;
3730         else if (RegVT == MVT::v2f64)
3731           RC = &ARM::QPRRegClass;
3732         else if (RegVT == MVT::i32)
3733           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3734                                            : &ARM::GPRRegClass;
3735         else
3736           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3737 
3738         // Transform the arguments in physical registers into virtual ones.
3739         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3740         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3741       }
3742 
3743       // If this is an 8 or 16-bit value, it is really passed promoted
3744       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3745       // truncate to the right size.
3746       switch (VA.getLocInfo()) {
3747       default: llvm_unreachable("Unknown loc info!");
3748       case CCValAssign::Full: break;
3749       case CCValAssign::BCvt:
3750         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3751         break;
3752       case CCValAssign::SExt:
3753         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3754                                DAG.getValueType(VA.getValVT()));
3755         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3756         break;
3757       case CCValAssign::ZExt:
3758         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3759                                DAG.getValueType(VA.getValVT()));
3760         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3761         break;
3762       }
3763 
3764       InVals.push_back(ArgValue);
3765     } else { // VA.isRegLoc()
3766       // sanity check
3767       assert(VA.isMemLoc());
3768       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3769 
3770       int index = VA.getValNo();
3771 
3772       // Some Ins[] entries become multiple ArgLoc[] entries.
3773       // Process them only once.
3774       if (index != lastInsIndex)
3775         {
3776           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3777           // FIXME: For now, all byval parameter objects are marked mutable.
3778           // This can be changed with more analysis.
3779           // In case of tail call optimization mark all arguments mutable.
3780           // Since they could be overwritten by lowering of arguments in case of
3781           // a tail call.
3782           if (Flags.isByVal()) {
3783             assert(Ins[index].isOrigArg() &&
3784                    "Byval arguments cannot be implicit");
3785             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3786 
3787             int FrameIndex = StoreByValRegs(
3788                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3789                 VA.getLocMemOffset(), Flags.getByValSize());
3790             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3791             CCInfo.nextInRegsParam();
3792           } else {
3793             unsigned FIOffset = VA.getLocMemOffset();
3794             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3795                                            FIOffset, true);
3796 
3797             // Create load nodes to retrieve arguments from the stack.
3798             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3799             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3800                                          MachinePointerInfo::getFixedStack(
3801                                              DAG.getMachineFunction(), FI)));
3802           }
3803           lastInsIndex = index;
3804         }
3805     }
3806   }
3807 
3808   // varargs
3809   if (isVarArg && MFI.hasVAStart())
3810     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3811                          CCInfo.getNextStackOffset(),
3812                          TotalArgRegsSaveSize);
3813 
3814   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3815 
3816   return Chain;
3817 }
3818 
3819 /// isFloatingPointZero - Return true if this is +0.0.
3820 static bool isFloatingPointZero(SDValue Op) {
3821   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3822     return CFP->getValueAPF().isPosZero();
3823   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3824     // Maybe this has already been legalized into the constant pool?
3825     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3826       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3827       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3828         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3829           return CFP->getValueAPF().isPosZero();
3830     }
3831   } else if (Op->getOpcode() == ISD::BITCAST &&
3832              Op->getValueType(0) == MVT::f64) {
3833     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3834     // created by LowerConstantFP().
3835     SDValue BitcastOp = Op->getOperand(0);
3836     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3837         isNullConstant(BitcastOp->getOperand(0)))
3838       return true;
3839   }
3840   return false;
3841 }
3842 
3843 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3844 /// the given operands.
3845 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3846                                      SDValue &ARMcc, SelectionDAG &DAG,
3847                                      const SDLoc &dl) const {
3848   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3849     unsigned C = RHSC->getZExtValue();
3850     if (!isLegalICmpImmediate(C)) {
3851       // Constant does not fit, try adjusting it by one?
3852       switch (CC) {
3853       default: break;
3854       case ISD::SETLT:
3855       case ISD::SETGE:
3856         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3857           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3858           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3859         }
3860         break;
3861       case ISD::SETULT:
3862       case ISD::SETUGE:
3863         if (C != 0 && isLegalICmpImmediate(C-1)) {
3864           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3865           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3866         }
3867         break;
3868       case ISD::SETLE:
3869       case ISD::SETGT:
3870         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3871           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3872           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3873         }
3874         break;
3875       case ISD::SETULE:
3876       case ISD::SETUGT:
3877         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3878           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3879           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3880         }
3881         break;
3882       }
3883     }
3884   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
3885              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
3886     // In ARM and Thumb-2, the compare instructions can shift their second
3887     // operand.
3888     CC = ISD::getSetCCSwappedOperands(CC);
3889     std::swap(LHS, RHS);
3890   }
3891 
3892   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3893   ARMISD::NodeType CompareType;
3894   switch (CondCode) {
3895   default:
3896     CompareType = ARMISD::CMP;
3897     break;
3898   case ARMCC::EQ:
3899   case ARMCC::NE:
3900     // Uses only Z Flag
3901     CompareType = ARMISD::CMPZ;
3902     break;
3903   }
3904   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3905   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3906 }
3907 
3908 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3909 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3910                                      SelectionDAG &DAG, const SDLoc &dl,
3911                                      bool InvalidOnQNaN) const {
3912   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3913   SDValue Cmp;
3914   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3915   if (!isFloatingPointZero(RHS))
3916     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3917   else
3918     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3919   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3920 }
3921 
3922 /// duplicateCmp - Glue values can have only one use, so this function
3923 /// duplicates a comparison node.
3924 SDValue
3925 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3926   unsigned Opc = Cmp.getOpcode();
3927   SDLoc DL(Cmp);
3928   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3929     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3930 
3931   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3932   Cmp = Cmp.getOperand(0);
3933   Opc = Cmp.getOpcode();
3934   if (Opc == ARMISD::CMPFP)
3935     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3936                       Cmp.getOperand(1), Cmp.getOperand(2));
3937   else {
3938     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3939     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3940                       Cmp.getOperand(1));
3941   }
3942   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3943 }
3944 
3945 // This function returns three things: the arithmetic computation itself
3946 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
3947 // comparison and the condition code define the case in which the arithmetic
3948 // computation *does not* overflow.
3949 std::pair<SDValue, SDValue>
3950 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3951                                  SDValue &ARMcc) const {
3952   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3953 
3954   SDValue Value, OverflowCmp;
3955   SDValue LHS = Op.getOperand(0);
3956   SDValue RHS = Op.getOperand(1);
3957   SDLoc dl(Op);
3958 
3959   // FIXME: We are currently always generating CMPs because we don't support
3960   // generating CMN through the backend. This is not as good as the natural
3961   // CMP case because it causes a register dependency and cannot be folded
3962   // later.
3963 
3964   switch (Op.getOpcode()) {
3965   default:
3966     llvm_unreachable("Unknown overflow instruction!");
3967   case ISD::SADDO:
3968     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3969     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3970     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3971     break;
3972   case ISD::UADDO:
3973     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3974     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
3975     // We do not use it in the USUBO case as Value may not be used.
3976     Value = DAG.getNode(ARMISD::ADDC, dl,
3977                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
3978                 .getValue(0);
3979     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3980     break;
3981   case ISD::SSUBO:
3982     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3983     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3984     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3985     break;
3986   case ISD::USUBO:
3987     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3988     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3989     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3990     break;
3991   case ISD::UMULO:
3992     // We generate a UMUL_LOHI and then check if the high word is 0.
3993     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
3994     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
3995                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
3996                         LHS, RHS);
3997     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
3998                               DAG.getConstant(0, dl, MVT::i32));
3999     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4000     break;
4001   case ISD::SMULO:
4002     // We generate a SMUL_LOHI and then check if all the bits of the high word
4003     // are the same as the sign bit of the low word.
4004     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4005     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4006                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4007                         LHS, RHS);
4008     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4009                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4010                                           Value.getValue(0),
4011                                           DAG.getConstant(31, dl, MVT::i32)));
4012     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4013     break;
4014   } // switch (...)
4015 
4016   return std::make_pair(Value, OverflowCmp);
4017 }
4018 
4019 SDValue
4020 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4021   // Let legalize expand this if it isn't a legal type yet.
4022   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4023     return SDValue();
4024 
4025   SDValue Value, OverflowCmp;
4026   SDValue ARMcc;
4027   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4028   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4029   SDLoc dl(Op);
4030   // We use 0 and 1 as false and true values.
4031   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4032   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4033   EVT VT = Op.getValueType();
4034 
4035   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4036                                  ARMcc, CCR, OverflowCmp);
4037 
4038   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4039   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4040 }
4041 
4042 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4043                                               SelectionDAG &DAG) {
4044   SDLoc DL(BoolCarry);
4045   EVT CarryVT = BoolCarry.getValueType();
4046 
4047   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
4048   // This converts the boolean value carry into the carry flag by doing
4049   // ARMISD::ADDC Carry, ~0
4050   return DAG.getNode(ARMISD::ADDC, DL, DAG.getVTList(CarryVT, MVT::i32),
4051                      BoolCarry, DAG.getConstant(NegOne, DL, CarryVT));
4052 }
4053 
4054 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4055                                               SelectionDAG &DAG) {
4056   SDLoc DL(Flags);
4057 
4058   // Now convert the carry flag into a boolean carry. We do this
4059   // using ARMISD:ADDE 0, 0, Carry
4060   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4061                      DAG.getConstant(0, DL, MVT::i32),
4062                      DAG.getConstant(0, DL, MVT::i32), Flags);
4063 }
4064 
4065 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4066                                              SelectionDAG &DAG) const {
4067   // Let legalize expand this if it isn't a legal type yet.
4068   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4069     return SDValue();
4070 
4071   SDValue LHS = Op.getOperand(0);
4072   SDValue RHS = Op.getOperand(1);
4073   SDLoc dl(Op);
4074 
4075   EVT VT = Op.getValueType();
4076   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4077   SDValue Value;
4078   SDValue Overflow;
4079   switch (Op.getOpcode()) {
4080   default:
4081     llvm_unreachable("Unknown overflow instruction!");
4082   case ISD::UADDO:
4083     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4084     // Convert the carry flag into a boolean value.
4085     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4086     break;
4087   case ISD::USUBO: {
4088     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4089     // Convert the carry flag into a boolean value.
4090     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4091     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4092     // value. So compute 1 - C.
4093     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4094                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4095     break;
4096   }
4097   }
4098 
4099   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4100 }
4101 
4102 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4103   SDValue Cond = Op.getOperand(0);
4104   SDValue SelectTrue = Op.getOperand(1);
4105   SDValue SelectFalse = Op.getOperand(2);
4106   SDLoc dl(Op);
4107   unsigned Opc = Cond.getOpcode();
4108 
4109   if (Cond.getResNo() == 1 &&
4110       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4111        Opc == ISD::USUBO)) {
4112     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4113       return SDValue();
4114 
4115     SDValue Value, OverflowCmp;
4116     SDValue ARMcc;
4117     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4118     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4119     EVT VT = Op.getValueType();
4120 
4121     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4122                    OverflowCmp, DAG);
4123   }
4124 
4125   // Convert:
4126   //
4127   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4128   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4129   //
4130   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4131     const ConstantSDNode *CMOVTrue =
4132       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4133     const ConstantSDNode *CMOVFalse =
4134       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4135 
4136     if (CMOVTrue && CMOVFalse) {
4137       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4138       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4139 
4140       SDValue True;
4141       SDValue False;
4142       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4143         True = SelectTrue;
4144         False = SelectFalse;
4145       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4146         True = SelectFalse;
4147         False = SelectTrue;
4148       }
4149 
4150       if (True.getNode() && False.getNode()) {
4151         EVT VT = Op.getValueType();
4152         SDValue ARMcc = Cond.getOperand(2);
4153         SDValue CCR = Cond.getOperand(3);
4154         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4155         assert(True.getValueType() == VT);
4156         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4157       }
4158     }
4159   }
4160 
4161   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4162   // undefined bits before doing a full-word comparison with zero.
4163   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4164                      DAG.getConstant(1, dl, Cond.getValueType()));
4165 
4166   return DAG.getSelectCC(dl, Cond,
4167                          DAG.getConstant(0, dl, Cond.getValueType()),
4168                          SelectTrue, SelectFalse, ISD::SETNE);
4169 }
4170 
4171 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4172                                  bool &swpCmpOps, bool &swpVselOps) {
4173   // Start by selecting the GE condition code for opcodes that return true for
4174   // 'equality'
4175   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4176       CC == ISD::SETULE)
4177     CondCode = ARMCC::GE;
4178 
4179   // and GT for opcodes that return false for 'equality'.
4180   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4181            CC == ISD::SETULT)
4182     CondCode = ARMCC::GT;
4183 
4184   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4185   // to swap the compare operands.
4186   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4187       CC == ISD::SETULT)
4188     swpCmpOps = true;
4189 
4190   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4191   // If we have an unordered opcode, we need to swap the operands to the VSEL
4192   // instruction (effectively negating the condition).
4193   //
4194   // This also has the effect of swapping which one of 'less' or 'greater'
4195   // returns true, so we also swap the compare operands. It also switches
4196   // whether we return true for 'equality', so we compensate by picking the
4197   // opposite condition code to our original choice.
4198   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4199       CC == ISD::SETUGT) {
4200     swpCmpOps = !swpCmpOps;
4201     swpVselOps = !swpVselOps;
4202     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4203   }
4204 
4205   // 'ordered' is 'anything but unordered', so use the VS condition code and
4206   // swap the VSEL operands.
4207   if (CC == ISD::SETO) {
4208     CondCode = ARMCC::VS;
4209     swpVselOps = true;
4210   }
4211 
4212   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4213   // code and swap the VSEL operands.
4214   if (CC == ISD::SETUNE) {
4215     CondCode = ARMCC::EQ;
4216     swpVselOps = true;
4217   }
4218 }
4219 
4220 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4221                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4222                                    SDValue Cmp, SelectionDAG &DAG) const {
4223   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4224     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4225                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4226     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4227                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4228 
4229     SDValue TrueLow = TrueVal.getValue(0);
4230     SDValue TrueHigh = TrueVal.getValue(1);
4231     SDValue FalseLow = FalseVal.getValue(0);
4232     SDValue FalseHigh = FalseVal.getValue(1);
4233 
4234     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4235                               ARMcc, CCR, Cmp);
4236     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4237                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4238 
4239     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4240   } else {
4241     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4242                        Cmp);
4243   }
4244 }
4245 
4246 static bool isGTorGE(ISD::CondCode CC) {
4247   return CC == ISD::SETGT || CC == ISD::SETGE;
4248 }
4249 
4250 static bool isLTorLE(ISD::CondCode CC) {
4251   return CC == ISD::SETLT || CC == ISD::SETLE;
4252 }
4253 
4254 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4255 // All of these conditions (and their <= and >= counterparts) will do:
4256 //          x < k ? k : x
4257 //          x > k ? x : k
4258 //          k < x ? x : k
4259 //          k > x ? k : x
4260 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4261                             const SDValue TrueVal, const SDValue FalseVal,
4262                             const ISD::CondCode CC, const SDValue K) {
4263   return (isGTorGE(CC) &&
4264           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4265          (isLTorLE(CC) &&
4266           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4267 }
4268 
4269 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4270 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4271                             const SDValue TrueVal, const SDValue FalseVal,
4272                             const ISD::CondCode CC, const SDValue K) {
4273   return (isGTorGE(CC) &&
4274           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4275          (isLTorLE(CC) &&
4276           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4277 }
4278 
4279 // Check if two chained conditionals could be converted into SSAT or USAT.
4280 //
4281 // SSAT can replace a set of two conditional selectors that bound a number to an
4282 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4283 //
4284 //     x < -k ? -k : (x > k ? k : x)
4285 //     x < -k ? -k : (x < k ? x : k)
4286 //     x > -k ? (x > k ? k : x) : -k
4287 //     x < k ? (x < -k ? -k : x) : k
4288 //     etc.
4289 //
4290 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4291 // a power of 2.
4292 //
4293 // It returns true if the conversion can be done, false otherwise.
4294 // Additionally, the variable is returned in parameter V, the constant in K and
4295 // usat is set to true if the conditional represents an unsigned saturation
4296 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4297                                     uint64_t &K, bool &usat) {
4298   SDValue LHS1 = Op.getOperand(0);
4299   SDValue RHS1 = Op.getOperand(1);
4300   SDValue TrueVal1 = Op.getOperand(2);
4301   SDValue FalseVal1 = Op.getOperand(3);
4302   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4303 
4304   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4305   if (Op2.getOpcode() != ISD::SELECT_CC)
4306     return false;
4307 
4308   SDValue LHS2 = Op2.getOperand(0);
4309   SDValue RHS2 = Op2.getOperand(1);
4310   SDValue TrueVal2 = Op2.getOperand(2);
4311   SDValue FalseVal2 = Op2.getOperand(3);
4312   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4313 
4314   // Find out which are the constants and which are the variables
4315   // in each conditional
4316   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4317                                                         ? &RHS1
4318                                                         : nullptr;
4319   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4320                                                         ? &RHS2
4321                                                         : nullptr;
4322   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4323   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4324   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4325   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4326 
4327   // We must detect cases where the original operations worked with 16- or
4328   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4329   // must work with sign-extended values but the select operations return
4330   // the original non-extended value.
4331   SDValue V2TmpReg = V2Tmp;
4332   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4333     V2TmpReg = V2Tmp->getOperand(0);
4334 
4335   // Check that the registers and the constants have the correct values
4336   // in both conditionals
4337   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4338       V2TmpReg != V2)
4339     return false;
4340 
4341   // Figure out which conditional is saturating the lower/upper bound.
4342   const SDValue *LowerCheckOp =
4343       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4344           ? &Op
4345           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4346                 ? &Op2
4347                 : nullptr;
4348   const SDValue *UpperCheckOp =
4349       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4350           ? &Op
4351           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4352                 ? &Op2
4353                 : nullptr;
4354 
4355   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4356     return false;
4357 
4358   // Check that the constant in the lower-bound check is
4359   // the opposite of the constant in the upper-bound check
4360   // in 1's complement.
4361   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4362   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4363   int64_t PosVal = std::max(Val1, Val2);
4364   int64_t NegVal = std::min(Val1, Val2);
4365 
4366   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4367        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4368       isPowerOf2_64(PosVal + 1)) {
4369 
4370     // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4371     if (Val1 == ~Val2)
4372       usat = false;
4373     else if (NegVal == 0)
4374       usat = true;
4375     else
4376       return false;
4377 
4378     V = V2;
4379     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4380 
4381     return true;
4382   }
4383 
4384   return false;
4385 }
4386 
4387 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4388   EVT VT = Op.getValueType();
4389   SDLoc dl(Op);
4390 
4391   // Try to convert two saturating conditional selects into a single SSAT
4392   SDValue SatValue;
4393   uint64_t SatConstant;
4394   bool SatUSat;
4395   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4396       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4397     if (SatUSat)
4398       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4399                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4400     else
4401       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4402                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4403   }
4404 
4405   SDValue LHS = Op.getOperand(0);
4406   SDValue RHS = Op.getOperand(1);
4407   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4408   SDValue TrueVal = Op.getOperand(2);
4409   SDValue FalseVal = Op.getOperand(3);
4410 
4411   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4412     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4413                                                     dl);
4414 
4415     // If softenSetCCOperands only returned one value, we should compare it to
4416     // zero.
4417     if (!RHS.getNode()) {
4418       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4419       CC = ISD::SETNE;
4420     }
4421   }
4422 
4423   if (LHS.getValueType() == MVT::i32) {
4424     // Try to generate VSEL on ARMv8.
4425     // The VSEL instruction can't use all the usual ARM condition
4426     // codes: it only has two bits to select the condition code, so it's
4427     // constrained to use only GE, GT, VS and EQ.
4428     //
4429     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4430     // swap the operands of the previous compare instruction (effectively
4431     // inverting the compare condition, swapping 'less' and 'greater') and
4432     // sometimes need to swap the operands to the VSEL (which inverts the
4433     // condition in the sense of firing whenever the previous condition didn't)
4434     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4435                                     TrueVal.getValueType() == MVT::f64)) {
4436       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4437       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4438           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4439         CC = ISD::getSetCCInverse(CC, true);
4440         std::swap(TrueVal, FalseVal);
4441       }
4442     }
4443 
4444     SDValue ARMcc;
4445     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4446     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4447     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4448   }
4449 
4450   ARMCC::CondCodes CondCode, CondCode2;
4451   bool InvalidOnQNaN;
4452   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4453 
4454   // Try to generate VMAXNM/VMINNM on ARMv8.
4455   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4456                                   TrueVal.getValueType() == MVT::f64)) {
4457     bool swpCmpOps = false;
4458     bool swpVselOps = false;
4459     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4460 
4461     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4462         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4463       if (swpCmpOps)
4464         std::swap(LHS, RHS);
4465       if (swpVselOps)
4466         std::swap(TrueVal, FalseVal);
4467     }
4468   }
4469 
4470   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4471   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4472   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4473   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4474   if (CondCode2 != ARMCC::AL) {
4475     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4476     // FIXME: Needs another CMP because flag can have but one use.
4477     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4478     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4479   }
4480   return Result;
4481 }
4482 
4483 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4484 /// to morph to an integer compare sequence.
4485 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4486                            const ARMSubtarget *Subtarget) {
4487   SDNode *N = Op.getNode();
4488   if (!N->hasOneUse())
4489     // Otherwise it requires moving the value from fp to integer registers.
4490     return false;
4491   if (!N->getNumValues())
4492     return false;
4493   EVT VT = Op.getValueType();
4494   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4495     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4496     // vmrs are very slow, e.g. cortex-a8.
4497     return false;
4498 
4499   if (isFloatingPointZero(Op)) {
4500     SeenZero = true;
4501     return true;
4502   }
4503   return ISD::isNormalLoad(N);
4504 }
4505 
4506 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4507   if (isFloatingPointZero(Op))
4508     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4509 
4510   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4511     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4512                        Ld->getPointerInfo(), Ld->getAlignment(),
4513                        Ld->getMemOperand()->getFlags());
4514 
4515   llvm_unreachable("Unknown VFP cmp argument!");
4516 }
4517 
4518 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4519                            SDValue &RetVal1, SDValue &RetVal2) {
4520   SDLoc dl(Op);
4521 
4522   if (isFloatingPointZero(Op)) {
4523     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4524     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4525     return;
4526   }
4527 
4528   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4529     SDValue Ptr = Ld->getBasePtr();
4530     RetVal1 =
4531         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4532                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4533 
4534     EVT PtrType = Ptr.getValueType();
4535     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4536     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4537                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4538     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4539                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4540                           Ld->getMemOperand()->getFlags());
4541     return;
4542   }
4543 
4544   llvm_unreachable("Unknown VFP cmp argument!");
4545 }
4546 
4547 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4548 /// f32 and even f64 comparisons to integer ones.
4549 SDValue
4550 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4551   SDValue Chain = Op.getOperand(0);
4552   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4553   SDValue LHS = Op.getOperand(2);
4554   SDValue RHS = Op.getOperand(3);
4555   SDValue Dest = Op.getOperand(4);
4556   SDLoc dl(Op);
4557 
4558   bool LHSSeenZero = false;
4559   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4560   bool RHSSeenZero = false;
4561   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4562   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4563     // If unsafe fp math optimization is enabled and there are no other uses of
4564     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4565     // to an integer comparison.
4566     if (CC == ISD::SETOEQ)
4567       CC = ISD::SETEQ;
4568     else if (CC == ISD::SETUNE)
4569       CC = ISD::SETNE;
4570 
4571     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4572     SDValue ARMcc;
4573     if (LHS.getValueType() == MVT::f32) {
4574       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4575                         bitcastf32Toi32(LHS, DAG), Mask);
4576       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4577                         bitcastf32Toi32(RHS, DAG), Mask);
4578       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4579       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4580       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4581                          Chain, Dest, ARMcc, CCR, Cmp);
4582     }
4583 
4584     SDValue LHS1, LHS2;
4585     SDValue RHS1, RHS2;
4586     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4587     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4588     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4589     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4590     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4591     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4592     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4593     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4594     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4595   }
4596 
4597   return SDValue();
4598 }
4599 
4600 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4601   SDValue Chain = Op.getOperand(0);
4602   SDValue Cond = Op.getOperand(1);
4603   SDValue Dest = Op.getOperand(2);
4604   SDLoc dl(Op);
4605 
4606   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4607   // instruction.
4608   unsigned Opc = Cond.getOpcode();
4609   if (Cond.getResNo() == 1 &&
4610       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4611        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4612     // Only lower legal XALUO ops.
4613     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4614       return SDValue();
4615 
4616     // The actual operation with overflow check.
4617     SDValue Value, OverflowCmp;
4618     SDValue ARMcc;
4619     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4620 
4621     // Reverse the condition code.
4622     ARMCC::CondCodes CondCode =
4623         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4624     CondCode = ARMCC::getOppositeCondition(CondCode);
4625     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4626     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4627 
4628     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4629                        OverflowCmp);
4630   }
4631 
4632   return SDValue();
4633 }
4634 
4635 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4636   SDValue Chain = Op.getOperand(0);
4637   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4638   SDValue LHS = Op.getOperand(2);
4639   SDValue RHS = Op.getOperand(3);
4640   SDValue Dest = Op.getOperand(4);
4641   SDLoc dl(Op);
4642 
4643   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4644     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4645                                                     dl);
4646 
4647     // If softenSetCCOperands only returned one value, we should compare it to
4648     // zero.
4649     if (!RHS.getNode()) {
4650       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4651       CC = ISD::SETNE;
4652     }
4653   }
4654 
4655   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4656   // instruction.
4657   unsigned Opc = LHS.getOpcode();
4658   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
4659       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4660        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4661       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4662     // Only lower legal XALUO ops.
4663     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4664       return SDValue();
4665 
4666     // The actual operation with overflow check.
4667     SDValue Value, OverflowCmp;
4668     SDValue ARMcc;
4669     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
4670 
4671     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
4672       // Reverse the condition code.
4673       ARMCC::CondCodes CondCode =
4674           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4675       CondCode = ARMCC::getOppositeCondition(CondCode);
4676       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4677     }
4678     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4679 
4680     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4681                        OverflowCmp);
4682   }
4683 
4684   if (LHS.getValueType() == MVT::i32) {
4685     SDValue ARMcc;
4686     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4687     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4688     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4689                        Chain, Dest, ARMcc, CCR, Cmp);
4690   }
4691 
4692   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4693 
4694   if (getTargetMachine().Options.UnsafeFPMath &&
4695       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4696        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4697     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4698       return Result;
4699   }
4700 
4701   ARMCC::CondCodes CondCode, CondCode2;
4702   bool InvalidOnQNaN;
4703   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4704 
4705   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4706   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4707   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4708   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4709   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4710   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4711   if (CondCode2 != ARMCC::AL) {
4712     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4713     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4714     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4715   }
4716   return Res;
4717 }
4718 
4719 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4720   SDValue Chain = Op.getOperand(0);
4721   SDValue Table = Op.getOperand(1);
4722   SDValue Index = Op.getOperand(2);
4723   SDLoc dl(Op);
4724 
4725   EVT PTy = getPointerTy(DAG.getDataLayout());
4726   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4727   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4728   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4729   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4730   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
4731   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4732     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4733     // which does another jump to the destination. This also makes it easier
4734     // to translate it to TBB / TBH later (Thumb2 only).
4735     // FIXME: This might not work if the function is extremely large.
4736     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4737                        Addr, Op.getOperand(2), JTI);
4738   }
4739   if (isPositionIndependent() || Subtarget->isROPI()) {
4740     Addr =
4741         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4742                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4743     Chain = Addr.getValue(1);
4744     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
4745     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4746   } else {
4747     Addr =
4748         DAG.getLoad(PTy, dl, Chain, Addr,
4749                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4750     Chain = Addr.getValue(1);
4751     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4752   }
4753 }
4754 
4755 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4756   EVT VT = Op.getValueType();
4757   SDLoc dl(Op);
4758 
4759   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4760     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4761       return Op;
4762     return DAG.UnrollVectorOp(Op.getNode());
4763   }
4764 
4765   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4766          "Invalid type for custom lowering!");
4767   if (VT != MVT::v4i16)
4768     return DAG.UnrollVectorOp(Op.getNode());
4769 
4770   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4771   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4772 }
4773 
4774 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4775   EVT VT = Op.getValueType();
4776   if (VT.isVector())
4777     return LowerVectorFP_TO_INT(Op, DAG);
4778   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4779     RTLIB::Libcall LC;
4780     if (Op.getOpcode() == ISD::FP_TO_SINT)
4781       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4782                               Op.getValueType());
4783     else
4784       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4785                               Op.getValueType());
4786     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4787                        /*isSigned*/ false, SDLoc(Op)).first;
4788   }
4789 
4790   return Op;
4791 }
4792 
4793 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4794   EVT VT = Op.getValueType();
4795   SDLoc dl(Op);
4796 
4797   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4798     if (VT.getVectorElementType() == MVT::f32)
4799       return Op;
4800     return DAG.UnrollVectorOp(Op.getNode());
4801   }
4802 
4803   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4804          "Invalid type for custom lowering!");
4805   if (VT != MVT::v4f32)
4806     return DAG.UnrollVectorOp(Op.getNode());
4807 
4808   unsigned CastOpc;
4809   unsigned Opc;
4810   switch (Op.getOpcode()) {
4811   default: llvm_unreachable("Invalid opcode!");
4812   case ISD::SINT_TO_FP:
4813     CastOpc = ISD::SIGN_EXTEND;
4814     Opc = ISD::SINT_TO_FP;
4815     break;
4816   case ISD::UINT_TO_FP:
4817     CastOpc = ISD::ZERO_EXTEND;
4818     Opc = ISD::UINT_TO_FP;
4819     break;
4820   }
4821 
4822   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4823   return DAG.getNode(Opc, dl, VT, Op);
4824 }
4825 
4826 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4827   EVT VT = Op.getValueType();
4828   if (VT.isVector())
4829     return LowerVectorINT_TO_FP(Op, DAG);
4830   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4831     RTLIB::Libcall LC;
4832     if (Op.getOpcode() == ISD::SINT_TO_FP)
4833       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4834                               Op.getValueType());
4835     else
4836       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4837                               Op.getValueType());
4838     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4839                        /*isSigned*/ false, SDLoc(Op)).first;
4840   }
4841 
4842   return Op;
4843 }
4844 
4845 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4846   // Implement fcopysign with a fabs and a conditional fneg.
4847   SDValue Tmp0 = Op.getOperand(0);
4848   SDValue Tmp1 = Op.getOperand(1);
4849   SDLoc dl(Op);
4850   EVT VT = Op.getValueType();
4851   EVT SrcVT = Tmp1.getValueType();
4852   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4853     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4854   bool UseNEON = !InGPR && Subtarget->hasNEON();
4855 
4856   if (UseNEON) {
4857     // Use VBSL to copy the sign bit.
4858     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4859     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4860                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4861     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4862     if (VT == MVT::f64)
4863       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4864                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4865                          DAG.getConstant(32, dl, MVT::i32));
4866     else /*if (VT == MVT::f32)*/
4867       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4868     if (SrcVT == MVT::f32) {
4869       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4870       if (VT == MVT::f64)
4871         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4872                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4873                            DAG.getConstant(32, dl, MVT::i32));
4874     } else if (VT == MVT::f32)
4875       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4876                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4877                          DAG.getConstant(32, dl, MVT::i32));
4878     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4879     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4880 
4881     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4882                                             dl, MVT::i32);
4883     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4884     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4885                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4886 
4887     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4888                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4889                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4890     if (VT == MVT::f32) {
4891       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4892       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4893                         DAG.getConstant(0, dl, MVT::i32));
4894     } else {
4895       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4896     }
4897 
4898     return Res;
4899   }
4900 
4901   // Bitcast operand 1 to i32.
4902   if (SrcVT == MVT::f64)
4903     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4904                        Tmp1).getValue(1);
4905   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4906 
4907   // Or in the signbit with integer operations.
4908   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4909   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4910   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4911   if (VT == MVT::f32) {
4912     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4913                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4914     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4915                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4916   }
4917 
4918   // f64: Or the high part with signbit and then combine two parts.
4919   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4920                      Tmp0);
4921   SDValue Lo = Tmp0.getValue(0);
4922   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4923   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4924   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4925 }
4926 
4927 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4928   MachineFunction &MF = DAG.getMachineFunction();
4929   MachineFrameInfo &MFI = MF.getFrameInfo();
4930   MFI.setReturnAddressIsTaken(true);
4931 
4932   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4933     return SDValue();
4934 
4935   EVT VT = Op.getValueType();
4936   SDLoc dl(Op);
4937   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4938   if (Depth) {
4939     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4940     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4941     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4942                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4943                        MachinePointerInfo());
4944   }
4945 
4946   // Return LR, which contains the return address. Mark it an implicit live-in.
4947   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4948   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4949 }
4950 
4951 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4952   const ARMBaseRegisterInfo &ARI =
4953     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4954   MachineFunction &MF = DAG.getMachineFunction();
4955   MachineFrameInfo &MFI = MF.getFrameInfo();
4956   MFI.setFrameAddressIsTaken(true);
4957 
4958   EVT VT = Op.getValueType();
4959   SDLoc dl(Op);  // FIXME probably not meaningful
4960   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4961   unsigned FrameReg = ARI.getFrameRegister(MF);
4962   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4963   while (Depth--)
4964     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4965                             MachinePointerInfo());
4966   return FrameAddr;
4967 }
4968 
4969 // FIXME? Maybe this could be a TableGen attribute on some registers and
4970 // this table could be generated automatically from RegInfo.
4971 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4972                                               SelectionDAG &DAG) const {
4973   unsigned Reg = StringSwitch<unsigned>(RegName)
4974                        .Case("sp", ARM::SP)
4975                        .Default(0);
4976   if (Reg)
4977     return Reg;
4978   report_fatal_error(Twine("Invalid register name \""
4979                               + StringRef(RegName)  + "\"."));
4980 }
4981 
4982 // Result is 64 bit value so split into two 32 bit values and return as a
4983 // pair of values.
4984 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4985                                 SelectionDAG &DAG) {
4986   SDLoc DL(N);
4987 
4988   // This function is only supposed to be called for i64 type destination.
4989   assert(N->getValueType(0) == MVT::i64
4990           && "ExpandREAD_REGISTER called for non-i64 type result.");
4991 
4992   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4993                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4994                              N->getOperand(0),
4995                              N->getOperand(1));
4996 
4997   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4998                     Read.getValue(1)));
4999   Results.push_back(Read.getOperand(0));
5000 }
5001 
5002 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5003 /// When \p DstVT, the destination type of \p BC, is on the vector
5004 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5005 /// it might be possible to combine them, such that everything stays on the
5006 /// vector register bank.
5007 /// \p return The node that would replace \p BT, if the combine
5008 /// is possible.
5009 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5010                                                 SelectionDAG &DAG) {
5011   SDValue Op = BC->getOperand(0);
5012   EVT DstVT = BC->getValueType(0);
5013 
5014   // The only vector instruction that can produce a scalar (remember,
5015   // since the bitcast was about to be turned into VMOVDRR, the source
5016   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5017   // Moreover, we can do this combine only if there is one use.
5018   // Finally, if the destination type is not a vector, there is not
5019   // much point on forcing everything on the vector bank.
5020   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5021       !Op.hasOneUse())
5022     return SDValue();
5023 
5024   // If the index is not constant, we will introduce an additional
5025   // multiply that will stick.
5026   // Give up in that case.
5027   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5028   if (!Index)
5029     return SDValue();
5030   unsigned DstNumElt = DstVT.getVectorNumElements();
5031 
5032   // Compute the new index.
5033   const APInt &APIntIndex = Index->getAPIntValue();
5034   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5035   NewIndex *= APIntIndex;
5036   // Check if the new constant index fits into i32.
5037   if (NewIndex.getBitWidth() > 32)
5038     return SDValue();
5039 
5040   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5041   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5042   SDLoc dl(Op);
5043   SDValue ExtractSrc = Op.getOperand(0);
5044   EVT VecVT = EVT::getVectorVT(
5045       *DAG.getContext(), DstVT.getScalarType(),
5046       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5047   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5048   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5049                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5050 }
5051 
5052 /// ExpandBITCAST - If the target supports VFP, this function is called to
5053 /// expand a bit convert where either the source or destination type is i64 to
5054 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5055 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5056 /// vectors), since the legalizer won't know what to do with that.
5057 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5058                              const ARMSubtarget *Subtarget) {
5059   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5060   SDLoc dl(N);
5061   SDValue Op = N->getOperand(0);
5062 
5063   // This function is only supposed to be called for i64 types, either as the
5064   // source or destination of the bit convert.
5065   EVT SrcVT = Op.getValueType();
5066   EVT DstVT = N->getValueType(0);
5067   const bool HasFullFP16 = Subtarget->hasFullFP16();
5068 
5069   if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5070      // FullFP16: half values are passed in S-registers, and we don't
5071      // need any of the bitcast and moves:
5072      //
5073      // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5074      //   t5: i32 = bitcast t2
5075      // t18: f16 = ARMISD::VMOVhr t5
5076      if (Op.getOpcode() != ISD::CopyFromReg ||
5077          Op.getValueType() != MVT::f32)
5078        return SDValue();
5079 
5080      auto Move = N->use_begin();
5081      if (Move->getOpcode() != ARMISD::VMOVhr)
5082        return SDValue();
5083 
5084      SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5085      SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5086      DAG.ReplaceAllUsesWith(*Move, &Copy);
5087      return Copy;
5088   }
5089 
5090   if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5091     if (!HasFullFP16)
5092       return SDValue();
5093     // SoftFP: read half-precision arguments:
5094     //
5095     // t2: i32,ch = ...
5096     //        t7: i16 = truncate t2 <~~~~ Op
5097     //      t8: f16 = bitcast t7    <~~~~ N
5098     //
5099     if (Op.getOperand(0).getValueType() == MVT::i32)
5100       return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5101                          MVT::f16, Op.getOperand(0));
5102 
5103     return SDValue();
5104   }
5105 
5106   // Half-precision return values
5107   if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5108     if (!HasFullFP16)
5109       return SDValue();
5110     //
5111     //          t11: f16 = fadd t8, t10
5112     //        t12: i16 = bitcast t11       <~~~ SDNode N
5113     //      t13: i32 = zero_extend t12
5114     //    t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5115     //  t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5116     //
5117     // transform this into:
5118     //
5119     //    t20: i32 = ARMISD::VMOVrh t11
5120     //  t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5121     //
5122     auto ZeroExtend = N->use_begin();
5123     if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5124         ZeroExtend->getValueType(0) != MVT::i32)
5125       return SDValue();
5126 
5127     auto Copy = ZeroExtend->use_begin();
5128     if (Copy->getOpcode() == ISD::CopyToReg &&
5129         Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5130       SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5131       DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5132       return Cvt;
5133     }
5134     return SDValue();
5135   }
5136 
5137   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5138     return SDValue();
5139 
5140   // Turn i64->f64 into VMOVDRR.
5141   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5142     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5143     // if we can combine the bitcast with its source.
5144     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5145       return Val;
5146 
5147     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5148                              DAG.getConstant(0, dl, MVT::i32));
5149     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5150                              DAG.getConstant(1, dl, MVT::i32));
5151     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5152                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5153   }
5154 
5155   // Turn f64->i64 into VMOVRRD.
5156   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5157     SDValue Cvt;
5158     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5159         SrcVT.getVectorNumElements() > 1)
5160       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5161                         DAG.getVTList(MVT::i32, MVT::i32),
5162                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5163     else
5164       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5165                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5166     // Merge the pieces into a single i64 value.
5167     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5168   }
5169 
5170   return SDValue();
5171 }
5172 
5173 /// getZeroVector - Returns a vector of specified type with all zero elements.
5174 /// Zero vectors are used to represent vector negation and in those cases
5175 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
5176 /// not support i64 elements, so sometimes the zero vectors will need to be
5177 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
5178 /// zero vector.
5179 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5180   assert(VT.isVector() && "Expected a vector type");
5181   // The canonical modified immediate encoding of a zero vector is....0!
5182   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5183   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5184   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5185   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5186 }
5187 
5188 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5189 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5190 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5191                                                 SelectionDAG &DAG) const {
5192   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5193   EVT VT = Op.getValueType();
5194   unsigned VTBits = VT.getSizeInBits();
5195   SDLoc dl(Op);
5196   SDValue ShOpLo = Op.getOperand(0);
5197   SDValue ShOpHi = Op.getOperand(1);
5198   SDValue ShAmt  = Op.getOperand(2);
5199   SDValue ARMcc;
5200   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5201   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5202 
5203   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5204 
5205   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5206                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5207   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5208   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5209                                    DAG.getConstant(VTBits, dl, MVT::i32));
5210   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5211   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5212   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5213   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5214                             ISD::SETGE, ARMcc, DAG, dl);
5215   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5216                            ARMcc, CCR, CmpLo);
5217 
5218   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5219   SDValue HiBigShift = Opc == ISD::SRA
5220                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5221                                          DAG.getConstant(VTBits - 1, dl, VT))
5222                            : DAG.getConstant(0, dl, VT);
5223   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5224                             ISD::SETGE, ARMcc, DAG, dl);
5225   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5226                            ARMcc, CCR, CmpHi);
5227 
5228   SDValue Ops[2] = { Lo, Hi };
5229   return DAG.getMergeValues(Ops, dl);
5230 }
5231 
5232 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5233 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5234 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5235                                                SelectionDAG &DAG) const {
5236   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5237   EVT VT = Op.getValueType();
5238   unsigned VTBits = VT.getSizeInBits();
5239   SDLoc dl(Op);
5240   SDValue ShOpLo = Op.getOperand(0);
5241   SDValue ShOpHi = Op.getOperand(1);
5242   SDValue ShAmt  = Op.getOperand(2);
5243   SDValue ARMcc;
5244   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5245 
5246   assert(Op.getOpcode() == ISD::SHL_PARTS);
5247   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5248                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5249   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5250   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5251   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5252 
5253   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5254                                    DAG.getConstant(VTBits, dl, MVT::i32));
5255   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5256   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5257                             ISD::SETGE, ARMcc, DAG, dl);
5258   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5259                            ARMcc, CCR, CmpHi);
5260 
5261   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5262                           ISD::SETGE, ARMcc, DAG, dl);
5263   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5264   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5265                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5266 
5267   SDValue Ops[2] = { Lo, Hi };
5268   return DAG.getMergeValues(Ops, dl);
5269 }
5270 
5271 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5272                                             SelectionDAG &DAG) const {
5273   // The rounding mode is in bits 23:22 of the FPSCR.
5274   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5275   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5276   // so that the shift + and get folded into a bitfield extract.
5277   SDLoc dl(Op);
5278   SDValue Ops[] = { DAG.getEntryNode(),
5279                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5280 
5281   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5282   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5283                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5284   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5285                               DAG.getConstant(22, dl, MVT::i32));
5286   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5287                      DAG.getConstant(3, dl, MVT::i32));
5288 }
5289 
5290 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5291                          const ARMSubtarget *ST) {
5292   SDLoc dl(N);
5293   EVT VT = N->getValueType(0);
5294   if (VT.isVector()) {
5295     assert(ST->hasNEON());
5296 
5297     // Compute the least significant set bit: LSB = X & -X
5298     SDValue X = N->getOperand(0);
5299     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5300     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5301 
5302     EVT ElemTy = VT.getVectorElementType();
5303 
5304     if (ElemTy == MVT::i8) {
5305       // Compute with: cttz(x) = ctpop(lsb - 1)
5306       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5307                                 DAG.getTargetConstant(1, dl, ElemTy));
5308       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5309       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5310     }
5311 
5312     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5313         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5314       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5315       unsigned NumBits = ElemTy.getSizeInBits();
5316       SDValue WidthMinus1 =
5317           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5318                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5319       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5320       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5321     }
5322 
5323     // Compute with: cttz(x) = ctpop(lsb - 1)
5324 
5325     // Since we can only compute the number of bits in a byte with vcnt.8, we
5326     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
5327     // and i64.
5328 
5329     // Compute LSB - 1.
5330     SDValue Bits;
5331     if (ElemTy == MVT::i64) {
5332       // Load constant 0xffff'ffff'ffff'ffff to register.
5333       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5334                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5335       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5336     } else {
5337       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5338                                 DAG.getTargetConstant(1, dl, ElemTy));
5339       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5340     }
5341 
5342     // Count #bits with vcnt.8.
5343     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5344     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5345     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5346 
5347     // Gather the #bits with vpaddl (pairwise add.)
5348     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5349     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5350         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5351         Cnt8);
5352     if (ElemTy == MVT::i16)
5353       return Cnt16;
5354 
5355     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5356     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5357         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5358         Cnt16);
5359     if (ElemTy == MVT::i32)
5360       return Cnt32;
5361 
5362     assert(ElemTy == MVT::i64);
5363     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5364         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5365         Cnt32);
5366     return Cnt64;
5367   }
5368 
5369   if (!ST->hasV6T2Ops())
5370     return SDValue();
5371 
5372   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5373   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5374 }
5375 
5376 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5377 /// for each 16-bit element from operand, repeated.  The basic idea is to
5378 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5379 ///
5380 /// Trace for v4i16:
5381 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
5382 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5383 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5384 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5385 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
5386 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
5387 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5388 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
5389 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5390   EVT VT = N->getValueType(0);
5391   SDLoc DL(N);
5392 
5393   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5394   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5395   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5396   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5397   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5398   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5399 }
5400 
5401 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5402 /// bit-count for each 16-bit element from the operand.  We need slightly
5403 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5404 /// 64/128-bit registers.
5405 ///
5406 /// Trace for v4i16:
5407 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
5408 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5409 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
5410 /// v4i16:Extracted = [k0    k1    k2    k3    ]
5411 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5412   EVT VT = N->getValueType(0);
5413   SDLoc DL(N);
5414 
5415   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5416   if (VT.is64BitVector()) {
5417     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5418     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5419                        DAG.getIntPtrConstant(0, DL));
5420   } else {
5421     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5422                                     BitCounts, DAG.getIntPtrConstant(0, DL));
5423     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5424   }
5425 }
5426 
5427 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5428 /// bit-count for each 32-bit element from the operand.  The idea here is
5429 /// to split the vector into 16-bit elements, leverage the 16-bit count
5430 /// routine, and then combine the results.
5431 ///
5432 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5433 /// input    = [v0    v1    ] (vi: 32-bit elements)
5434 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5435 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5436 /// vrev: N0 = [k1 k0 k3 k2 ]
5437 ///            [k0 k1 k2 k3 ]
5438 ///       N1 =+[k1 k0 k3 k2 ]
5439 ///            [k0 k2 k1 k3 ]
5440 ///       N2 =+[k1 k3 k0 k2 ]
5441 ///            [k0    k2    k1    k3    ]
5442 /// Extended =+[k1    k3    k0    k2    ]
5443 ///            [k0    k2    ]
5444 /// Extracted=+[k1    k3    ]
5445 ///
5446 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5447   EVT VT = N->getValueType(0);
5448   SDLoc DL(N);
5449 
5450   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5451 
5452   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5453   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5454   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5455   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5456   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5457 
5458   if (VT.is64BitVector()) {
5459     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5460     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5461                        DAG.getIntPtrConstant(0, DL));
5462   } else {
5463     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5464                                     DAG.getIntPtrConstant(0, DL));
5465     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5466   }
5467 }
5468 
5469 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5470                           const ARMSubtarget *ST) {
5471   EVT VT = N->getValueType(0);
5472 
5473   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5474   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5475           VT == MVT::v4i16 || VT == MVT::v8i16) &&
5476          "Unexpected type for custom ctpop lowering");
5477 
5478   if (VT.getVectorElementType() == MVT::i32)
5479     return lowerCTPOP32BitElements(N, DAG);
5480   else
5481     return lowerCTPOP16BitElements(N, DAG);
5482 }
5483 
5484 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5485                           const ARMSubtarget *ST) {
5486   EVT VT = N->getValueType(0);
5487   SDLoc dl(N);
5488 
5489   if (!VT.isVector())
5490     return SDValue();
5491 
5492   // Lower vector shifts on NEON to use VSHL.
5493   assert(ST->hasNEON() && "unexpected vector shift");
5494 
5495   // Left shifts translate directly to the vshiftu intrinsic.
5496   if (N->getOpcode() == ISD::SHL)
5497     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5498                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5499                                        MVT::i32),
5500                        N->getOperand(0), N->getOperand(1));
5501 
5502   assert((N->getOpcode() == ISD::SRA ||
5503           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5504 
5505   // NEON uses the same intrinsics for both left and right shifts.  For
5506   // right shifts, the shift amounts are negative, so negate the vector of
5507   // shift amounts.
5508   EVT ShiftVT = N->getOperand(1).getValueType();
5509   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5510                                      getZeroVector(ShiftVT, DAG, dl),
5511                                      N->getOperand(1));
5512   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5513                              Intrinsic::arm_neon_vshifts :
5514                              Intrinsic::arm_neon_vshiftu);
5515   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5516                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5517                      N->getOperand(0), NegatedCount);
5518 }
5519 
5520 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5521                                 const ARMSubtarget *ST) {
5522   EVT VT = N->getValueType(0);
5523   SDLoc dl(N);
5524 
5525   // We can get here for a node like i32 = ISD::SHL i32, i64
5526   if (VT != MVT::i64)
5527     return SDValue();
5528 
5529   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5530          "Unknown shift to lower!");
5531 
5532   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5533   if (!isOneConstant(N->getOperand(1)))
5534     return SDValue();
5535 
5536   // If we are in thumb mode, we don't have RRX.
5537   if (ST->isThumb1Only()) return SDValue();
5538 
5539   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5540   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5541                            DAG.getConstant(0, dl, MVT::i32));
5542   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5543                            DAG.getConstant(1, dl, MVT::i32));
5544 
5545   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5546   // captures the result into a carry flag.
5547   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5548   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5549 
5550   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5551   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5552 
5553   // Merge the pieces into a single i64 value.
5554  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5555 }
5556 
5557 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5558   SDValue TmpOp0, TmpOp1;
5559   bool Invert = false;
5560   bool Swap = false;
5561   unsigned Opc = 0;
5562 
5563   SDValue Op0 = Op.getOperand(0);
5564   SDValue Op1 = Op.getOperand(1);
5565   SDValue CC = Op.getOperand(2);
5566   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5567   EVT VT = Op.getValueType();
5568   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5569   SDLoc dl(Op);
5570 
5571   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5572       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5573     // Special-case integer 64-bit equality comparisons. They aren't legal,
5574     // but they can be lowered with a few vector instructions.
5575     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5576     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5577     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5578     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5579     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5580                               DAG.getCondCode(ISD::SETEQ));
5581     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5582     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5583     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5584     if (SetCCOpcode == ISD::SETNE)
5585       Merged = DAG.getNOT(dl, Merged, CmpVT);
5586     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5587     return Merged;
5588   }
5589 
5590   if (CmpVT.getVectorElementType() == MVT::i64)
5591     // 64-bit comparisons are not legal in general.
5592     return SDValue();
5593 
5594   if (Op1.getValueType().isFloatingPoint()) {
5595     switch (SetCCOpcode) {
5596     default: llvm_unreachable("Illegal FP comparison");
5597     case ISD::SETUNE:
5598     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5599     case ISD::SETOEQ:
5600     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5601     case ISD::SETOLT:
5602     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5603     case ISD::SETOGT:
5604     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5605     case ISD::SETOLE:
5606     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5607     case ISD::SETOGE:
5608     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5609     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5610     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5611     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5612     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5613     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5614     case ISD::SETONE:
5615       // Expand this to (OLT | OGT).
5616       TmpOp0 = Op0;
5617       TmpOp1 = Op1;
5618       Opc = ISD::OR;
5619       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5620       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5621       break;
5622     case ISD::SETUO:
5623       Invert = true;
5624       LLVM_FALLTHROUGH;
5625     case ISD::SETO:
5626       // Expand this to (OLT | OGE).
5627       TmpOp0 = Op0;
5628       TmpOp1 = Op1;
5629       Opc = ISD::OR;
5630       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5631       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5632       break;
5633     }
5634   } else {
5635     // Integer comparisons.
5636     switch (SetCCOpcode) {
5637     default: llvm_unreachable("Illegal integer comparison");
5638     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5639     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5640     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
5641     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5642     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5643     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5644     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5645     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5646     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5647     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5648     }
5649 
5650     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5651     if (Opc == ARMISD::VCEQ) {
5652       SDValue AndOp;
5653       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5654         AndOp = Op0;
5655       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5656         AndOp = Op1;
5657 
5658       // Ignore bitconvert.
5659       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5660         AndOp = AndOp.getOperand(0);
5661 
5662       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5663         Opc = ARMISD::VTST;
5664         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5665         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5666         Invert = !Invert;
5667       }
5668     }
5669   }
5670 
5671   if (Swap)
5672     std::swap(Op0, Op1);
5673 
5674   // If one of the operands is a constant vector zero, attempt to fold the
5675   // comparison to a specialized compare-against-zero form.
5676   SDValue SingleOp;
5677   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5678     SingleOp = Op0;
5679   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5680     if (Opc == ARMISD::VCGE)
5681       Opc = ARMISD::VCLEZ;
5682     else if (Opc == ARMISD::VCGT)
5683       Opc = ARMISD::VCLTZ;
5684     SingleOp = Op1;
5685   }
5686 
5687   SDValue Result;
5688   if (SingleOp.getNode()) {
5689     switch (Opc) {
5690     case ARMISD::VCEQ:
5691       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5692     case ARMISD::VCGE:
5693       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5694     case ARMISD::VCLEZ:
5695       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5696     case ARMISD::VCGT:
5697       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5698     case ARMISD::VCLTZ:
5699       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5700     default:
5701       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5702     }
5703   } else {
5704      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5705   }
5706 
5707   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5708 
5709   if (Invert)
5710     Result = DAG.getNOT(dl, Result, VT);
5711 
5712   return Result;
5713 }
5714 
5715 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5716   SDValue LHS = Op.getOperand(0);
5717   SDValue RHS = Op.getOperand(1);
5718   SDValue Carry = Op.getOperand(2);
5719   SDValue Cond = Op.getOperand(3);
5720   SDLoc DL(Op);
5721 
5722   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5723 
5724   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5725   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5726   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5727 
5728   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5729   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5730   SDValue ARMcc = DAG.getConstant(
5731       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5732   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5733   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5734                                    Cmp.getValue(1), SDValue());
5735   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5736                      CCR, Chain.getValue(1));
5737 }
5738 
5739 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5740 /// valid vector constant for a NEON instruction with a "modified immediate"
5741 /// operand (e.g., VMOV).  If so, return the encoded value.
5742 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5743                                  unsigned SplatBitSize, SelectionDAG &DAG,
5744                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5745                                  NEONModImmType type) {
5746   unsigned OpCmode, Imm;
5747 
5748   // SplatBitSize is set to the smallest size that splats the vector, so a
5749   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5750   // immediate instructions others than VMOV do not support the 8-bit encoding
5751   // of a zero vector, and the default encoding of zero is supposed to be the
5752   // 32-bit version.
5753   if (SplatBits == 0)
5754     SplatBitSize = 32;
5755 
5756   switch (SplatBitSize) {
5757   case 8:
5758     if (type != VMOVModImm)
5759       return SDValue();
5760     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5761     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5762     OpCmode = 0xe;
5763     Imm = SplatBits;
5764     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5765     break;
5766 
5767   case 16:
5768     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5769     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5770     if ((SplatBits & ~0xff) == 0) {
5771       // Value = 0x00nn: Op=x, Cmode=100x.
5772       OpCmode = 0x8;
5773       Imm = SplatBits;
5774       break;
5775     }
5776     if ((SplatBits & ~0xff00) == 0) {
5777       // Value = 0xnn00: Op=x, Cmode=101x.
5778       OpCmode = 0xa;
5779       Imm = SplatBits >> 8;
5780       break;
5781     }
5782     return SDValue();
5783 
5784   case 32:
5785     // NEON's 32-bit VMOV supports splat values where:
5786     // * only one byte is nonzero, or
5787     // * the least significant byte is 0xff and the second byte is nonzero, or
5788     // * the least significant 2 bytes are 0xff and the third is nonzero.
5789     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5790     if ((SplatBits & ~0xff) == 0) {
5791       // Value = 0x000000nn: Op=x, Cmode=000x.
5792       OpCmode = 0;
5793       Imm = SplatBits;
5794       break;
5795     }
5796     if ((SplatBits & ~0xff00) == 0) {
5797       // Value = 0x0000nn00: Op=x, Cmode=001x.
5798       OpCmode = 0x2;
5799       Imm = SplatBits >> 8;
5800       break;
5801     }
5802     if ((SplatBits & ~0xff0000) == 0) {
5803       // Value = 0x00nn0000: Op=x, Cmode=010x.
5804       OpCmode = 0x4;
5805       Imm = SplatBits >> 16;
5806       break;
5807     }
5808     if ((SplatBits & ~0xff000000) == 0) {
5809       // Value = 0xnn000000: Op=x, Cmode=011x.
5810       OpCmode = 0x6;
5811       Imm = SplatBits >> 24;
5812       break;
5813     }
5814 
5815     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5816     if (type == OtherModImm) return SDValue();
5817 
5818     if ((SplatBits & ~0xffff) == 0 &&
5819         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5820       // Value = 0x0000nnff: Op=x, Cmode=1100.
5821       OpCmode = 0xc;
5822       Imm = SplatBits >> 8;
5823       break;
5824     }
5825 
5826     if ((SplatBits & ~0xffffff) == 0 &&
5827         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5828       // Value = 0x00nnffff: Op=x, Cmode=1101.
5829       OpCmode = 0xd;
5830       Imm = SplatBits >> 16;
5831       break;
5832     }
5833 
5834     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5835     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5836     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5837     // and fall through here to test for a valid 64-bit splat.  But, then the
5838     // caller would also need to check and handle the change in size.
5839     return SDValue();
5840 
5841   case 64: {
5842     if (type != VMOVModImm)
5843       return SDValue();
5844     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5845     uint64_t BitMask = 0xff;
5846     uint64_t Val = 0;
5847     unsigned ImmMask = 1;
5848     Imm = 0;
5849     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5850       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5851         Val |= BitMask;
5852         Imm |= ImmMask;
5853       } else if ((SplatBits & BitMask) != 0) {
5854         return SDValue();
5855       }
5856       BitMask <<= 8;
5857       ImmMask <<= 1;
5858     }
5859 
5860     if (DAG.getDataLayout().isBigEndian())
5861       // swap higher and lower 32 bit word
5862       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5863 
5864     // Op=1, Cmode=1110.
5865     OpCmode = 0x1e;
5866     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5867     break;
5868   }
5869 
5870   default:
5871     llvm_unreachable("unexpected size for isNEONModifiedImm");
5872   }
5873 
5874   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5875   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5876 }
5877 
5878 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5879                                            const ARMSubtarget *ST) const {
5880   bool IsDouble = Op.getValueType() == MVT::f64;
5881   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5882   const APFloat &FPVal = CFP->getValueAPF();
5883 
5884   // Prevent floating-point constants from using literal loads
5885   // when execute-only is enabled.
5886   if (ST->genExecuteOnly()) {
5887     APInt INTVal = FPVal.bitcastToAPInt();
5888     SDLoc DL(CFP);
5889     if (IsDouble) {
5890       SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5891       SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5892       if (!ST->isLittle())
5893         std::swap(Lo, Hi);
5894       return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5895     } else {
5896       return DAG.getConstant(INTVal, DL, MVT::i32);
5897     }
5898   }
5899 
5900   if (!ST->hasVFP3())
5901     return SDValue();
5902 
5903   // Use the default (constant pool) lowering for double constants when we have
5904   // an SP-only FPU
5905   if (IsDouble && Subtarget->isFPOnlySP())
5906     return SDValue();
5907 
5908   // Try splatting with a VMOV.f32...
5909   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5910 
5911   if (ImmVal != -1) {
5912     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5913       // We have code in place to select a valid ConstantFP already, no need to
5914       // do any mangling.
5915       return Op;
5916     }
5917 
5918     // It's a float and we are trying to use NEON operations where
5919     // possible. Lower it to a splat followed by an extract.
5920     SDLoc DL(Op);
5921     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5922     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5923                                       NewVal);
5924     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5925                        DAG.getConstant(0, DL, MVT::i32));
5926   }
5927 
5928   // The rest of our options are NEON only, make sure that's allowed before
5929   // proceeding..
5930   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5931     return SDValue();
5932 
5933   EVT VMovVT;
5934   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5935 
5936   // It wouldn't really be worth bothering for doubles except for one very
5937   // important value, which does happen to match: 0.0. So make sure we don't do
5938   // anything stupid.
5939   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5940     return SDValue();
5941 
5942   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5943   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5944                                      VMovVT, false, VMOVModImm);
5945   if (NewVal != SDValue()) {
5946     SDLoc DL(Op);
5947     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5948                                       NewVal);
5949     if (IsDouble)
5950       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5951 
5952     // It's a float: cast and extract a vector element.
5953     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5954                                        VecConstant);
5955     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5956                        DAG.getConstant(0, DL, MVT::i32));
5957   }
5958 
5959   // Finally, try a VMVN.i32
5960   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5961                              false, VMVNModImm);
5962   if (NewVal != SDValue()) {
5963     SDLoc DL(Op);
5964     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5965 
5966     if (IsDouble)
5967       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5968 
5969     // It's a float: cast and extract a vector element.
5970     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5971                                        VecConstant);
5972     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5973                        DAG.getConstant(0, DL, MVT::i32));
5974   }
5975 
5976   return SDValue();
5977 }
5978 
5979 // check if an VEXT instruction can handle the shuffle mask when the
5980 // vector sources of the shuffle are the same.
5981 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5982   unsigned NumElts = VT.getVectorNumElements();
5983 
5984   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5985   if (M[0] < 0)
5986     return false;
5987 
5988   Imm = M[0];
5989 
5990   // If this is a VEXT shuffle, the immediate value is the index of the first
5991   // element.  The other shuffle indices must be the successive elements after
5992   // the first one.
5993   unsigned ExpectedElt = Imm;
5994   for (unsigned i = 1; i < NumElts; ++i) {
5995     // Increment the expected index.  If it wraps around, just follow it
5996     // back to index zero and keep going.
5997     ++ExpectedElt;
5998     if (ExpectedElt == NumElts)
5999       ExpectedElt = 0;
6000 
6001     if (M[i] < 0) continue; // ignore UNDEF indices
6002     if (ExpectedElt != static_cast<unsigned>(M[i]))
6003       return false;
6004   }
6005 
6006   return true;
6007 }
6008 
6009 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6010                        bool &ReverseVEXT, unsigned &Imm) {
6011   unsigned NumElts = VT.getVectorNumElements();
6012   ReverseVEXT = false;
6013 
6014   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6015   if (M[0] < 0)
6016     return false;
6017 
6018   Imm = M[0];
6019 
6020   // If this is a VEXT shuffle, the immediate value is the index of the first
6021   // element.  The other shuffle indices must be the successive elements after
6022   // the first one.
6023   unsigned ExpectedElt = Imm;
6024   for (unsigned i = 1; i < NumElts; ++i) {
6025     // Increment the expected index.  If it wraps around, it may still be
6026     // a VEXT but the source vectors must be swapped.
6027     ExpectedElt += 1;
6028     if (ExpectedElt == NumElts * 2) {
6029       ExpectedElt = 0;
6030       ReverseVEXT = true;
6031     }
6032 
6033     if (M[i] < 0) continue; // ignore UNDEF indices
6034     if (ExpectedElt != static_cast<unsigned>(M[i]))
6035       return false;
6036   }
6037 
6038   // Adjust the index value if the source operands will be swapped.
6039   if (ReverseVEXT)
6040     Imm -= NumElts;
6041 
6042   return true;
6043 }
6044 
6045 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6046 /// instruction with the specified blocksize.  (The order of the elements
6047 /// within each block of the vector is reversed.)
6048 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6049   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6050          "Only possible block sizes for VREV are: 16, 32, 64");
6051 
6052   unsigned EltSz = VT.getScalarSizeInBits();
6053   if (EltSz == 64)
6054     return false;
6055 
6056   unsigned NumElts = VT.getVectorNumElements();
6057   unsigned BlockElts = M[0] + 1;
6058   // If the first shuffle index is UNDEF, be optimistic.
6059   if (M[0] < 0)
6060     BlockElts = BlockSize / EltSz;
6061 
6062   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6063     return false;
6064 
6065   for (unsigned i = 0; i < NumElts; ++i) {
6066     if (M[i] < 0) continue; // ignore UNDEF indices
6067     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6068       return false;
6069   }
6070 
6071   return true;
6072 }
6073 
6074 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6075   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6076   // range, then 0 is placed into the resulting vector. So pretty much any mask
6077   // of 8 elements can work here.
6078   return VT == MVT::v8i8 && M.size() == 8;
6079 }
6080 
6081 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6082                                unsigned Index) {
6083   if (Mask.size() == Elements * 2)
6084     return Index / Elements;
6085   return Mask[Index] == 0 ? 0 : 1;
6086 }
6087 
6088 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6089 // checking that pairs of elements in the shuffle mask represent the same index
6090 // in each vector, incrementing the expected index by 2 at each step.
6091 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6092 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6093 //  v2={e,f,g,h}
6094 // WhichResult gives the offset for each element in the mask based on which
6095 // of the two results it belongs to.
6096 //
6097 // The transpose can be represented either as:
6098 // result1 = shufflevector v1, v2, result1_shuffle_mask
6099 // result2 = shufflevector v1, v2, result2_shuffle_mask
6100 // where v1/v2 and the shuffle masks have the same number of elements
6101 // (here WhichResult (see below) indicates which result is being checked)
6102 //
6103 // or as:
6104 // results = shufflevector v1, v2, shuffle_mask
6105 // where both results are returned in one vector and the shuffle mask has twice
6106 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6107 // want to check the low half and high half of the shuffle mask as if it were
6108 // the other case
6109 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6110   unsigned EltSz = VT.getScalarSizeInBits();
6111   if (EltSz == 64)
6112     return false;
6113 
6114   unsigned NumElts = VT.getVectorNumElements();
6115   if (M.size() != NumElts && M.size() != NumElts*2)
6116     return false;
6117 
6118   // If the mask is twice as long as the input vector then we need to check the
6119   // upper and lower parts of the mask with a matching value for WhichResult
6120   // FIXME: A mask with only even values will be rejected in case the first
6121   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6122   // M[0] is used to determine WhichResult
6123   for (unsigned i = 0; i < M.size(); i += NumElts) {
6124     WhichResult = SelectPairHalf(NumElts, M, i);
6125     for (unsigned j = 0; j < NumElts; j += 2) {
6126       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6127           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6128         return false;
6129     }
6130   }
6131 
6132   if (M.size() == NumElts*2)
6133     WhichResult = 0;
6134 
6135   return true;
6136 }
6137 
6138 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6139 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6140 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6141 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6142   unsigned EltSz = VT.getScalarSizeInBits();
6143   if (EltSz == 64)
6144     return false;
6145 
6146   unsigned NumElts = VT.getVectorNumElements();
6147   if (M.size() != NumElts && M.size() != NumElts*2)
6148     return false;
6149 
6150   for (unsigned i = 0; i < M.size(); i += NumElts) {
6151     WhichResult = SelectPairHalf(NumElts, M, i);
6152     for (unsigned j = 0; j < NumElts; j += 2) {
6153       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6154           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6155         return false;
6156     }
6157   }
6158 
6159   if (M.size() == NumElts*2)
6160     WhichResult = 0;
6161 
6162   return true;
6163 }
6164 
6165 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6166 // that the mask elements are either all even and in steps of size 2 or all odd
6167 // and in steps of size 2.
6168 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6169 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6170 //  v2={e,f,g,h}
6171 // Requires similar checks to that of isVTRNMask with
6172 // respect the how results are returned.
6173 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6174   unsigned EltSz = VT.getScalarSizeInBits();
6175   if (EltSz == 64)
6176     return false;
6177 
6178   unsigned NumElts = VT.getVectorNumElements();
6179   if (M.size() != NumElts && M.size() != NumElts*2)
6180     return false;
6181 
6182   for (unsigned i = 0; i < M.size(); i += NumElts) {
6183     WhichResult = SelectPairHalf(NumElts, M, i);
6184     for (unsigned j = 0; j < NumElts; ++j) {
6185       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6186         return false;
6187     }
6188   }
6189 
6190   if (M.size() == NumElts*2)
6191     WhichResult = 0;
6192 
6193   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6194   if (VT.is64BitVector() && EltSz == 32)
6195     return false;
6196 
6197   return true;
6198 }
6199 
6200 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6201 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6202 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6203 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6204   unsigned EltSz = VT.getScalarSizeInBits();
6205   if (EltSz == 64)
6206     return false;
6207 
6208   unsigned NumElts = VT.getVectorNumElements();
6209   if (M.size() != NumElts && M.size() != NumElts*2)
6210     return false;
6211 
6212   unsigned Half = NumElts / 2;
6213   for (unsigned i = 0; i < M.size(); i += NumElts) {
6214     WhichResult = SelectPairHalf(NumElts, M, i);
6215     for (unsigned j = 0; j < NumElts; j += Half) {
6216       unsigned Idx = WhichResult;
6217       for (unsigned k = 0; k < Half; ++k) {
6218         int MIdx = M[i + j + k];
6219         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6220           return false;
6221         Idx += 2;
6222       }
6223     }
6224   }
6225 
6226   if (M.size() == NumElts*2)
6227     WhichResult = 0;
6228 
6229   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6230   if (VT.is64BitVector() && EltSz == 32)
6231     return false;
6232 
6233   return true;
6234 }
6235 
6236 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6237 // that pairs of elements of the shufflemask represent the same index in each
6238 // vector incrementing sequentially through the vectors.
6239 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6240 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6241 //  v2={e,f,g,h}
6242 // Requires similar checks to that of isVTRNMask with respect the how results
6243 // are returned.
6244 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6245   unsigned EltSz = VT.getScalarSizeInBits();
6246   if (EltSz == 64)
6247     return false;
6248 
6249   unsigned NumElts = VT.getVectorNumElements();
6250   if (M.size() != NumElts && M.size() != NumElts*2)
6251     return false;
6252 
6253   for (unsigned i = 0; i < M.size(); i += NumElts) {
6254     WhichResult = SelectPairHalf(NumElts, M, i);
6255     unsigned Idx = WhichResult * NumElts / 2;
6256     for (unsigned j = 0; j < NumElts; j += 2) {
6257       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6258           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6259         return false;
6260       Idx += 1;
6261     }
6262   }
6263 
6264   if (M.size() == NumElts*2)
6265     WhichResult = 0;
6266 
6267   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6268   if (VT.is64BitVector() && EltSz == 32)
6269     return false;
6270 
6271   return true;
6272 }
6273 
6274 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6275 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6276 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6277 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6278   unsigned EltSz = VT.getScalarSizeInBits();
6279   if (EltSz == 64)
6280     return false;
6281 
6282   unsigned NumElts = VT.getVectorNumElements();
6283   if (M.size() != NumElts && M.size() != NumElts*2)
6284     return false;
6285 
6286   for (unsigned i = 0; i < M.size(); i += NumElts) {
6287     WhichResult = SelectPairHalf(NumElts, M, i);
6288     unsigned Idx = WhichResult * NumElts / 2;
6289     for (unsigned j = 0; j < NumElts; j += 2) {
6290       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6291           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6292         return false;
6293       Idx += 1;
6294     }
6295   }
6296 
6297   if (M.size() == NumElts*2)
6298     WhichResult = 0;
6299 
6300   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6301   if (VT.is64BitVector() && EltSz == 32)
6302     return false;
6303 
6304   return true;
6305 }
6306 
6307 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6308 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6309 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6310                                            unsigned &WhichResult,
6311                                            bool &isV_UNDEF) {
6312   isV_UNDEF = false;
6313   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6314     return ARMISD::VTRN;
6315   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6316     return ARMISD::VUZP;
6317   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6318     return ARMISD::VZIP;
6319 
6320   isV_UNDEF = true;
6321   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6322     return ARMISD::VTRN;
6323   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6324     return ARMISD::VUZP;
6325   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6326     return ARMISD::VZIP;
6327 
6328   return 0;
6329 }
6330 
6331 /// \return true if this is a reverse operation on an vector.
6332 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6333   unsigned NumElts = VT.getVectorNumElements();
6334   // Make sure the mask has the right size.
6335   if (NumElts != M.size())
6336       return false;
6337 
6338   // Look for <15, ..., 3, -1, 1, 0>.
6339   for (unsigned i = 0; i != NumElts; ++i)
6340     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6341       return false;
6342 
6343   return true;
6344 }
6345 
6346 // If N is an integer constant that can be moved into a register in one
6347 // instruction, return an SDValue of such a constant (will become a MOV
6348 // instruction).  Otherwise return null.
6349 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6350                                      const ARMSubtarget *ST, const SDLoc &dl) {
6351   uint64_t Val;
6352   if (!isa<ConstantSDNode>(N))
6353     return SDValue();
6354   Val = cast<ConstantSDNode>(N)->getZExtValue();
6355 
6356   if (ST->isThumb1Only()) {
6357     if (Val <= 255 || ~Val <= 255)
6358       return DAG.getConstant(Val, dl, MVT::i32);
6359   } else {
6360     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6361       return DAG.getConstant(Val, dl, MVT::i32);
6362   }
6363   return SDValue();
6364 }
6365 
6366 // If this is a case we can't handle, return null and let the default
6367 // expansion code take care of it.
6368 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6369                                              const ARMSubtarget *ST) const {
6370   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6371   SDLoc dl(Op);
6372   EVT VT = Op.getValueType();
6373 
6374   APInt SplatBits, SplatUndef;
6375   unsigned SplatBitSize;
6376   bool HasAnyUndefs;
6377   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6378     if (SplatUndef.isAllOnesValue())
6379       return DAG.getUNDEF(VT);
6380 
6381     if (SplatBitSize <= 64) {
6382       // Check if an immediate VMOV works.
6383       EVT VmovVT;
6384       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6385                                       SplatUndef.getZExtValue(), SplatBitSize,
6386                                       DAG, dl, VmovVT, VT.is128BitVector(),
6387                                       VMOVModImm);
6388       if (Val.getNode()) {
6389         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6390         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6391       }
6392 
6393       // Try an immediate VMVN.
6394       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6395       Val = isNEONModifiedImm(NegatedImm,
6396                                       SplatUndef.getZExtValue(), SplatBitSize,
6397                                       DAG, dl, VmovVT, VT.is128BitVector(),
6398                                       VMVNModImm);
6399       if (Val.getNode()) {
6400         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6401         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6402       }
6403 
6404       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6405       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6406         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6407         if (ImmVal != -1) {
6408           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6409           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6410         }
6411       }
6412     }
6413   }
6414 
6415   // Scan through the operands to see if only one value is used.
6416   //
6417   // As an optimisation, even if more than one value is used it may be more
6418   // profitable to splat with one value then change some lanes.
6419   //
6420   // Heuristically we decide to do this if the vector has a "dominant" value,
6421   // defined as splatted to more than half of the lanes.
6422   unsigned NumElts = VT.getVectorNumElements();
6423   bool isOnlyLowElement = true;
6424   bool usesOnlyOneValue = true;
6425   bool hasDominantValue = false;
6426   bool isConstant = true;
6427 
6428   // Map of the number of times a particular SDValue appears in the
6429   // element list.
6430   DenseMap<SDValue, unsigned> ValueCounts;
6431   SDValue Value;
6432   for (unsigned i = 0; i < NumElts; ++i) {
6433     SDValue V = Op.getOperand(i);
6434     if (V.isUndef())
6435       continue;
6436     if (i > 0)
6437       isOnlyLowElement = false;
6438     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6439       isConstant = false;
6440 
6441     ValueCounts.insert(std::make_pair(V, 0));
6442     unsigned &Count = ValueCounts[V];
6443 
6444     // Is this value dominant? (takes up more than half of the lanes)
6445     if (++Count > (NumElts / 2)) {
6446       hasDominantValue = true;
6447       Value = V;
6448     }
6449   }
6450   if (ValueCounts.size() != 1)
6451     usesOnlyOneValue = false;
6452   if (!Value.getNode() && !ValueCounts.empty())
6453     Value = ValueCounts.begin()->first;
6454 
6455   if (ValueCounts.empty())
6456     return DAG.getUNDEF(VT);
6457 
6458   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6459   // Keep going if we are hitting this case.
6460   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6461     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6462 
6463   unsigned EltSize = VT.getScalarSizeInBits();
6464 
6465   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6466   // i32 and try again.
6467   if (hasDominantValue && EltSize <= 32) {
6468     if (!isConstant) {
6469       SDValue N;
6470 
6471       // If we are VDUPing a value that comes directly from a vector, that will
6472       // cause an unnecessary move to and from a GPR, where instead we could
6473       // just use VDUPLANE. We can only do this if the lane being extracted
6474       // is at a constant index, as the VDUP from lane instructions only have
6475       // constant-index forms.
6476       ConstantSDNode *constIndex;
6477       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6478           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6479         // We need to create a new undef vector to use for the VDUPLANE if the
6480         // size of the vector from which we get the value is different than the
6481         // size of the vector that we need to create. We will insert the element
6482         // such that the register coalescer will remove unnecessary copies.
6483         if (VT != Value->getOperand(0).getValueType()) {
6484           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6485                              VT.getVectorNumElements();
6486           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6487                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6488                         Value, DAG.getConstant(index, dl, MVT::i32)),
6489                            DAG.getConstant(index, dl, MVT::i32));
6490         } else
6491           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6492                         Value->getOperand(0), Value->getOperand(1));
6493       } else
6494         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6495 
6496       if (!usesOnlyOneValue) {
6497         // The dominant value was splatted as 'N', but we now have to insert
6498         // all differing elements.
6499         for (unsigned I = 0; I < NumElts; ++I) {
6500           if (Op.getOperand(I) == Value)
6501             continue;
6502           SmallVector<SDValue, 3> Ops;
6503           Ops.push_back(N);
6504           Ops.push_back(Op.getOperand(I));
6505           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6506           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6507         }
6508       }
6509       return N;
6510     }
6511     if (VT.getVectorElementType().isFloatingPoint()) {
6512       SmallVector<SDValue, 8> Ops;
6513       for (unsigned i = 0; i < NumElts; ++i)
6514         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6515                                   Op.getOperand(i)));
6516       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6517       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6518       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6519       if (Val.getNode())
6520         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6521     }
6522     if (usesOnlyOneValue) {
6523       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6524       if (isConstant && Val.getNode())
6525         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6526     }
6527   }
6528 
6529   // If all elements are constants and the case above didn't get hit, fall back
6530   // to the default expansion, which will generate a load from the constant
6531   // pool.
6532   if (isConstant)
6533     return SDValue();
6534 
6535   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6536   if (NumElts >= 4) {
6537     SDValue shuffle = ReconstructShuffle(Op, DAG);
6538     if (shuffle != SDValue())
6539       return shuffle;
6540   }
6541 
6542   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6543     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6544     // into two 64-bit vectors; we might discover a better way to lower it.
6545     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6546     EVT ExtVT = VT.getVectorElementType();
6547     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6548     SDValue Lower =
6549         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6550     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6551       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6552     SDValue Upper = DAG.getBuildVector(
6553         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6554     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6555       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6556     if (Lower && Upper)
6557       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6558   }
6559 
6560   // Vectors with 32- or 64-bit elements can be built by directly assigning
6561   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6562   // will be legalized.
6563   if (EltSize >= 32) {
6564     // Do the expansion with floating-point types, since that is what the VFP
6565     // registers are defined to use, and since i64 is not legal.
6566     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6567     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6568     SmallVector<SDValue, 8> Ops;
6569     for (unsigned i = 0; i < NumElts; ++i)
6570       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6571     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6572     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6573   }
6574 
6575   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6576   // know the default expansion would otherwise fall back on something even
6577   // worse. For a vector with one or two non-undef values, that's
6578   // scalar_to_vector for the elements followed by a shuffle (provided the
6579   // shuffle is valid for the target) and materialization element by element
6580   // on the stack followed by a load for everything else.
6581   if (!isConstant && !usesOnlyOneValue) {
6582     SDValue Vec = DAG.getUNDEF(VT);
6583     for (unsigned i = 0 ; i < NumElts; ++i) {
6584       SDValue V = Op.getOperand(i);
6585       if (V.isUndef())
6586         continue;
6587       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6588       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6589     }
6590     return Vec;
6591   }
6592 
6593   return SDValue();
6594 }
6595 
6596 // Gather data to see if the operation can be modelled as a
6597 // shuffle in combination with VEXTs.
6598 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6599                                               SelectionDAG &DAG) const {
6600   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6601   SDLoc dl(Op);
6602   EVT VT = Op.getValueType();
6603   unsigned NumElts = VT.getVectorNumElements();
6604 
6605   struct ShuffleSourceInfo {
6606     SDValue Vec;
6607     unsigned MinElt = std::numeric_limits<unsigned>::max();
6608     unsigned MaxElt = 0;
6609 
6610     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6611     // be compatible with the shuffle we intend to construct. As a result
6612     // ShuffleVec will be some sliding window into the original Vec.
6613     SDValue ShuffleVec;
6614 
6615     // Code should guarantee that element i in Vec starts at element "WindowBase
6616     // + i * WindowScale in ShuffleVec".
6617     int WindowBase = 0;
6618     int WindowScale = 1;
6619 
6620     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6621 
6622     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6623   };
6624 
6625   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6626   // node.
6627   SmallVector<ShuffleSourceInfo, 2> Sources;
6628   for (unsigned i = 0; i < NumElts; ++i) {
6629     SDValue V = Op.getOperand(i);
6630     if (V.isUndef())
6631       continue;
6632     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6633       // A shuffle can only come from building a vector from various
6634       // elements of other vectors.
6635       return SDValue();
6636     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6637       // Furthermore, shuffles require a constant mask, whereas extractelts
6638       // accept variable indices.
6639       return SDValue();
6640     }
6641 
6642     // Add this element source to the list if it's not already there.
6643     SDValue SourceVec = V.getOperand(0);
6644     auto Source = llvm::find(Sources, SourceVec);
6645     if (Source == Sources.end())
6646       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6647 
6648     // Update the minimum and maximum lane number seen.
6649     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6650     Source->MinElt = std::min(Source->MinElt, EltNo);
6651     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6652   }
6653 
6654   // Currently only do something sane when at most two source vectors
6655   // are involved.
6656   if (Sources.size() > 2)
6657     return SDValue();
6658 
6659   // Find out the smallest element size among result and two sources, and use
6660   // it as element size to build the shuffle_vector.
6661   EVT SmallestEltTy = VT.getVectorElementType();
6662   for (auto &Source : Sources) {
6663     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6664     if (SrcEltTy.bitsLT(SmallestEltTy))
6665       SmallestEltTy = SrcEltTy;
6666   }
6667   unsigned ResMultiplier =
6668       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6669   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6670   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6671 
6672   // If the source vector is too wide or too narrow, we may nevertheless be able
6673   // to construct a compatible shuffle either by concatenating it with UNDEF or
6674   // extracting a suitable range of elements.
6675   for (auto &Src : Sources) {
6676     EVT SrcVT = Src.ShuffleVec.getValueType();
6677 
6678     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6679       continue;
6680 
6681     // This stage of the search produces a source with the same element type as
6682     // the original, but with a total width matching the BUILD_VECTOR output.
6683     EVT EltVT = SrcVT.getVectorElementType();
6684     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6685     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6686 
6687     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6688       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6689         return SDValue();
6690       // We can pad out the smaller vector for free, so if it's part of a
6691       // shuffle...
6692       Src.ShuffleVec =
6693           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6694                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6695       continue;
6696     }
6697 
6698     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6699       return SDValue();
6700 
6701     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6702       // Span too large for a VEXT to cope
6703       return SDValue();
6704     }
6705 
6706     if (Src.MinElt >= NumSrcElts) {
6707       // The extraction can just take the second half
6708       Src.ShuffleVec =
6709           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6710                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6711       Src.WindowBase = -NumSrcElts;
6712     } else if (Src.MaxElt < NumSrcElts) {
6713       // The extraction can just take the first half
6714       Src.ShuffleVec =
6715           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6716                       DAG.getConstant(0, dl, MVT::i32));
6717     } else {
6718       // An actual VEXT is needed
6719       SDValue VEXTSrc1 =
6720           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6721                       DAG.getConstant(0, dl, MVT::i32));
6722       SDValue VEXTSrc2 =
6723           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6724                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6725 
6726       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6727                                    VEXTSrc2,
6728                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6729       Src.WindowBase = -Src.MinElt;
6730     }
6731   }
6732 
6733   // Another possible incompatibility occurs from the vector element types. We
6734   // can fix this by bitcasting the source vectors to the same type we intend
6735   // for the shuffle.
6736   for (auto &Src : Sources) {
6737     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6738     if (SrcEltTy == SmallestEltTy)
6739       continue;
6740     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6741     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6742     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6743     Src.WindowBase *= Src.WindowScale;
6744   }
6745 
6746   // Final sanity check before we try to actually produce a shuffle.
6747   DEBUG(
6748     for (auto Src : Sources)
6749       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6750   );
6751 
6752   // The stars all align, our next step is to produce the mask for the shuffle.
6753   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6754   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6755   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6756     SDValue Entry = Op.getOperand(i);
6757     if (Entry.isUndef())
6758       continue;
6759 
6760     auto Src = llvm::find(Sources, Entry.getOperand(0));
6761     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6762 
6763     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6764     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6765     // segment.
6766     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6767     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6768                                VT.getScalarSizeInBits());
6769     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6770 
6771     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6772     // starting at the appropriate offset.
6773     int *LaneMask = &Mask[i * ResMultiplier];
6774 
6775     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6776     ExtractBase += NumElts * (Src - Sources.begin());
6777     for (int j = 0; j < LanesDefined; ++j)
6778       LaneMask[j] = ExtractBase + j;
6779   }
6780 
6781   // Final check before we try to produce nonsense...
6782   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6783     return SDValue();
6784 
6785   // We can't handle more than two sources. This should have already
6786   // been checked before this point.
6787   assert(Sources.size() <= 2 && "Too many sources!");
6788 
6789   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6790   for (unsigned i = 0; i < Sources.size(); ++i)
6791     ShuffleOps[i] = Sources[i].ShuffleVec;
6792 
6793   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6794                                          ShuffleOps[1], Mask);
6795   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6796 }
6797 
6798 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6799 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6800 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6801 /// are assumed to be legal.
6802 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
6803   if (VT.getVectorNumElements() == 4 &&
6804       (VT.is128BitVector() || VT.is64BitVector())) {
6805     unsigned PFIndexes[4];
6806     for (unsigned i = 0; i != 4; ++i) {
6807       if (M[i] < 0)
6808         PFIndexes[i] = 8;
6809       else
6810         PFIndexes[i] = M[i];
6811     }
6812 
6813     // Compute the index in the perfect shuffle table.
6814     unsigned PFTableIndex =
6815       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6816     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6817     unsigned Cost = (PFEntry >> 30);
6818 
6819     if (Cost <= 4)
6820       return true;
6821   }
6822 
6823   bool ReverseVEXT, isV_UNDEF;
6824   unsigned Imm, WhichResult;
6825 
6826   unsigned EltSize = VT.getScalarSizeInBits();
6827   return (EltSize >= 32 ||
6828           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6829           isVREVMask(M, VT, 64) ||
6830           isVREVMask(M, VT, 32) ||
6831           isVREVMask(M, VT, 16) ||
6832           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6833           isVTBLMask(M, VT) ||
6834           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6835           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6836 }
6837 
6838 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6839 /// the specified operations to build the shuffle.
6840 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6841                                       SDValue RHS, SelectionDAG &DAG,
6842                                       const SDLoc &dl) {
6843   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6844   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6845   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6846 
6847   enum {
6848     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6849     OP_VREV,
6850     OP_VDUP0,
6851     OP_VDUP1,
6852     OP_VDUP2,
6853     OP_VDUP3,
6854     OP_VEXT1,
6855     OP_VEXT2,
6856     OP_VEXT3,
6857     OP_VUZPL, // VUZP, left result
6858     OP_VUZPR, // VUZP, right result
6859     OP_VZIPL, // VZIP, left result
6860     OP_VZIPR, // VZIP, right result
6861     OP_VTRNL, // VTRN, left result
6862     OP_VTRNR  // VTRN, right result
6863   };
6864 
6865   if (OpNum == OP_COPY) {
6866     if (LHSID == (1*9+2)*9+3) return LHS;
6867     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6868     return RHS;
6869   }
6870 
6871   SDValue OpLHS, OpRHS;
6872   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6873   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6874   EVT VT = OpLHS.getValueType();
6875 
6876   switch (OpNum) {
6877   default: llvm_unreachable("Unknown shuffle opcode!");
6878   case OP_VREV:
6879     // VREV divides the vector in half and swaps within the half.
6880     if (VT.getVectorElementType() == MVT::i32 ||
6881         VT.getVectorElementType() == MVT::f32)
6882       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6883     // vrev <4 x i16> -> VREV32
6884     if (VT.getVectorElementType() == MVT::i16)
6885       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6886     // vrev <4 x i8> -> VREV16
6887     assert(VT.getVectorElementType() == MVT::i8);
6888     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6889   case OP_VDUP0:
6890   case OP_VDUP1:
6891   case OP_VDUP2:
6892   case OP_VDUP3:
6893     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6894                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6895   case OP_VEXT1:
6896   case OP_VEXT2:
6897   case OP_VEXT3:
6898     return DAG.getNode(ARMISD::VEXT, dl, VT,
6899                        OpLHS, OpRHS,
6900                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6901   case OP_VUZPL:
6902   case OP_VUZPR:
6903     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6904                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6905   case OP_VZIPL:
6906   case OP_VZIPR:
6907     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6908                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6909   case OP_VTRNL:
6910   case OP_VTRNR:
6911     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6912                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6913   }
6914 }
6915 
6916 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6917                                        ArrayRef<int> ShuffleMask,
6918                                        SelectionDAG &DAG) {
6919   // Check to see if we can use the VTBL instruction.
6920   SDValue V1 = Op.getOperand(0);
6921   SDValue V2 = Op.getOperand(1);
6922   SDLoc DL(Op);
6923 
6924   SmallVector<SDValue, 8> VTBLMask;
6925   for (ArrayRef<int>::iterator
6926          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6927     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6928 
6929   if (V2.getNode()->isUndef())
6930     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6931                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6932 
6933   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6934                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6935 }
6936 
6937 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6938                                                       SelectionDAG &DAG) {
6939   SDLoc DL(Op);
6940   SDValue OpLHS = Op.getOperand(0);
6941   EVT VT = OpLHS.getValueType();
6942 
6943   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6944          "Expect an v8i16/v16i8 type");
6945   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6946   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6947   // extract the first 8 bytes into the top double word and the last 8 bytes
6948   // into the bottom double word. The v8i16 case is similar.
6949   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6950   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6951                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6952 }
6953 
6954 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6955   SDValue V1 = Op.getOperand(0);
6956   SDValue V2 = Op.getOperand(1);
6957   SDLoc dl(Op);
6958   EVT VT = Op.getValueType();
6959   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6960 
6961   // Convert shuffles that are directly supported on NEON to target-specific
6962   // DAG nodes, instead of keeping them as shuffles and matching them again
6963   // during code selection.  This is more efficient and avoids the possibility
6964   // of inconsistencies between legalization and selection.
6965   // FIXME: floating-point vectors should be canonicalized to integer vectors
6966   // of the same time so that they get CSEd properly.
6967   ArrayRef<int> ShuffleMask = SVN->getMask();
6968 
6969   unsigned EltSize = VT.getScalarSizeInBits();
6970   if (EltSize <= 32) {
6971     if (SVN->isSplat()) {
6972       int Lane = SVN->getSplatIndex();
6973       // If this is undef splat, generate it via "just" vdup, if possible.
6974       if (Lane == -1) Lane = 0;
6975 
6976       // Test if V1 is a SCALAR_TO_VECTOR.
6977       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6978         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6979       }
6980       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6981       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6982       // reaches it).
6983       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6984           !isa<ConstantSDNode>(V1.getOperand(0))) {
6985         bool IsScalarToVector = true;
6986         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6987           if (!V1.getOperand(i).isUndef()) {
6988             IsScalarToVector = false;
6989             break;
6990           }
6991         if (IsScalarToVector)
6992           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6993       }
6994       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6995                          DAG.getConstant(Lane, dl, MVT::i32));
6996     }
6997 
6998     bool ReverseVEXT;
6999     unsigned Imm;
7000     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7001       if (ReverseVEXT)
7002         std::swap(V1, V2);
7003       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7004                          DAG.getConstant(Imm, dl, MVT::i32));
7005     }
7006 
7007     if (isVREVMask(ShuffleMask, VT, 64))
7008       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7009     if (isVREVMask(ShuffleMask, VT, 32))
7010       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7011     if (isVREVMask(ShuffleMask, VT, 16))
7012       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7013 
7014     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7015       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7016                          DAG.getConstant(Imm, dl, MVT::i32));
7017     }
7018 
7019     // Check for Neon shuffles that modify both input vectors in place.
7020     // If both results are used, i.e., if there are two shuffles with the same
7021     // source operands and with masks corresponding to both results of one of
7022     // these operations, DAG memoization will ensure that a single node is
7023     // used for both shuffles.
7024     unsigned WhichResult;
7025     bool isV_UNDEF;
7026     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7027             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7028       if (isV_UNDEF)
7029         V2 = V1;
7030       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7031           .getValue(WhichResult);
7032     }
7033 
7034     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7035     // shuffles that produce a result larger than their operands with:
7036     //   shuffle(concat(v1, undef), concat(v2, undef))
7037     // ->
7038     //   shuffle(concat(v1, v2), undef)
7039     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7040     //
7041     // This is useful in the general case, but there are special cases where
7042     // native shuffles produce larger results: the two-result ops.
7043     //
7044     // Look through the concat when lowering them:
7045     //   shuffle(concat(v1, v2), undef)
7046     // ->
7047     //   concat(VZIP(v1, v2):0, :1)
7048     //
7049     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7050       SDValue SubV1 = V1->getOperand(0);
7051       SDValue SubV2 = V1->getOperand(1);
7052       EVT SubVT = SubV1.getValueType();
7053 
7054       // We expect these to have been canonicalized to -1.
7055       assert(llvm::all_of(ShuffleMask, [&](int i) {
7056         return i < (int)VT.getVectorNumElements();
7057       }) && "Unexpected shuffle index into UNDEF operand!");
7058 
7059       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7060               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7061         if (isV_UNDEF)
7062           SubV2 = SubV1;
7063         assert((WhichResult == 0) &&
7064                "In-place shuffle of concat can only have one result!");
7065         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7066                                   SubV1, SubV2);
7067         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7068                            Res.getValue(1));
7069       }
7070     }
7071   }
7072 
7073   // If the shuffle is not directly supported and it has 4 elements, use
7074   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7075   unsigned NumElts = VT.getVectorNumElements();
7076   if (NumElts == 4) {
7077     unsigned PFIndexes[4];
7078     for (unsigned i = 0; i != 4; ++i) {
7079       if (ShuffleMask[i] < 0)
7080         PFIndexes[i] = 8;
7081       else
7082         PFIndexes[i] = ShuffleMask[i];
7083     }
7084 
7085     // Compute the index in the perfect shuffle table.
7086     unsigned PFTableIndex =
7087       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7088     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7089     unsigned Cost = (PFEntry >> 30);
7090 
7091     if (Cost <= 4)
7092       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7093   }
7094 
7095   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7096   if (EltSize >= 32) {
7097     // Do the expansion with floating-point types, since that is what the VFP
7098     // registers are defined to use, and since i64 is not legal.
7099     EVT EltVT = EVT::getFloatingPointVT(EltSize);
7100     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7101     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7102     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7103     SmallVector<SDValue, 8> Ops;
7104     for (unsigned i = 0; i < NumElts; ++i) {
7105       if (ShuffleMask[i] < 0)
7106         Ops.push_back(DAG.getUNDEF(EltVT));
7107       else
7108         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7109                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
7110                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7111                                                   dl, MVT::i32)));
7112     }
7113     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7114     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7115   }
7116 
7117   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7118     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7119 
7120   if (VT == MVT::v8i8)
7121     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7122       return NewOp;
7123 
7124   return SDValue();
7125 }
7126 
7127 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7128   // INSERT_VECTOR_ELT is legal only for immediate indexes.
7129   SDValue Lane = Op.getOperand(2);
7130   if (!isa<ConstantSDNode>(Lane))
7131     return SDValue();
7132 
7133   return Op;
7134 }
7135 
7136 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7137   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7138   SDValue Lane = Op.getOperand(1);
7139   if (!isa<ConstantSDNode>(Lane))
7140     return SDValue();
7141 
7142   SDValue Vec = Op.getOperand(0);
7143   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7144     SDLoc dl(Op);
7145     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7146   }
7147 
7148   return Op;
7149 }
7150 
7151 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7152   // The only time a CONCAT_VECTORS operation can have legal types is when
7153   // two 64-bit vectors are concatenated to a 128-bit vector.
7154   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
7155          "unexpected CONCAT_VECTORS");
7156   SDLoc dl(Op);
7157   SDValue Val = DAG.getUNDEF(MVT::v2f64);
7158   SDValue Op0 = Op.getOperand(0);
7159   SDValue Op1 = Op.getOperand(1);
7160   if (!Op0.isUndef())
7161     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7162                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
7163                       DAG.getIntPtrConstant(0, dl));
7164   if (!Op1.isUndef())
7165     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7166                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
7167                       DAG.getIntPtrConstant(1, dl));
7168   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
7169 }
7170 
7171 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
7172 /// element has been zero/sign-extended, depending on the isSigned parameter,
7173 /// from an integer type half its size.
7174 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
7175                                    bool isSigned) {
7176   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
7177   EVT VT = N->getValueType(0);
7178   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
7179     SDNode *BVN = N->getOperand(0).getNode();
7180     if (BVN->getValueType(0) != MVT::v4i32 ||
7181         BVN->getOpcode() != ISD::BUILD_VECTOR)
7182       return false;
7183     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7184     unsigned HiElt = 1 - LoElt;
7185     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
7186     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
7187     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
7188     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
7189     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
7190       return false;
7191     if (isSigned) {
7192       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
7193           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
7194         return true;
7195     } else {
7196       if (Hi0->isNullValue() && Hi1->isNullValue())
7197         return true;
7198     }
7199     return false;
7200   }
7201 
7202   if (N->getOpcode() != ISD::BUILD_VECTOR)
7203     return false;
7204 
7205   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
7206     SDNode *Elt = N->getOperand(i).getNode();
7207     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
7208       unsigned EltSize = VT.getScalarSizeInBits();
7209       unsigned HalfSize = EltSize / 2;
7210       if (isSigned) {
7211         if (!isIntN(HalfSize, C->getSExtValue()))
7212           return false;
7213       } else {
7214         if (!isUIntN(HalfSize, C->getZExtValue()))
7215           return false;
7216       }
7217       continue;
7218     }
7219     return false;
7220   }
7221 
7222   return true;
7223 }
7224 
7225 /// isSignExtended - Check if a node is a vector value that is sign-extended
7226 /// or a constant BUILD_VECTOR with sign-extended elements.
7227 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7228   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7229     return true;
7230   if (isExtendedBUILD_VECTOR(N, DAG, true))
7231     return true;
7232   return false;
7233 }
7234 
7235 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7236 /// or a constant BUILD_VECTOR with zero-extended elements.
7237 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7238   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7239     return true;
7240   if (isExtendedBUILD_VECTOR(N, DAG, false))
7241     return true;
7242   return false;
7243 }
7244 
7245 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7246   if (OrigVT.getSizeInBits() >= 64)
7247     return OrigVT;
7248 
7249   assert(OrigVT.isSimple() && "Expecting a simple value type");
7250 
7251   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7252   switch (OrigSimpleTy) {
7253   default: llvm_unreachable("Unexpected Vector Type");
7254   case MVT::v2i8:
7255   case MVT::v2i16:
7256      return MVT::v2i32;
7257   case MVT::v4i8:
7258     return  MVT::v4i16;
7259   }
7260 }
7261 
7262 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7263 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7264 /// We insert the required extension here to get the vector to fill a D register.
7265 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7266                                             const EVT &OrigTy,
7267                                             const EVT &ExtTy,
7268                                             unsigned ExtOpcode) {
7269   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7270   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7271   // 64-bits we need to insert a new extension so that it will be 64-bits.
7272   assert(ExtTy.is128BitVector() && "Unexpected extension size");
7273   if (OrigTy.getSizeInBits() >= 64)
7274     return N;
7275 
7276   // Must extend size to at least 64 bits to be used as an operand for VMULL.
7277   EVT NewVT = getExtensionTo64Bits(OrigTy);
7278 
7279   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7280 }
7281 
7282 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7283 /// does not do any sign/zero extension. If the original vector is less
7284 /// than 64 bits, an appropriate extension will be added after the load to
7285 /// reach a total size of 64 bits. We have to add the extension separately
7286 /// because ARM does not have a sign/zero extending load for vectors.
7287 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7288   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7289 
7290   // The load already has the right type.
7291   if (ExtendedTy == LD->getMemoryVT())
7292     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7293                        LD->getBasePtr(), LD->getPointerInfo(),
7294                        LD->getAlignment(), LD->getMemOperand()->getFlags());
7295 
7296   // We need to create a zextload/sextload. We cannot just create a load
7297   // followed by a zext/zext node because LowerMUL is also run during normal
7298   // operation legalization where we can't create illegal types.
7299   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7300                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7301                         LD->getMemoryVT(), LD->getAlignment(),
7302                         LD->getMemOperand()->getFlags());
7303 }
7304 
7305 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7306 /// extending load, or BUILD_VECTOR with extended elements, return the
7307 /// unextended value. The unextended vector should be 64 bits so that it can
7308 /// be used as an operand to a VMULL instruction. If the original vector size
7309 /// before extension is less than 64 bits we add a an extension to resize
7310 /// the vector to 64 bits.
7311 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7312   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7313     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7314                                         N->getOperand(0)->getValueType(0),
7315                                         N->getValueType(0),
7316                                         N->getOpcode());
7317 
7318   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7319     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7320            "Expected extending load");
7321 
7322     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7323     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7324     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7325     SDValue extLoad =
7326         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7327     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7328 
7329     return newLoad;
7330   }
7331 
7332   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7333   // have been legalized as a BITCAST from v4i32.
7334   if (N->getOpcode() == ISD::BITCAST) {
7335     SDNode *BVN = N->getOperand(0).getNode();
7336     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7337            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7338     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7339     return DAG.getBuildVector(
7340         MVT::v2i32, SDLoc(N),
7341         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7342   }
7343   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7344   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7345   EVT VT = N->getValueType(0);
7346   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7347   unsigned NumElts = VT.getVectorNumElements();
7348   MVT TruncVT = MVT::getIntegerVT(EltSize);
7349   SmallVector<SDValue, 8> Ops;
7350   SDLoc dl(N);
7351   for (unsigned i = 0; i != NumElts; ++i) {
7352     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7353     const APInt &CInt = C->getAPIntValue();
7354     // Element types smaller than 32 bits are not legal, so use i32 elements.
7355     // The values are implicitly truncated so sext vs. zext doesn't matter.
7356     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7357   }
7358   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7359 }
7360 
7361 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7362   unsigned Opcode = N->getOpcode();
7363   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7364     SDNode *N0 = N->getOperand(0).getNode();
7365     SDNode *N1 = N->getOperand(1).getNode();
7366     return N0->hasOneUse() && N1->hasOneUse() &&
7367       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7368   }
7369   return false;
7370 }
7371 
7372 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7373   unsigned Opcode = N->getOpcode();
7374   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7375     SDNode *N0 = N->getOperand(0).getNode();
7376     SDNode *N1 = N->getOperand(1).getNode();
7377     return N0->hasOneUse() && N1->hasOneUse() &&
7378       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7379   }
7380   return false;
7381 }
7382 
7383 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7384   // Multiplications are only custom-lowered for 128-bit vectors so that
7385   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7386   EVT VT = Op.getValueType();
7387   assert(VT.is128BitVector() && VT.isInteger() &&
7388          "unexpected type for custom-lowering ISD::MUL");
7389   SDNode *N0 = Op.getOperand(0).getNode();
7390   SDNode *N1 = Op.getOperand(1).getNode();
7391   unsigned NewOpc = 0;
7392   bool isMLA = false;
7393   bool isN0SExt = isSignExtended(N0, DAG);
7394   bool isN1SExt = isSignExtended(N1, DAG);
7395   if (isN0SExt && isN1SExt)
7396     NewOpc = ARMISD::VMULLs;
7397   else {
7398     bool isN0ZExt = isZeroExtended(N0, DAG);
7399     bool isN1ZExt = isZeroExtended(N1, DAG);
7400     if (isN0ZExt && isN1ZExt)
7401       NewOpc = ARMISD::VMULLu;
7402     else if (isN1SExt || isN1ZExt) {
7403       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7404       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7405       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7406         NewOpc = ARMISD::VMULLs;
7407         isMLA = true;
7408       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7409         NewOpc = ARMISD::VMULLu;
7410         isMLA = true;
7411       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7412         std::swap(N0, N1);
7413         NewOpc = ARMISD::VMULLu;
7414         isMLA = true;
7415       }
7416     }
7417 
7418     if (!NewOpc) {
7419       if (VT == MVT::v2i64)
7420         // Fall through to expand this.  It is not legal.
7421         return SDValue();
7422       else
7423         // Other vector multiplications are legal.
7424         return Op;
7425     }
7426   }
7427 
7428   // Legalize to a VMULL instruction.
7429   SDLoc DL(Op);
7430   SDValue Op0;
7431   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7432   if (!isMLA) {
7433     Op0 = SkipExtensionForVMULL(N0, DAG);
7434     assert(Op0.getValueType().is64BitVector() &&
7435            Op1.getValueType().is64BitVector() &&
7436            "unexpected types for extended operands to VMULL");
7437     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7438   }
7439 
7440   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7441   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7442   //   vmull q0, d4, d6
7443   //   vmlal q0, d5, d6
7444   // is faster than
7445   //   vaddl q0, d4, d5
7446   //   vmovl q1, d6
7447   //   vmul  q0, q0, q1
7448   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7449   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7450   EVT Op1VT = Op1.getValueType();
7451   return DAG.getNode(N0->getOpcode(), DL, VT,
7452                      DAG.getNode(NewOpc, DL, VT,
7453                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7454                      DAG.getNode(NewOpc, DL, VT,
7455                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7456 }
7457 
7458 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7459                               SelectionDAG &DAG) {
7460   // TODO: Should this propagate fast-math-flags?
7461 
7462   // Convert to float
7463   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7464   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7465   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7466   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7467   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7468   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7469   // Get reciprocal estimate.
7470   // float4 recip = vrecpeq_f32(yf);
7471   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7472                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7473                    Y);
7474   // Because char has a smaller range than uchar, we can actually get away
7475   // without any newton steps.  This requires that we use a weird bias
7476   // of 0xb000, however (again, this has been exhaustively tested).
7477   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7478   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7479   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7480   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7481   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7482   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7483   // Convert back to short.
7484   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7485   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7486   return X;
7487 }
7488 
7489 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7490                                SelectionDAG &DAG) {
7491   // TODO: Should this propagate fast-math-flags?
7492 
7493   SDValue N2;
7494   // Convert to float.
7495   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7496   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7497   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7498   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7499   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7500   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7501 
7502   // Use reciprocal estimate and one refinement step.
7503   // float4 recip = vrecpeq_f32(yf);
7504   // recip *= vrecpsq_f32(yf, recip);
7505   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7506                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7507                    N1);
7508   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7509                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7510                    N1, N2);
7511   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7512   // Because short has a smaller range than ushort, we can actually get away
7513   // with only a single newton step.  This requires that we use a weird bias
7514   // of 89, however (again, this has been exhaustively tested).
7515   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7516   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7517   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7518   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7519   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7520   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7521   // Convert back to integer and return.
7522   // return vmovn_s32(vcvt_s32_f32(result));
7523   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7524   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7525   return N0;
7526 }
7527 
7528 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7529   EVT VT = Op.getValueType();
7530   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7531          "unexpected type for custom-lowering ISD::SDIV");
7532 
7533   SDLoc dl(Op);
7534   SDValue N0 = Op.getOperand(0);
7535   SDValue N1 = Op.getOperand(1);
7536   SDValue N2, N3;
7537 
7538   if (VT == MVT::v8i8) {
7539     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7540     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7541 
7542     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7543                      DAG.getIntPtrConstant(4, dl));
7544     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7545                      DAG.getIntPtrConstant(4, dl));
7546     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7547                      DAG.getIntPtrConstant(0, dl));
7548     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7549                      DAG.getIntPtrConstant(0, dl));
7550 
7551     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7552     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7553 
7554     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7555     N0 = LowerCONCAT_VECTORS(N0, DAG);
7556 
7557     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7558     return N0;
7559   }
7560   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7561 }
7562 
7563 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7564   // TODO: Should this propagate fast-math-flags?
7565   EVT VT = Op.getValueType();
7566   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7567          "unexpected type for custom-lowering ISD::UDIV");
7568 
7569   SDLoc dl(Op);
7570   SDValue N0 = Op.getOperand(0);
7571   SDValue N1 = Op.getOperand(1);
7572   SDValue N2, N3;
7573 
7574   if (VT == MVT::v8i8) {
7575     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7576     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7577 
7578     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7579                      DAG.getIntPtrConstant(4, dl));
7580     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7581                      DAG.getIntPtrConstant(4, dl));
7582     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7583                      DAG.getIntPtrConstant(0, dl));
7584     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7585                      DAG.getIntPtrConstant(0, dl));
7586 
7587     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7588     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7589 
7590     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7591     N0 = LowerCONCAT_VECTORS(N0, DAG);
7592 
7593     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7594                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7595                                      MVT::i32),
7596                      N0);
7597     return N0;
7598   }
7599 
7600   // v4i16 sdiv ... Convert to float.
7601   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7602   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7603   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7604   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7605   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7606   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7607 
7608   // Use reciprocal estimate and two refinement steps.
7609   // float4 recip = vrecpeq_f32(yf);
7610   // recip *= vrecpsq_f32(yf, recip);
7611   // recip *= vrecpsq_f32(yf, recip);
7612   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7613                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7614                    BN1);
7615   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7616                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7617                    BN1, N2);
7618   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7619   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7620                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7621                    BN1, N2);
7622   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7623   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7624   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7625   // and that it will never cause us to return an answer too large).
7626   // float4 result = as_float4(as_int4(xf*recip) + 2);
7627   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7628   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7629   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7630   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7631   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7632   // Convert back to integer and return.
7633   // return vmovn_u32(vcvt_s32_f32(result));
7634   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7635   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7636   return N0;
7637 }
7638 
7639 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7640   EVT VT = Op.getNode()->getValueType(0);
7641   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7642 
7643   unsigned Opc;
7644   bool ExtraOp = false;
7645   switch (Op.getOpcode()) {
7646   default: llvm_unreachable("Invalid code");
7647   case ISD::ADDC: Opc = ARMISD::ADDC; break;
7648   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7649   case ISD::SUBC: Opc = ARMISD::SUBC; break;
7650   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7651   }
7652 
7653   if (!ExtraOp)
7654     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7655                        Op.getOperand(1));
7656   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7657                      Op.getOperand(1), Op.getOperand(2));
7658 }
7659 
7660 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
7661   SDNode *N = Op.getNode();
7662   EVT VT = N->getValueType(0);
7663   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7664 
7665   SDValue Carry = Op.getOperand(2);
7666   EVT CarryVT = Carry.getValueType();
7667 
7668   SDLoc DL(Op);
7669 
7670   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
7671 
7672   SDValue Result;
7673   if (Op.getOpcode() == ISD::ADDCARRY) {
7674     // This converts the boolean value carry into the carry flag.
7675     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7676 
7677     // Do the addition proper using the carry flag we wanted.
7678     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
7679                          Op.getOperand(1), Carry.getValue(1));
7680 
7681     // Now convert the carry flag into a boolean value.
7682     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7683   } else {
7684     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
7685     // have to invert the carry first.
7686     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7687                         DAG.getConstant(1, DL, MVT::i32), Carry);
7688     // This converts the boolean value carry into the carry flag.
7689     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7690 
7691     // Do the subtraction proper using the carry flag we wanted.
7692     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
7693                          Op.getOperand(1), Carry.getValue(1));
7694 
7695     // Now convert the carry flag into a boolean value.
7696     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7697     // But the carry returned by ARMISD::SUBE is not a borrow as expected
7698     // by ISD::SUBCARRY, so compute 1 - C.
7699     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7700                         DAG.getConstant(1, DL, MVT::i32), Carry);
7701   }
7702 
7703   // Return both values.
7704   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
7705 }
7706 
7707 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7708   assert(Subtarget->isTargetDarwin());
7709 
7710   // For iOS, we want to call an alternative entry point: __sincos_stret,
7711   // return values are passed via sret.
7712   SDLoc dl(Op);
7713   SDValue Arg = Op.getOperand(0);
7714   EVT ArgVT = Arg.getValueType();
7715   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7716   auto PtrVT = getPointerTy(DAG.getDataLayout());
7717 
7718   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7719   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7720 
7721   // Pair of floats / doubles used to pass the result.
7722   Type *RetTy = StructType::get(ArgTy, ArgTy);
7723   auto &DL = DAG.getDataLayout();
7724 
7725   ArgListTy Args;
7726   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7727   SDValue SRet;
7728   if (ShouldUseSRet) {
7729     // Create stack object for sret.
7730     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7731     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7732     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7733     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7734 
7735     ArgListEntry Entry;
7736     Entry.Node = SRet;
7737     Entry.Ty = RetTy->getPointerTo();
7738     Entry.IsSExt = false;
7739     Entry.IsZExt = false;
7740     Entry.IsSRet = true;
7741     Args.push_back(Entry);
7742     RetTy = Type::getVoidTy(*DAG.getContext());
7743   }
7744 
7745   ArgListEntry Entry;
7746   Entry.Node = Arg;
7747   Entry.Ty = ArgTy;
7748   Entry.IsSExt = false;
7749   Entry.IsZExt = false;
7750   Args.push_back(Entry);
7751 
7752   RTLIB::Libcall LC =
7753       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
7754   const char *LibcallName = getLibcallName(LC);
7755   CallingConv::ID CC = getLibcallCallingConv(LC);
7756   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7757 
7758   TargetLowering::CallLoweringInfo CLI(DAG);
7759   CLI.setDebugLoc(dl)
7760       .setChain(DAG.getEntryNode())
7761       .setCallee(CC, RetTy, Callee, std::move(Args))
7762       .setDiscardResult(ShouldUseSRet);
7763   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7764 
7765   if (!ShouldUseSRet)
7766     return CallResult.first;
7767 
7768   SDValue LoadSin =
7769       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7770 
7771   // Address of cos field.
7772   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7773                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7774   SDValue LoadCos =
7775       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7776 
7777   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7778   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7779                      LoadSin.getValue(0), LoadCos.getValue(0));
7780 }
7781 
7782 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7783                                                   bool Signed,
7784                                                   SDValue &Chain) const {
7785   EVT VT = Op.getValueType();
7786   assert((VT == MVT::i32 || VT == MVT::i64) &&
7787          "unexpected type for custom lowering DIV");
7788   SDLoc dl(Op);
7789 
7790   const auto &DL = DAG.getDataLayout();
7791   const auto &TLI = DAG.getTargetLoweringInfo();
7792 
7793   const char *Name = nullptr;
7794   if (Signed)
7795     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7796   else
7797     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7798 
7799   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7800 
7801   ARMTargetLowering::ArgListTy Args;
7802 
7803   for (auto AI : {1, 0}) {
7804     ArgListEntry Arg;
7805     Arg.Node = Op.getOperand(AI);
7806     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7807     Args.push_back(Arg);
7808   }
7809 
7810   CallLoweringInfo CLI(DAG);
7811   CLI.setDebugLoc(dl)
7812     .setChain(Chain)
7813     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7814                ES, std::move(Args));
7815 
7816   return LowerCallTo(CLI).first;
7817 }
7818 
7819 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7820                                             bool Signed) const {
7821   assert(Op.getValueType() == MVT::i32 &&
7822          "unexpected type for custom lowering DIV");
7823   SDLoc dl(Op);
7824 
7825   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7826                                DAG.getEntryNode(), Op.getOperand(1));
7827 
7828   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7829 }
7830 
7831 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7832   SDLoc DL(N);
7833   SDValue Op = N->getOperand(1);
7834   if (N->getValueType(0) == MVT::i32)
7835     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7836   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7837                            DAG.getConstant(0, DL, MVT::i32));
7838   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7839                            DAG.getConstant(1, DL, MVT::i32));
7840   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7841                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7842 }
7843 
7844 void ARMTargetLowering::ExpandDIV_Windows(
7845     SDValue Op, SelectionDAG &DAG, bool Signed,
7846     SmallVectorImpl<SDValue> &Results) const {
7847   const auto &DL = DAG.getDataLayout();
7848   const auto &TLI = DAG.getTargetLoweringInfo();
7849 
7850   assert(Op.getValueType() == MVT::i64 &&
7851          "unexpected type for custom lowering DIV");
7852   SDLoc dl(Op);
7853 
7854   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7855 
7856   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7857 
7858   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7859   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7860                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7861   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7862 
7863   Results.push_back(Lower);
7864   Results.push_back(Upper);
7865 }
7866 
7867 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7868   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7869     // Acquire/Release load/store is not legal for targets without a dmb or
7870     // equivalent available.
7871     return SDValue();
7872 
7873   // Monotonic load/store is legal for all targets.
7874   return Op;
7875 }
7876 
7877 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7878                                     SmallVectorImpl<SDValue> &Results,
7879                                     SelectionDAG &DAG,
7880                                     const ARMSubtarget *Subtarget) {
7881   SDLoc DL(N);
7882   // Under Power Management extensions, the cycle-count is:
7883   //    mrc p15, #0, <Rt>, c9, c13, #0
7884   SDValue Ops[] = { N->getOperand(0), // Chain
7885                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7886                     DAG.getConstant(15, DL, MVT::i32),
7887                     DAG.getConstant(0, DL, MVT::i32),
7888                     DAG.getConstant(9, DL, MVT::i32),
7889                     DAG.getConstant(13, DL, MVT::i32),
7890                     DAG.getConstant(0, DL, MVT::i32)
7891   };
7892 
7893   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7894                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7895   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7896                                 DAG.getConstant(0, DL, MVT::i32)));
7897   Results.push_back(Cycles32.getValue(1));
7898 }
7899 
7900 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7901   SDLoc dl(V.getNode());
7902   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7903   SDValue VHi = DAG.getAnyExtOrTrunc(
7904       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7905       dl, MVT::i32);
7906   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7907   if (isBigEndian)
7908     std::swap (VLo, VHi);
7909   SDValue RegClass =
7910       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7911   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7912   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7913   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7914   return SDValue(
7915       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7916 }
7917 
7918 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7919                                        SmallVectorImpl<SDValue> & Results,
7920                                        SelectionDAG &DAG) {
7921   assert(N->getValueType(0) == MVT::i64 &&
7922          "AtomicCmpSwap on types less than 64 should be legal");
7923   SDValue Ops[] = {N->getOperand(1),
7924                    createGPRPairNode(DAG, N->getOperand(2)),
7925                    createGPRPairNode(DAG, N->getOperand(3)),
7926                    N->getOperand(0)};
7927   SDNode *CmpSwap = DAG.getMachineNode(
7928       ARM::CMP_SWAP_64, SDLoc(N),
7929       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7930 
7931   MachineFunction &MF = DAG.getMachineFunction();
7932   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7933   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7934   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7935 
7936   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7937 
7938   Results.push_back(
7939       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
7940                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7941   Results.push_back(
7942       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
7943                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7944   Results.push_back(SDValue(CmpSwap, 2));
7945 }
7946 
7947 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7948                           SelectionDAG &DAG) {
7949   const auto &TLI = DAG.getTargetLoweringInfo();
7950 
7951   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7952          "Custom lowering is MSVCRT specific!");
7953 
7954   SDLoc dl(Op);
7955   SDValue Val = Op.getOperand(0);
7956   MVT Ty = Val->getSimpleValueType(0);
7957   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7958   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7959                                          TLI.getPointerTy(DAG.getDataLayout()));
7960 
7961   TargetLowering::ArgListTy Args;
7962   TargetLowering::ArgListEntry Entry;
7963 
7964   Entry.Node = Val;
7965   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7966   Entry.IsZExt = true;
7967   Args.push_back(Entry);
7968 
7969   Entry.Node = Exponent;
7970   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7971   Entry.IsZExt = true;
7972   Args.push_back(Entry);
7973 
7974   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7975 
7976   // In the in-chain to the call is the entry node  If we are emitting a
7977   // tailcall, the chain will be mutated if the node has a non-entry input
7978   // chain.
7979   SDValue InChain = DAG.getEntryNode();
7980   SDValue TCChain = InChain;
7981 
7982   const Function &F = DAG.getMachineFunction().getFunction();
7983   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
7984               F.getReturnType() == LCRTy;
7985   if (IsTC)
7986     InChain = TCChain;
7987 
7988   TargetLowering::CallLoweringInfo CLI(DAG);
7989   CLI.setDebugLoc(dl)
7990       .setChain(InChain)
7991       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
7992       .setTailCall(IsTC);
7993   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
7994 
7995   // Return the chain (the DAG root) if it is a tail call
7996   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
7997 }
7998 
7999 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8000   DEBUG(dbgs() << "Lowering node: "; Op.dump());
8001   switch (Op.getOpcode()) {
8002   default: llvm_unreachable("Don't know how to custom lower this!");
8003   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
8004   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8005   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
8006   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8007   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8008   case ISD::SELECT:        return LowerSELECT(Op, DAG);
8009   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
8010   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
8011   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
8012   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
8013   case ISD::VASTART:       return LowerVASTART(Op, DAG);
8014   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8015   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
8016   case ISD::SINT_TO_FP:
8017   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
8018   case ISD::FP_TO_SINT:
8019   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
8020   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
8021   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
8022   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
8023   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
8024   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
8025   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
8026   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
8027                                                                Subtarget);
8028   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
8029   case ISD::SHL:
8030   case ISD::SRL:
8031   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
8032   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
8033   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
8034   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
8035   case ISD::SRL_PARTS:
8036   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
8037   case ISD::CTTZ:
8038   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
8039   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
8040   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
8041   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
8042   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
8043   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
8044   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8045   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8046   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8047   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8048   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
8049   case ISD::MUL:           return LowerMUL(Op, DAG);
8050   case ISD::SDIV:
8051     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8052       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
8053     return LowerSDIV(Op, DAG);
8054   case ISD::UDIV:
8055     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8056       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
8057     return LowerUDIV(Op, DAG);
8058   case ISD::ADDC:
8059   case ISD::ADDE:
8060   case ISD::SUBC:
8061   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
8062   case ISD::ADDCARRY:
8063   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
8064   case ISD::SADDO:
8065   case ISD::SSUBO:
8066     return LowerSignedALUO(Op, DAG);
8067   case ISD::UADDO:
8068   case ISD::USUBO:
8069     return LowerUnsignedALUO(Op, DAG);
8070   case ISD::ATOMIC_LOAD:
8071   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
8072   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
8073   case ISD::SDIVREM:
8074   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
8075   case ISD::DYNAMIC_STACKALLOC:
8076     if (Subtarget->isTargetWindows())
8077       return LowerDYNAMIC_STACKALLOC(Op, DAG);
8078     llvm_unreachable("Don't know how to custom lower this!");
8079   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
8080   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
8081   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
8082   case ARMISD::WIN__DBZCHK: return SDValue();
8083   }
8084 }
8085 
8086 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
8087                                  SelectionDAG &DAG) {
8088   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8089   unsigned Opc = 0;
8090   if (IntNo == Intrinsic::arm_smlald)
8091     Opc = ARMISD::SMLALD;
8092   else if (IntNo == Intrinsic::arm_smlaldx)
8093     Opc = ARMISD::SMLALDX;
8094   else if (IntNo == Intrinsic::arm_smlsld)
8095     Opc = ARMISD::SMLSLD;
8096   else if (IntNo == Intrinsic::arm_smlsldx)
8097     Opc = ARMISD::SMLSLDX;
8098   else
8099     return;
8100 
8101   SDLoc dl(N);
8102   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8103                            N->getOperand(3),
8104                            DAG.getConstant(0, dl, MVT::i32));
8105   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8106                            N->getOperand(3),
8107                            DAG.getConstant(1, dl, MVT::i32));
8108 
8109   SDValue LongMul = DAG.getNode(Opc, dl,
8110                                 DAG.getVTList(MVT::i32, MVT::i32),
8111                                 N->getOperand(1), N->getOperand(2),
8112                                 Lo, Hi);
8113   Results.push_back(LongMul.getValue(0));
8114   Results.push_back(LongMul.getValue(1));
8115 }
8116 
8117 /// ReplaceNodeResults - Replace the results of node with an illegal result
8118 /// type with new values built out of custom code.
8119 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
8120                                            SmallVectorImpl<SDValue> &Results,
8121                                            SelectionDAG &DAG) const {
8122   SDValue Res;
8123   switch (N->getOpcode()) {
8124   default:
8125     llvm_unreachable("Don't know how to custom expand this!");
8126   case ISD::READ_REGISTER:
8127     ExpandREAD_REGISTER(N, Results, DAG);
8128     break;
8129   case ISD::BITCAST:
8130     Res = ExpandBITCAST(N, DAG, Subtarget);
8131     break;
8132   case ISD::SRL:
8133   case ISD::SRA:
8134     Res = Expand64BitShift(N, DAG, Subtarget);
8135     break;
8136   case ISD::SREM:
8137   case ISD::UREM:
8138     Res = LowerREM(N, DAG);
8139     break;
8140   case ISD::SDIVREM:
8141   case ISD::UDIVREM:
8142     Res = LowerDivRem(SDValue(N, 0), DAG);
8143     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
8144     Results.push_back(Res.getValue(0));
8145     Results.push_back(Res.getValue(1));
8146     return;
8147   case ISD::READCYCLECOUNTER:
8148     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
8149     return;
8150   case ISD::UDIV:
8151   case ISD::SDIV:
8152     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
8153     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
8154                              Results);
8155   case ISD::ATOMIC_CMP_SWAP:
8156     ReplaceCMP_SWAP_64Results(N, Results, DAG);
8157     return;
8158   case ISD::INTRINSIC_WO_CHAIN:
8159     return ReplaceLongIntrinsic(N, Results, DAG);
8160   }
8161   if (Res.getNode())
8162     Results.push_back(Res);
8163 }
8164 
8165 //===----------------------------------------------------------------------===//
8166 //                           ARM Scheduler Hooks
8167 //===----------------------------------------------------------------------===//
8168 
8169 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
8170 /// registers the function context.
8171 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
8172                                                MachineBasicBlock *MBB,
8173                                                MachineBasicBlock *DispatchBB,
8174                                                int FI) const {
8175   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
8176          "ROPI/RWPI not currently supported with SjLj");
8177   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8178   DebugLoc dl = MI.getDebugLoc();
8179   MachineFunction *MF = MBB->getParent();
8180   MachineRegisterInfo *MRI = &MF->getRegInfo();
8181   MachineConstantPool *MCP = MF->getConstantPool();
8182   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
8183   const Function &F = MF->getFunction();
8184 
8185   bool isThumb = Subtarget->isThumb();
8186   bool isThumb2 = Subtarget->isThumb2();
8187 
8188   unsigned PCLabelId = AFI->createPICLabelUId();
8189   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
8190   ARMConstantPoolValue *CPV =
8191     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
8192   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
8193 
8194   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
8195                                            : &ARM::GPRRegClass;
8196 
8197   // Grab constant pool and fixed stack memory operands.
8198   MachineMemOperand *CPMMO =
8199       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
8200                                MachineMemOperand::MOLoad, 4, 4);
8201 
8202   MachineMemOperand *FIMMOSt =
8203       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
8204                                MachineMemOperand::MOStore, 4, 4);
8205 
8206   // Load the address of the dispatch MBB into the jump buffer.
8207   if (isThumb2) {
8208     // Incoming value: jbuf
8209     //   ldr.n  r5, LCPI1_1
8210     //   orr    r5, r5, #1
8211     //   add    r5, pc
8212     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
8213     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8214     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
8215         .addConstantPoolIndex(CPI)
8216         .addMemOperand(CPMMO)
8217         .add(predOps(ARMCC::AL));
8218     // Set the low bit because of thumb mode.
8219     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8220     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8221         .addReg(NewVReg1, RegState::Kill)
8222         .addImm(0x01)
8223         .add(predOps(ARMCC::AL))
8224         .add(condCodeOp());
8225     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8226     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8227       .addReg(NewVReg2, RegState::Kill)
8228       .addImm(PCLabelId);
8229     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8230         .addReg(NewVReg3, RegState::Kill)
8231         .addFrameIndex(FI)
8232         .addImm(36) // &jbuf[1] :: pc
8233         .addMemOperand(FIMMOSt)
8234         .add(predOps(ARMCC::AL));
8235   } else if (isThumb) {
8236     // Incoming value: jbuf
8237     //   ldr.n  r1, LCPI1_4
8238     //   add    r1, pc
8239     //   mov    r2, #1
8240     //   orrs   r1, r2
8241     //   add    r2, $jbuf, #+4 ; &jbuf[1]
8242     //   str    r1, [r2]
8243     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8244     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8245         .addConstantPoolIndex(CPI)
8246         .addMemOperand(CPMMO)
8247         .add(predOps(ARMCC::AL));
8248     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8249     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8250       .addReg(NewVReg1, RegState::Kill)
8251       .addImm(PCLabelId);
8252     // Set the low bit because of thumb mode.
8253     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8254     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8255         .addReg(ARM::CPSR, RegState::Define)
8256         .addImm(1)
8257         .add(predOps(ARMCC::AL));
8258     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8259     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8260         .addReg(ARM::CPSR, RegState::Define)
8261         .addReg(NewVReg2, RegState::Kill)
8262         .addReg(NewVReg3, RegState::Kill)
8263         .add(predOps(ARMCC::AL));
8264     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8265     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8266             .addFrameIndex(FI)
8267             .addImm(36); // &jbuf[1] :: pc
8268     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8269         .addReg(NewVReg4, RegState::Kill)
8270         .addReg(NewVReg5, RegState::Kill)
8271         .addImm(0)
8272         .addMemOperand(FIMMOSt)
8273         .add(predOps(ARMCC::AL));
8274   } else {
8275     // Incoming value: jbuf
8276     //   ldr  r1, LCPI1_1
8277     //   add  r1, pc, r1
8278     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
8279     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8280     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
8281         .addConstantPoolIndex(CPI)
8282         .addImm(0)
8283         .addMemOperand(CPMMO)
8284         .add(predOps(ARMCC::AL));
8285     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8286     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
8287         .addReg(NewVReg1, RegState::Kill)
8288         .addImm(PCLabelId)
8289         .add(predOps(ARMCC::AL));
8290     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
8291         .addReg(NewVReg2, RegState::Kill)
8292         .addFrameIndex(FI)
8293         .addImm(36) // &jbuf[1] :: pc
8294         .addMemOperand(FIMMOSt)
8295         .add(predOps(ARMCC::AL));
8296   }
8297 }
8298 
8299 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
8300                                               MachineBasicBlock *MBB) const {
8301   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8302   DebugLoc dl = MI.getDebugLoc();
8303   MachineFunction *MF = MBB->getParent();
8304   MachineRegisterInfo *MRI = &MF->getRegInfo();
8305   MachineFrameInfo &MFI = MF->getFrameInfo();
8306   int FI = MFI.getFunctionContextIndex();
8307 
8308   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
8309                                                         : &ARM::GPRnopcRegClass;
8310 
8311   // Get a mapping of the call site numbers to all of the landing pads they're
8312   // associated with.
8313   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
8314   unsigned MaxCSNum = 0;
8315   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8316        ++BB) {
8317     if (!BB->isEHPad()) continue;
8318 
8319     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8320     // pad.
8321     for (MachineBasicBlock::iterator
8322            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8323       if (!II->isEHLabel()) continue;
8324 
8325       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8326       if (!MF->hasCallSiteLandingPad(Sym)) continue;
8327 
8328       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8329       for (SmallVectorImpl<unsigned>::iterator
8330              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8331            CSI != CSE; ++CSI) {
8332         CallSiteNumToLPad[*CSI].push_back(&*BB);
8333         MaxCSNum = std::max(MaxCSNum, *CSI);
8334       }
8335       break;
8336     }
8337   }
8338 
8339   // Get an ordered list of the machine basic blocks for the jump table.
8340   std::vector<MachineBasicBlock*> LPadList;
8341   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8342   LPadList.reserve(CallSiteNumToLPad.size());
8343   for (unsigned I = 1; I <= MaxCSNum; ++I) {
8344     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8345     for (SmallVectorImpl<MachineBasicBlock*>::iterator
8346            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8347       LPadList.push_back(*II);
8348       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8349     }
8350   }
8351 
8352   assert(!LPadList.empty() &&
8353          "No landing pad destinations for the dispatch jump table!");
8354 
8355   // Create the jump table and associated information.
8356   MachineJumpTableInfo *JTI =
8357     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8358   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8359 
8360   // Create the MBBs for the dispatch code.
8361 
8362   // Shove the dispatch's address into the return slot in the function context.
8363   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8364   DispatchBB->setIsEHPad();
8365 
8366   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8367   unsigned trap_opcode;
8368   if (Subtarget->isThumb())
8369     trap_opcode = ARM::tTRAP;
8370   else
8371     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8372 
8373   BuildMI(TrapBB, dl, TII->get(trap_opcode));
8374   DispatchBB->addSuccessor(TrapBB);
8375 
8376   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8377   DispatchBB->addSuccessor(DispContBB);
8378 
8379   // Insert and MBBs.
8380   MF->insert(MF->end(), DispatchBB);
8381   MF->insert(MF->end(), DispContBB);
8382   MF->insert(MF->end(), TrapBB);
8383 
8384   // Insert code into the entry block that creates and registers the function
8385   // context.
8386   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8387 
8388   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8389       MachinePointerInfo::getFixedStack(*MF, FI),
8390       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8391 
8392   MachineInstrBuilder MIB;
8393   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8394 
8395   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8396   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8397 
8398   // Add a register mask with no preserved registers.  This results in all
8399   // registers being marked as clobbered. This can't work if the dispatch block
8400   // is in a Thumb1 function and is linked with ARM code which uses the FP
8401   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8402   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8403 
8404   bool IsPositionIndependent = isPositionIndependent();
8405   unsigned NumLPads = LPadList.size();
8406   if (Subtarget->isThumb2()) {
8407     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8408     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8409         .addFrameIndex(FI)
8410         .addImm(4)
8411         .addMemOperand(FIMMOLd)
8412         .add(predOps(ARMCC::AL));
8413 
8414     if (NumLPads < 256) {
8415       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8416           .addReg(NewVReg1)
8417           .addImm(LPadList.size())
8418           .add(predOps(ARMCC::AL));
8419     } else {
8420       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8421       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8422           .addImm(NumLPads & 0xFFFF)
8423           .add(predOps(ARMCC::AL));
8424 
8425       unsigned VReg2 = VReg1;
8426       if ((NumLPads & 0xFFFF0000) != 0) {
8427         VReg2 = MRI->createVirtualRegister(TRC);
8428         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8429             .addReg(VReg1)
8430             .addImm(NumLPads >> 16)
8431             .add(predOps(ARMCC::AL));
8432       }
8433 
8434       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8435           .addReg(NewVReg1)
8436           .addReg(VReg2)
8437           .add(predOps(ARMCC::AL));
8438     }
8439 
8440     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8441       .addMBB(TrapBB)
8442       .addImm(ARMCC::HI)
8443       .addReg(ARM::CPSR);
8444 
8445     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8446     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8447         .addJumpTableIndex(MJTI)
8448         .add(predOps(ARMCC::AL));
8449 
8450     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8451     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8452         .addReg(NewVReg3, RegState::Kill)
8453         .addReg(NewVReg1)
8454         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8455         .add(predOps(ARMCC::AL))
8456         .add(condCodeOp());
8457 
8458     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8459       .addReg(NewVReg4, RegState::Kill)
8460       .addReg(NewVReg1)
8461       .addJumpTableIndex(MJTI);
8462   } else if (Subtarget->isThumb()) {
8463     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8464     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8465         .addFrameIndex(FI)
8466         .addImm(1)
8467         .addMemOperand(FIMMOLd)
8468         .add(predOps(ARMCC::AL));
8469 
8470     if (NumLPads < 256) {
8471       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8472           .addReg(NewVReg1)
8473           .addImm(NumLPads)
8474           .add(predOps(ARMCC::AL));
8475     } else {
8476       MachineConstantPool *ConstantPool = MF->getConstantPool();
8477       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8478       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8479 
8480       // MachineConstantPool wants an explicit alignment.
8481       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8482       if (Align == 0)
8483         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8484       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8485 
8486       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8487       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8488           .addReg(VReg1, RegState::Define)
8489           .addConstantPoolIndex(Idx)
8490           .add(predOps(ARMCC::AL));
8491       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8492           .addReg(NewVReg1)
8493           .addReg(VReg1)
8494           .add(predOps(ARMCC::AL));
8495     }
8496 
8497     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8498       .addMBB(TrapBB)
8499       .addImm(ARMCC::HI)
8500       .addReg(ARM::CPSR);
8501 
8502     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8503     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8504         .addReg(ARM::CPSR, RegState::Define)
8505         .addReg(NewVReg1)
8506         .addImm(2)
8507         .add(predOps(ARMCC::AL));
8508 
8509     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8510     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8511         .addJumpTableIndex(MJTI)
8512         .add(predOps(ARMCC::AL));
8513 
8514     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8515     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8516         .addReg(ARM::CPSR, RegState::Define)
8517         .addReg(NewVReg2, RegState::Kill)
8518         .addReg(NewVReg3)
8519         .add(predOps(ARMCC::AL));
8520 
8521     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8522         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8523 
8524     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8525     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8526         .addReg(NewVReg4, RegState::Kill)
8527         .addImm(0)
8528         .addMemOperand(JTMMOLd)
8529         .add(predOps(ARMCC::AL));
8530 
8531     unsigned NewVReg6 = NewVReg5;
8532     if (IsPositionIndependent) {
8533       NewVReg6 = MRI->createVirtualRegister(TRC);
8534       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8535           .addReg(ARM::CPSR, RegState::Define)
8536           .addReg(NewVReg5, RegState::Kill)
8537           .addReg(NewVReg3)
8538           .add(predOps(ARMCC::AL));
8539     }
8540 
8541     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8542       .addReg(NewVReg6, RegState::Kill)
8543       .addJumpTableIndex(MJTI);
8544   } else {
8545     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8546     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8547         .addFrameIndex(FI)
8548         .addImm(4)
8549         .addMemOperand(FIMMOLd)
8550         .add(predOps(ARMCC::AL));
8551 
8552     if (NumLPads < 256) {
8553       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8554           .addReg(NewVReg1)
8555           .addImm(NumLPads)
8556           .add(predOps(ARMCC::AL));
8557     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8558       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8559       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8560           .addImm(NumLPads & 0xFFFF)
8561           .add(predOps(ARMCC::AL));
8562 
8563       unsigned VReg2 = VReg1;
8564       if ((NumLPads & 0xFFFF0000) != 0) {
8565         VReg2 = MRI->createVirtualRegister(TRC);
8566         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8567             .addReg(VReg1)
8568             .addImm(NumLPads >> 16)
8569             .add(predOps(ARMCC::AL));
8570       }
8571 
8572       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8573           .addReg(NewVReg1)
8574           .addReg(VReg2)
8575           .add(predOps(ARMCC::AL));
8576     } else {
8577       MachineConstantPool *ConstantPool = MF->getConstantPool();
8578       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8579       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8580 
8581       // MachineConstantPool wants an explicit alignment.
8582       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8583       if (Align == 0)
8584         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8585       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8586 
8587       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8588       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8589           .addReg(VReg1, RegState::Define)
8590           .addConstantPoolIndex(Idx)
8591           .addImm(0)
8592           .add(predOps(ARMCC::AL));
8593       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8594           .addReg(NewVReg1)
8595           .addReg(VReg1, RegState::Kill)
8596           .add(predOps(ARMCC::AL));
8597     }
8598 
8599     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8600       .addMBB(TrapBB)
8601       .addImm(ARMCC::HI)
8602       .addReg(ARM::CPSR);
8603 
8604     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8605     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8606         .addReg(NewVReg1)
8607         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8608         .add(predOps(ARMCC::AL))
8609         .add(condCodeOp());
8610     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8611     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8612         .addJumpTableIndex(MJTI)
8613         .add(predOps(ARMCC::AL));
8614 
8615     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8616         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8617     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8618     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8619         .addReg(NewVReg3, RegState::Kill)
8620         .addReg(NewVReg4)
8621         .addImm(0)
8622         .addMemOperand(JTMMOLd)
8623         .add(predOps(ARMCC::AL));
8624 
8625     if (IsPositionIndependent) {
8626       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8627         .addReg(NewVReg5, RegState::Kill)
8628         .addReg(NewVReg4)
8629         .addJumpTableIndex(MJTI);
8630     } else {
8631       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8632         .addReg(NewVReg5, RegState::Kill)
8633         .addJumpTableIndex(MJTI);
8634     }
8635   }
8636 
8637   // Add the jump table entries as successors to the MBB.
8638   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8639   for (std::vector<MachineBasicBlock*>::iterator
8640          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8641     MachineBasicBlock *CurMBB = *I;
8642     if (SeenMBBs.insert(CurMBB).second)
8643       DispContBB->addSuccessor(CurMBB);
8644   }
8645 
8646   // N.B. the order the invoke BBs are processed in doesn't matter here.
8647   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8648   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8649   for (MachineBasicBlock *BB : InvokeBBs) {
8650 
8651     // Remove the landing pad successor from the invoke block and replace it
8652     // with the new dispatch block.
8653     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8654                                                   BB->succ_end());
8655     while (!Successors.empty()) {
8656       MachineBasicBlock *SMBB = Successors.pop_back_val();
8657       if (SMBB->isEHPad()) {
8658         BB->removeSuccessor(SMBB);
8659         MBBLPads.push_back(SMBB);
8660       }
8661     }
8662 
8663     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8664     BB->normalizeSuccProbs();
8665 
8666     // Find the invoke call and mark all of the callee-saved registers as
8667     // 'implicit defined' so that they're spilled. This prevents code from
8668     // moving instructions to before the EH block, where they will never be
8669     // executed.
8670     for (MachineBasicBlock::reverse_iterator
8671            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8672       if (!II->isCall()) continue;
8673 
8674       DenseMap<unsigned, bool> DefRegs;
8675       for (MachineInstr::mop_iterator
8676              OI = II->operands_begin(), OE = II->operands_end();
8677            OI != OE; ++OI) {
8678         if (!OI->isReg()) continue;
8679         DefRegs[OI->getReg()] = true;
8680       }
8681 
8682       MachineInstrBuilder MIB(*MF, &*II);
8683 
8684       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8685         unsigned Reg = SavedRegs[i];
8686         if (Subtarget->isThumb2() &&
8687             !ARM::tGPRRegClass.contains(Reg) &&
8688             !ARM::hGPRRegClass.contains(Reg))
8689           continue;
8690         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8691           continue;
8692         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8693           continue;
8694         if (!DefRegs[Reg])
8695           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8696       }
8697 
8698       break;
8699     }
8700   }
8701 
8702   // Mark all former landing pads as non-landing pads. The dispatch is the only
8703   // landing pad now.
8704   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8705          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8706     (*I)->setIsEHPad(false);
8707 
8708   // The instruction is gone now.
8709   MI.eraseFromParent();
8710 }
8711 
8712 static
8713 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8714   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8715        E = MBB->succ_end(); I != E; ++I)
8716     if (*I != Succ)
8717       return *I;
8718   llvm_unreachable("Expecting a BB with two successors!");
8719 }
8720 
8721 /// Return the load opcode for a given load size. If load size >= 8,
8722 /// neon opcode will be returned.
8723 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8724   if (LdSize >= 8)
8725     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8726                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8727   if (IsThumb1)
8728     return LdSize == 4 ? ARM::tLDRi
8729                        : LdSize == 2 ? ARM::tLDRHi
8730                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8731   if (IsThumb2)
8732     return LdSize == 4 ? ARM::t2LDR_POST
8733                        : LdSize == 2 ? ARM::t2LDRH_POST
8734                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8735   return LdSize == 4 ? ARM::LDR_POST_IMM
8736                      : LdSize == 2 ? ARM::LDRH_POST
8737                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8738 }
8739 
8740 /// Return the store opcode for a given store size. If store size >= 8,
8741 /// neon opcode will be returned.
8742 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8743   if (StSize >= 8)
8744     return StSize == 16 ? ARM::VST1q32wb_fixed
8745                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8746   if (IsThumb1)
8747     return StSize == 4 ? ARM::tSTRi
8748                        : StSize == 2 ? ARM::tSTRHi
8749                                      : StSize == 1 ? ARM::tSTRBi : 0;
8750   if (IsThumb2)
8751     return StSize == 4 ? ARM::t2STR_POST
8752                        : StSize == 2 ? ARM::t2STRH_POST
8753                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8754   return StSize == 4 ? ARM::STR_POST_IMM
8755                      : StSize == 2 ? ARM::STRH_POST
8756                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8757 }
8758 
8759 /// Emit a post-increment load operation with given size. The instructions
8760 /// will be added to BB at Pos.
8761 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8762                        const TargetInstrInfo *TII, const DebugLoc &dl,
8763                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8764                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8765   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8766   assert(LdOpc != 0 && "Should have a load opcode");
8767   if (LdSize >= 8) {
8768     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8769         .addReg(AddrOut, RegState::Define)
8770         .addReg(AddrIn)
8771         .addImm(0)
8772         .add(predOps(ARMCC::AL));
8773   } else if (IsThumb1) {
8774     // load + update AddrIn
8775     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8776         .addReg(AddrIn)
8777         .addImm(0)
8778         .add(predOps(ARMCC::AL));
8779     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8780         .add(t1CondCodeOp())
8781         .addReg(AddrIn)
8782         .addImm(LdSize)
8783         .add(predOps(ARMCC::AL));
8784   } else if (IsThumb2) {
8785     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8786         .addReg(AddrOut, RegState::Define)
8787         .addReg(AddrIn)
8788         .addImm(LdSize)
8789         .add(predOps(ARMCC::AL));
8790   } else { // arm
8791     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8792         .addReg(AddrOut, RegState::Define)
8793         .addReg(AddrIn)
8794         .addReg(0)
8795         .addImm(LdSize)
8796         .add(predOps(ARMCC::AL));
8797   }
8798 }
8799 
8800 /// Emit a post-increment store operation with given size. The instructions
8801 /// will be added to BB at Pos.
8802 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8803                        const TargetInstrInfo *TII, const DebugLoc &dl,
8804                        unsigned StSize, unsigned Data, unsigned AddrIn,
8805                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8806   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8807   assert(StOpc != 0 && "Should have a store opcode");
8808   if (StSize >= 8) {
8809     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8810         .addReg(AddrIn)
8811         .addImm(0)
8812         .addReg(Data)
8813         .add(predOps(ARMCC::AL));
8814   } else if (IsThumb1) {
8815     // store + update AddrIn
8816     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8817         .addReg(Data)
8818         .addReg(AddrIn)
8819         .addImm(0)
8820         .add(predOps(ARMCC::AL));
8821     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8822         .add(t1CondCodeOp())
8823         .addReg(AddrIn)
8824         .addImm(StSize)
8825         .add(predOps(ARMCC::AL));
8826   } else if (IsThumb2) {
8827     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8828         .addReg(Data)
8829         .addReg(AddrIn)
8830         .addImm(StSize)
8831         .add(predOps(ARMCC::AL));
8832   } else { // arm
8833     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8834         .addReg(Data)
8835         .addReg(AddrIn)
8836         .addReg(0)
8837         .addImm(StSize)
8838         .add(predOps(ARMCC::AL));
8839   }
8840 }
8841 
8842 MachineBasicBlock *
8843 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8844                                    MachineBasicBlock *BB) const {
8845   // This pseudo instruction has 3 operands: dst, src, size
8846   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8847   // Otherwise, we will generate unrolled scalar copies.
8848   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8849   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8850   MachineFunction::iterator It = ++BB->getIterator();
8851 
8852   unsigned dest = MI.getOperand(0).getReg();
8853   unsigned src = MI.getOperand(1).getReg();
8854   unsigned SizeVal = MI.getOperand(2).getImm();
8855   unsigned Align = MI.getOperand(3).getImm();
8856   DebugLoc dl = MI.getDebugLoc();
8857 
8858   MachineFunction *MF = BB->getParent();
8859   MachineRegisterInfo &MRI = MF->getRegInfo();
8860   unsigned UnitSize = 0;
8861   const TargetRegisterClass *TRC = nullptr;
8862   const TargetRegisterClass *VecTRC = nullptr;
8863 
8864   bool IsThumb1 = Subtarget->isThumb1Only();
8865   bool IsThumb2 = Subtarget->isThumb2();
8866   bool IsThumb = Subtarget->isThumb();
8867 
8868   if (Align & 1) {
8869     UnitSize = 1;
8870   } else if (Align & 2) {
8871     UnitSize = 2;
8872   } else {
8873     // Check whether we can use NEON instructions.
8874     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
8875         Subtarget->hasNEON()) {
8876       if ((Align % 16 == 0) && SizeVal >= 16)
8877         UnitSize = 16;
8878       else if ((Align % 8 == 0) && SizeVal >= 8)
8879         UnitSize = 8;
8880     }
8881     // Can't use NEON instructions.
8882     if (UnitSize == 0)
8883       UnitSize = 4;
8884   }
8885 
8886   // Select the correct opcode and register class for unit size load/store
8887   bool IsNeon = UnitSize >= 8;
8888   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8889   if (IsNeon)
8890     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8891                             : UnitSize == 8 ? &ARM::DPRRegClass
8892                                             : nullptr;
8893 
8894   unsigned BytesLeft = SizeVal % UnitSize;
8895   unsigned LoopSize = SizeVal - BytesLeft;
8896 
8897   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8898     // Use LDR and STR to copy.
8899     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8900     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8901     unsigned srcIn = src;
8902     unsigned destIn = dest;
8903     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8904       unsigned srcOut = MRI.createVirtualRegister(TRC);
8905       unsigned destOut = MRI.createVirtualRegister(TRC);
8906       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8907       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8908                  IsThumb1, IsThumb2);
8909       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8910                  IsThumb1, IsThumb2);
8911       srcIn = srcOut;
8912       destIn = destOut;
8913     }
8914 
8915     // Handle the leftover bytes with LDRB and STRB.
8916     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8917     // [destOut] = STRB_POST(scratch, destIn, 1)
8918     for (unsigned i = 0; i < BytesLeft; i++) {
8919       unsigned srcOut = MRI.createVirtualRegister(TRC);
8920       unsigned destOut = MRI.createVirtualRegister(TRC);
8921       unsigned scratch = MRI.createVirtualRegister(TRC);
8922       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8923                  IsThumb1, IsThumb2);
8924       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8925                  IsThumb1, IsThumb2);
8926       srcIn = srcOut;
8927       destIn = destOut;
8928     }
8929     MI.eraseFromParent(); // The instruction is gone now.
8930     return BB;
8931   }
8932 
8933   // Expand the pseudo op to a loop.
8934   // thisMBB:
8935   //   ...
8936   //   movw varEnd, # --> with thumb2
8937   //   movt varEnd, #
8938   //   ldrcp varEnd, idx --> without thumb2
8939   //   fallthrough --> loopMBB
8940   // loopMBB:
8941   //   PHI varPhi, varEnd, varLoop
8942   //   PHI srcPhi, src, srcLoop
8943   //   PHI destPhi, dst, destLoop
8944   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8945   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8946   //   subs varLoop, varPhi, #UnitSize
8947   //   bne loopMBB
8948   //   fallthrough --> exitMBB
8949   // exitMBB:
8950   //   epilogue to handle left-over bytes
8951   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8952   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8953   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8954   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8955   MF->insert(It, loopMBB);
8956   MF->insert(It, exitMBB);
8957 
8958   // Transfer the remainder of BB and its successor edges to exitMBB.
8959   exitMBB->splice(exitMBB->begin(), BB,
8960                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8961   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8962 
8963   // Load an immediate to varEnd.
8964   unsigned varEnd = MRI.createVirtualRegister(TRC);
8965   if (Subtarget->useMovt(*MF)) {
8966     unsigned Vtmp = varEnd;
8967     if ((LoopSize & 0xFFFF0000) != 0)
8968       Vtmp = MRI.createVirtualRegister(TRC);
8969     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8970         .addImm(LoopSize & 0xFFFF)
8971         .add(predOps(ARMCC::AL));
8972 
8973     if ((LoopSize & 0xFFFF0000) != 0)
8974       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8975           .addReg(Vtmp)
8976           .addImm(LoopSize >> 16)
8977           .add(predOps(ARMCC::AL));
8978   } else {
8979     MachineConstantPool *ConstantPool = MF->getConstantPool();
8980     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8981     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8982 
8983     // MachineConstantPool wants an explicit alignment.
8984     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8985     if (Align == 0)
8986       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8987     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8988 
8989     if (IsThumb)
8990       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
8991           .addReg(varEnd, RegState::Define)
8992           .addConstantPoolIndex(Idx)
8993           .add(predOps(ARMCC::AL));
8994     else
8995       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
8996           .addReg(varEnd, RegState::Define)
8997           .addConstantPoolIndex(Idx)
8998           .addImm(0)
8999           .add(predOps(ARMCC::AL));
9000   }
9001   BB->addSuccessor(loopMBB);
9002 
9003   // Generate the loop body:
9004   //   varPhi = PHI(varLoop, varEnd)
9005   //   srcPhi = PHI(srcLoop, src)
9006   //   destPhi = PHI(destLoop, dst)
9007   MachineBasicBlock *entryBB = BB;
9008   BB = loopMBB;
9009   unsigned varLoop = MRI.createVirtualRegister(TRC);
9010   unsigned varPhi = MRI.createVirtualRegister(TRC);
9011   unsigned srcLoop = MRI.createVirtualRegister(TRC);
9012   unsigned srcPhi = MRI.createVirtualRegister(TRC);
9013   unsigned destLoop = MRI.createVirtualRegister(TRC);
9014   unsigned destPhi = MRI.createVirtualRegister(TRC);
9015 
9016   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
9017     .addReg(varLoop).addMBB(loopMBB)
9018     .addReg(varEnd).addMBB(entryBB);
9019   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
9020     .addReg(srcLoop).addMBB(loopMBB)
9021     .addReg(src).addMBB(entryBB);
9022   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
9023     .addReg(destLoop).addMBB(loopMBB)
9024     .addReg(dest).addMBB(entryBB);
9025 
9026   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9027   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
9028   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9029   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
9030              IsThumb1, IsThumb2);
9031   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
9032              IsThumb1, IsThumb2);
9033 
9034   // Decrement loop variable by UnitSize.
9035   if (IsThumb1) {
9036     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
9037         .add(t1CondCodeOp())
9038         .addReg(varPhi)
9039         .addImm(UnitSize)
9040         .add(predOps(ARMCC::AL));
9041   } else {
9042     MachineInstrBuilder MIB =
9043         BuildMI(*BB, BB->end(), dl,
9044                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
9045     MIB.addReg(varPhi)
9046         .addImm(UnitSize)
9047         .add(predOps(ARMCC::AL))
9048         .add(condCodeOp());
9049     MIB->getOperand(5).setReg(ARM::CPSR);
9050     MIB->getOperand(5).setIsDef(true);
9051   }
9052   BuildMI(*BB, BB->end(), dl,
9053           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
9054       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
9055 
9056   // loopMBB can loop back to loopMBB or fall through to exitMBB.
9057   BB->addSuccessor(loopMBB);
9058   BB->addSuccessor(exitMBB);
9059 
9060   // Add epilogue to handle BytesLeft.
9061   BB = exitMBB;
9062   auto StartOfExit = exitMBB->begin();
9063 
9064   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9065   //   [destOut] = STRB_POST(scratch, destLoop, 1)
9066   unsigned srcIn = srcLoop;
9067   unsigned destIn = destLoop;
9068   for (unsigned i = 0; i < BytesLeft; i++) {
9069     unsigned srcOut = MRI.createVirtualRegister(TRC);
9070     unsigned destOut = MRI.createVirtualRegister(TRC);
9071     unsigned scratch = MRI.createVirtualRegister(TRC);
9072     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
9073                IsThumb1, IsThumb2);
9074     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
9075                IsThumb1, IsThumb2);
9076     srcIn = srcOut;
9077     destIn = destOut;
9078   }
9079 
9080   MI.eraseFromParent(); // The instruction is gone now.
9081   return BB;
9082 }
9083 
9084 MachineBasicBlock *
9085 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
9086                                        MachineBasicBlock *MBB) const {
9087   const TargetMachine &TM = getTargetMachine();
9088   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
9089   DebugLoc DL = MI.getDebugLoc();
9090 
9091   assert(Subtarget->isTargetWindows() &&
9092          "__chkstk is only supported on Windows");
9093   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
9094 
9095   // __chkstk takes the number of words to allocate on the stack in R4, and
9096   // returns the stack adjustment in number of bytes in R4.  This will not
9097   // clober any other registers (other than the obvious lr).
9098   //
9099   // Although, technically, IP should be considered a register which may be
9100   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
9101   // thumb-2 environment, so there is no interworking required.  As a result, we
9102   // do not expect a veneer to be emitted by the linker, clobbering IP.
9103   //
9104   // Each module receives its own copy of __chkstk, so no import thunk is
9105   // required, again, ensuring that IP is not clobbered.
9106   //
9107   // Finally, although some linkers may theoretically provide a trampoline for
9108   // out of range calls (which is quite common due to a 32M range limitation of
9109   // branches for Thumb), we can generate the long-call version via
9110   // -mcmodel=large, alleviating the need for the trampoline which may clobber
9111   // IP.
9112 
9113   switch (TM.getCodeModel()) {
9114   case CodeModel::Small:
9115   case CodeModel::Medium:
9116   case CodeModel::Kernel:
9117     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
9118         .add(predOps(ARMCC::AL))
9119         .addExternalSymbol("__chkstk")
9120         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9121         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9122         .addReg(ARM::R12,
9123                 RegState::Implicit | RegState::Define | RegState::Dead)
9124         .addReg(ARM::CPSR,
9125                 RegState::Implicit | RegState::Define | RegState::Dead);
9126     break;
9127   case CodeModel::Large: {
9128     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9129     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
9130 
9131     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
9132       .addExternalSymbol("__chkstk");
9133     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
9134         .add(predOps(ARMCC::AL))
9135         .addReg(Reg, RegState::Kill)
9136         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9137         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9138         .addReg(ARM::R12,
9139                 RegState::Implicit | RegState::Define | RegState::Dead)
9140         .addReg(ARM::CPSR,
9141                 RegState::Implicit | RegState::Define | RegState::Dead);
9142     break;
9143   }
9144   }
9145 
9146   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
9147       .addReg(ARM::SP, RegState::Kill)
9148       .addReg(ARM::R4, RegState::Kill)
9149       .setMIFlags(MachineInstr::FrameSetup)
9150       .add(predOps(ARMCC::AL))
9151       .add(condCodeOp());
9152 
9153   MI.eraseFromParent();
9154   return MBB;
9155 }
9156 
9157 MachineBasicBlock *
9158 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
9159                                        MachineBasicBlock *MBB) const {
9160   DebugLoc DL = MI.getDebugLoc();
9161   MachineFunction *MF = MBB->getParent();
9162   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9163 
9164   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
9165   MF->insert(++MBB->getIterator(), ContBB);
9166   ContBB->splice(ContBB->begin(), MBB,
9167                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9168   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
9169   MBB->addSuccessor(ContBB);
9170 
9171   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9172   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
9173   MF->push_back(TrapBB);
9174   MBB->addSuccessor(TrapBB);
9175 
9176   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
9177       .addReg(MI.getOperand(0).getReg())
9178       .addImm(0)
9179       .add(predOps(ARMCC::AL));
9180   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
9181       .addMBB(TrapBB)
9182       .addImm(ARMCC::EQ)
9183       .addReg(ARM::CPSR);
9184 
9185   MI.eraseFromParent();
9186   return ContBB;
9187 }
9188 
9189 MachineBasicBlock *
9190 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9191                                                MachineBasicBlock *BB) const {
9192   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9193   DebugLoc dl = MI.getDebugLoc();
9194   bool isThumb2 = Subtarget->isThumb2();
9195   switch (MI.getOpcode()) {
9196   default: {
9197     MI.print(errs());
9198     llvm_unreachable("Unexpected instr type to insert");
9199   }
9200 
9201   // Thumb1 post-indexed loads are really just single-register LDMs.
9202   case ARM::tLDR_postidx: {
9203     MachineOperand Def(MI.getOperand(1));
9204     if (TargetRegisterInfo::isPhysicalRegister(Def.getReg()))
9205       Def.setIsRenamable(false);
9206     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
9207         .add(Def)  // Rn_wb
9208         .add(MI.getOperand(2))  // Rn
9209         .add(MI.getOperand(3))  // PredImm
9210         .add(MI.getOperand(4))  // PredReg
9211         .add(MI.getOperand(0)); // Rt
9212     MI.eraseFromParent();
9213     return BB;
9214   }
9215 
9216   // The Thumb2 pre-indexed stores have the same MI operands, they just
9217   // define them differently in the .td files from the isel patterns, so
9218   // they need pseudos.
9219   case ARM::t2STR_preidx:
9220     MI.setDesc(TII->get(ARM::t2STR_PRE));
9221     return BB;
9222   case ARM::t2STRB_preidx:
9223     MI.setDesc(TII->get(ARM::t2STRB_PRE));
9224     return BB;
9225   case ARM::t2STRH_preidx:
9226     MI.setDesc(TII->get(ARM::t2STRH_PRE));
9227     return BB;
9228 
9229   case ARM::STRi_preidx:
9230   case ARM::STRBi_preidx: {
9231     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9232                                                          : ARM::STRB_PRE_IMM;
9233     // Decode the offset.
9234     unsigned Offset = MI.getOperand(4).getImm();
9235     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
9236     Offset = ARM_AM::getAM2Offset(Offset);
9237     if (isSub)
9238       Offset = -Offset;
9239 
9240     MachineMemOperand *MMO = *MI.memoperands_begin();
9241     BuildMI(*BB, MI, dl, TII->get(NewOpc))
9242         .add(MI.getOperand(0)) // Rn_wb
9243         .add(MI.getOperand(1)) // Rt
9244         .add(MI.getOperand(2)) // Rn
9245         .addImm(Offset)        // offset (skip GPR==zero_reg)
9246         .add(MI.getOperand(5)) // pred
9247         .add(MI.getOperand(6))
9248         .addMemOperand(MMO);
9249     MI.eraseFromParent();
9250     return BB;
9251   }
9252   case ARM::STRr_preidx:
9253   case ARM::STRBr_preidx:
9254   case ARM::STRH_preidx: {
9255     unsigned NewOpc;
9256     switch (MI.getOpcode()) {
9257     default: llvm_unreachable("unexpected opcode!");
9258     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
9259     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
9260     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
9261     }
9262     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
9263     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
9264       MIB.add(MI.getOperand(i));
9265     MI.eraseFromParent();
9266     return BB;
9267   }
9268 
9269   case ARM::tMOVCCr_pseudo: {
9270     // To "insert" a SELECT_CC instruction, we actually have to insert the
9271     // diamond control-flow pattern.  The incoming instruction knows the
9272     // destination vreg to set, the condition code register to branch on, the
9273     // true/false values to select between, and a branch opcode to use.
9274     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9275     MachineFunction::iterator It = ++BB->getIterator();
9276 
9277     //  thisMBB:
9278     //  ...
9279     //   TrueVal = ...
9280     //   cmpTY ccX, r1, r2
9281     //   bCC copy1MBB
9282     //   fallthrough --> copy0MBB
9283     MachineBasicBlock *thisMBB  = BB;
9284     MachineFunction *F = BB->getParent();
9285     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9286     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
9287     F->insert(It, copy0MBB);
9288     F->insert(It, sinkMBB);
9289 
9290     // Transfer the remainder of BB and its successor edges to sinkMBB.
9291     sinkMBB->splice(sinkMBB->begin(), BB,
9292                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9293     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9294 
9295     BB->addSuccessor(copy0MBB);
9296     BB->addSuccessor(sinkMBB);
9297 
9298     BuildMI(BB, dl, TII->get(ARM::tBcc))
9299         .addMBB(sinkMBB)
9300         .addImm(MI.getOperand(3).getImm())
9301         .addReg(MI.getOperand(4).getReg());
9302 
9303     //  copy0MBB:
9304     //   %FalseValue = ...
9305     //   # fallthrough to sinkMBB
9306     BB = copy0MBB;
9307 
9308     // Update machine-CFG edges
9309     BB->addSuccessor(sinkMBB);
9310 
9311     //  sinkMBB:
9312     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9313     //  ...
9314     BB = sinkMBB;
9315     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
9316         .addReg(MI.getOperand(1).getReg())
9317         .addMBB(copy0MBB)
9318         .addReg(MI.getOperand(2).getReg())
9319         .addMBB(thisMBB);
9320 
9321     MI.eraseFromParent(); // The pseudo instruction is gone now.
9322     return BB;
9323   }
9324 
9325   case ARM::BCCi64:
9326   case ARM::BCCZi64: {
9327     // If there is an unconditional branch to the other successor, remove it.
9328     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9329 
9330     // Compare both parts that make up the double comparison separately for
9331     // equality.
9332     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9333 
9334     unsigned LHS1 = MI.getOperand(1).getReg();
9335     unsigned LHS2 = MI.getOperand(2).getReg();
9336     if (RHSisZero) {
9337       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9338           .addReg(LHS1)
9339           .addImm(0)
9340           .add(predOps(ARMCC::AL));
9341       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9342         .addReg(LHS2).addImm(0)
9343         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9344     } else {
9345       unsigned RHS1 = MI.getOperand(3).getReg();
9346       unsigned RHS2 = MI.getOperand(4).getReg();
9347       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9348           .addReg(LHS1)
9349           .addReg(RHS1)
9350           .add(predOps(ARMCC::AL));
9351       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9352         .addReg(LHS2).addReg(RHS2)
9353         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9354     }
9355 
9356     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9357     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9358     if (MI.getOperand(0).getImm() == ARMCC::NE)
9359       std::swap(destMBB, exitMBB);
9360 
9361     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9362       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9363     if (isThumb2)
9364       BuildMI(BB, dl, TII->get(ARM::t2B))
9365           .addMBB(exitMBB)
9366           .add(predOps(ARMCC::AL));
9367     else
9368       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9369 
9370     MI.eraseFromParent(); // The pseudo instruction is gone now.
9371     return BB;
9372   }
9373 
9374   case ARM::Int_eh_sjlj_setjmp:
9375   case ARM::Int_eh_sjlj_setjmp_nofp:
9376   case ARM::tInt_eh_sjlj_setjmp:
9377   case ARM::t2Int_eh_sjlj_setjmp:
9378   case ARM::t2Int_eh_sjlj_setjmp_nofp:
9379     return BB;
9380 
9381   case ARM::Int_eh_sjlj_setup_dispatch:
9382     EmitSjLjDispatchBlock(MI, BB);
9383     return BB;
9384 
9385   case ARM::ABS:
9386   case ARM::t2ABS: {
9387     // To insert an ABS instruction, we have to insert the
9388     // diamond control-flow pattern.  The incoming instruction knows the
9389     // source vreg to test against 0, the destination vreg to set,
9390     // the condition code register to branch on, the
9391     // true/false values to select between, and a branch opcode to use.
9392     // It transforms
9393     //     V1 = ABS V0
9394     // into
9395     //     V2 = MOVS V0
9396     //     BCC                      (branch to SinkBB if V0 >= 0)
9397     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
9398     //     SinkBB: V1 = PHI(V2, V3)
9399     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9400     MachineFunction::iterator BBI = ++BB->getIterator();
9401     MachineFunction *Fn = BB->getParent();
9402     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9403     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
9404     Fn->insert(BBI, RSBBB);
9405     Fn->insert(BBI, SinkBB);
9406 
9407     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9408     unsigned int ABSDstReg = MI.getOperand(0).getReg();
9409     bool ABSSrcKIll = MI.getOperand(1).isKill();
9410     bool isThumb2 = Subtarget->isThumb2();
9411     MachineRegisterInfo &MRI = Fn->getRegInfo();
9412     // In Thumb mode S must not be specified if source register is the SP or
9413     // PC and if destination register is the SP, so restrict register class
9414     unsigned NewRsbDstReg =
9415       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9416 
9417     // Transfer the remainder of BB and its successor edges to sinkMBB.
9418     SinkBB->splice(SinkBB->begin(), BB,
9419                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9420     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9421 
9422     BB->addSuccessor(RSBBB);
9423     BB->addSuccessor(SinkBB);
9424 
9425     // fall through to SinkMBB
9426     RSBBB->addSuccessor(SinkBB);
9427 
9428     // insert a cmp at the end of BB
9429     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9430         .addReg(ABSSrcReg)
9431         .addImm(0)
9432         .add(predOps(ARMCC::AL));
9433 
9434     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9435     BuildMI(BB, dl,
9436       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9437       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9438 
9439     // insert rsbri in RSBBB
9440     // Note: BCC and rsbri will be converted into predicated rsbmi
9441     // by if-conversion pass
9442     BuildMI(*RSBBB, RSBBB->begin(), dl,
9443             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9444         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9445         .addImm(0)
9446         .add(predOps(ARMCC::AL))
9447         .add(condCodeOp());
9448 
9449     // insert PHI in SinkBB,
9450     // reuse ABSDstReg to not change uses of ABS instruction
9451     BuildMI(*SinkBB, SinkBB->begin(), dl,
9452       TII->get(ARM::PHI), ABSDstReg)
9453       .addReg(NewRsbDstReg).addMBB(RSBBB)
9454       .addReg(ABSSrcReg).addMBB(BB);
9455 
9456     // remove ABS instruction
9457     MI.eraseFromParent();
9458 
9459     // return last added BB
9460     return SinkBB;
9461   }
9462   case ARM::COPY_STRUCT_BYVAL_I32:
9463     ++NumLoopByVals;
9464     return EmitStructByval(MI, BB);
9465   case ARM::WIN__CHKSTK:
9466     return EmitLowered__chkstk(MI, BB);
9467   case ARM::WIN__DBZCHK:
9468     return EmitLowered__dbzchk(MI, BB);
9469   }
9470 }
9471 
9472 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
9473 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9474 /// instead of as a custom inserter because we need the use list from the SDNode.
9475 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9476                                     MachineInstr &MI, const SDNode *Node) {
9477   bool isThumb1 = Subtarget->isThumb1Only();
9478 
9479   DebugLoc DL = MI.getDebugLoc();
9480   MachineFunction *MF = MI.getParent()->getParent();
9481   MachineRegisterInfo &MRI = MF->getRegInfo();
9482   MachineInstrBuilder MIB(*MF, MI);
9483 
9484   // If the new dst/src is unused mark it as dead.
9485   if (!Node->hasAnyUseOfValue(0)) {
9486     MI.getOperand(0).setIsDead(true);
9487   }
9488   if (!Node->hasAnyUseOfValue(1)) {
9489     MI.getOperand(1).setIsDead(true);
9490   }
9491 
9492   // The MEMCPY both defines and kills the scratch registers.
9493   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9494     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9495                                                          : &ARM::GPRRegClass);
9496     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9497   }
9498 }
9499 
9500 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9501                                                       SDNode *Node) const {
9502   if (MI.getOpcode() == ARM::MEMCPY) {
9503     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9504     return;
9505   }
9506 
9507   const MCInstrDesc *MCID = &MI.getDesc();
9508   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9509   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9510   // operand is still set to noreg. If needed, set the optional operand's
9511   // register to CPSR, and remove the redundant implicit def.
9512   //
9513   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
9514 
9515   // Rename pseudo opcodes.
9516   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9517   unsigned ccOutIdx;
9518   if (NewOpc) {
9519     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9520     MCID = &TII->get(NewOpc);
9521 
9522     assert(MCID->getNumOperands() ==
9523            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9524         && "converted opcode should be the same except for cc_out"
9525            " (and, on Thumb1, pred)");
9526 
9527     MI.setDesc(*MCID);
9528 
9529     // Add the optional cc_out operand
9530     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9531 
9532     // On Thumb1, move all input operands to the end, then add the predicate
9533     if (Subtarget->isThumb1Only()) {
9534       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9535         MI.addOperand(MI.getOperand(1));
9536         MI.RemoveOperand(1);
9537       }
9538 
9539       // Restore the ties
9540       for (unsigned i = MI.getNumOperands(); i--;) {
9541         const MachineOperand& op = MI.getOperand(i);
9542         if (op.isReg() && op.isUse()) {
9543           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9544           if (DefIdx != -1)
9545             MI.tieOperands(DefIdx, i);
9546         }
9547       }
9548 
9549       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9550       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9551       ccOutIdx = 1;
9552     } else
9553       ccOutIdx = MCID->getNumOperands() - 1;
9554   } else
9555     ccOutIdx = MCID->getNumOperands() - 1;
9556 
9557   // Any ARM instruction that sets the 's' bit should specify an optional
9558   // "cc_out" operand in the last operand position.
9559   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9560     assert(!NewOpc && "Optional cc_out operand required");
9561     return;
9562   }
9563   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9564   // since we already have an optional CPSR def.
9565   bool definesCPSR = false;
9566   bool deadCPSR = false;
9567   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9568        ++i) {
9569     const MachineOperand &MO = MI.getOperand(i);
9570     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9571       definesCPSR = true;
9572       if (MO.isDead())
9573         deadCPSR = true;
9574       MI.RemoveOperand(i);
9575       break;
9576     }
9577   }
9578   if (!definesCPSR) {
9579     assert(!NewOpc && "Optional cc_out operand required");
9580     return;
9581   }
9582   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9583   if (deadCPSR) {
9584     assert(!MI.getOperand(ccOutIdx).getReg() &&
9585            "expect uninitialized optional cc_out operand");
9586     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9587     if (!Subtarget->isThumb1Only())
9588       return;
9589   }
9590 
9591   // If this instruction was defined with an optional CPSR def and its dag node
9592   // had a live implicit CPSR def, then activate the optional CPSR def.
9593   MachineOperand &MO = MI.getOperand(ccOutIdx);
9594   MO.setReg(ARM::CPSR);
9595   MO.setIsDef(true);
9596 }
9597 
9598 //===----------------------------------------------------------------------===//
9599 //                           ARM Optimization Hooks
9600 //===----------------------------------------------------------------------===//
9601 
9602 // Helper function that checks if N is a null or all ones constant.
9603 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9604   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9605 }
9606 
9607 // Return true if N is conditionally 0 or all ones.
9608 // Detects these expressions where cc is an i1 value:
9609 //
9610 //   (select cc 0, y)   [AllOnes=0]
9611 //   (select cc y, 0)   [AllOnes=0]
9612 //   (zext cc)          [AllOnes=0]
9613 //   (sext cc)          [AllOnes=0/1]
9614 //   (select cc -1, y)  [AllOnes=1]
9615 //   (select cc y, -1)  [AllOnes=1]
9616 //
9617 // Invert is set when N is the null/all ones constant when CC is false.
9618 // OtherOp is set to the alternative value of N.
9619 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9620                                        SDValue &CC, bool &Invert,
9621                                        SDValue &OtherOp,
9622                                        SelectionDAG &DAG) {
9623   switch (N->getOpcode()) {
9624   default: return false;
9625   case ISD::SELECT: {
9626     CC = N->getOperand(0);
9627     SDValue N1 = N->getOperand(1);
9628     SDValue N2 = N->getOperand(2);
9629     if (isZeroOrAllOnes(N1, AllOnes)) {
9630       Invert = false;
9631       OtherOp = N2;
9632       return true;
9633     }
9634     if (isZeroOrAllOnes(N2, AllOnes)) {
9635       Invert = true;
9636       OtherOp = N1;
9637       return true;
9638     }
9639     return false;
9640   }
9641   case ISD::ZERO_EXTEND:
9642     // (zext cc) can never be the all ones value.
9643     if (AllOnes)
9644       return false;
9645     LLVM_FALLTHROUGH;
9646   case ISD::SIGN_EXTEND: {
9647     SDLoc dl(N);
9648     EVT VT = N->getValueType(0);
9649     CC = N->getOperand(0);
9650     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9651       return false;
9652     Invert = !AllOnes;
9653     if (AllOnes)
9654       // When looking for an AllOnes constant, N is an sext, and the 'other'
9655       // value is 0.
9656       OtherOp = DAG.getConstant(0, dl, VT);
9657     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9658       // When looking for a 0 constant, N can be zext or sext.
9659       OtherOp = DAG.getConstant(1, dl, VT);
9660     else
9661       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9662                                 VT);
9663     return true;
9664   }
9665   }
9666 }
9667 
9668 // Combine a constant select operand into its use:
9669 //
9670 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9671 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9672 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9673 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9674 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9675 //
9676 // The transform is rejected if the select doesn't have a constant operand that
9677 // is null, or all ones when AllOnes is set.
9678 //
9679 // Also recognize sext/zext from i1:
9680 //
9681 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9682 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9683 //
9684 // These transformations eventually create predicated instructions.
9685 //
9686 // @param N       The node to transform.
9687 // @param Slct    The N operand that is a select.
9688 // @param OtherOp The other N operand (x above).
9689 // @param DCI     Context.
9690 // @param AllOnes Require the select constant to be all ones instead of null.
9691 // @returns The new node, or SDValue() on failure.
9692 static
9693 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9694                             TargetLowering::DAGCombinerInfo &DCI,
9695                             bool AllOnes = false) {
9696   SelectionDAG &DAG = DCI.DAG;
9697   EVT VT = N->getValueType(0);
9698   SDValue NonConstantVal;
9699   SDValue CCOp;
9700   bool SwapSelectOps;
9701   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9702                                   NonConstantVal, DAG))
9703     return SDValue();
9704 
9705   // Slct is now know to be the desired identity constant when CC is true.
9706   SDValue TrueVal = OtherOp;
9707   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9708                                  OtherOp, NonConstantVal);
9709   // Unless SwapSelectOps says CC should be false.
9710   if (SwapSelectOps)
9711     std::swap(TrueVal, FalseVal);
9712 
9713   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9714                      CCOp, TrueVal, FalseVal);
9715 }
9716 
9717 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9718 static
9719 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9720                                        TargetLowering::DAGCombinerInfo &DCI) {
9721   SDValue N0 = N->getOperand(0);
9722   SDValue N1 = N->getOperand(1);
9723   if (N0.getNode()->hasOneUse())
9724     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9725       return Result;
9726   if (N1.getNode()->hasOneUse())
9727     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9728       return Result;
9729   return SDValue();
9730 }
9731 
9732 static bool IsVUZPShuffleNode(SDNode *N) {
9733   // VUZP shuffle node.
9734   if (N->getOpcode() == ARMISD::VUZP)
9735     return true;
9736 
9737   // "VUZP" on i32 is an alias for VTRN.
9738   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9739     return true;
9740 
9741   return false;
9742 }
9743 
9744 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9745                                  TargetLowering::DAGCombinerInfo &DCI,
9746                                  const ARMSubtarget *Subtarget) {
9747   // Look for ADD(VUZP.0, VUZP.1).
9748   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9749       N0 == N1)
9750    return SDValue();
9751 
9752   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9753   if (!N->getValueType(0).is64BitVector())
9754     return SDValue();
9755 
9756   // Generate vpadd.
9757   SelectionDAG &DAG = DCI.DAG;
9758   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9759   SDLoc dl(N);
9760   SDNode *Unzip = N0.getNode();
9761   EVT VT = N->getValueType(0);
9762 
9763   SmallVector<SDValue, 8> Ops;
9764   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9765                                 TLI.getPointerTy(DAG.getDataLayout())));
9766   Ops.push_back(Unzip->getOperand(0));
9767   Ops.push_back(Unzip->getOperand(1));
9768 
9769   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9770 }
9771 
9772 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9773                                       TargetLowering::DAGCombinerInfo &DCI,
9774                                       const ARMSubtarget *Subtarget) {
9775   // Check for two extended operands.
9776   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9777         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9778       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9779         N1.getOpcode() == ISD::ZERO_EXTEND))
9780     return SDValue();
9781 
9782   SDValue N00 = N0.getOperand(0);
9783   SDValue N10 = N1.getOperand(0);
9784 
9785   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9786   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9787       N00 == N10)
9788     return SDValue();
9789 
9790   // We only recognize Q register paddl here; this can't be reached until
9791   // after type legalization.
9792   if (!N00.getValueType().is64BitVector() ||
9793       !N0.getValueType().is128BitVector())
9794     return SDValue();
9795 
9796   // Generate vpaddl.
9797   SelectionDAG &DAG = DCI.DAG;
9798   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9799   SDLoc dl(N);
9800   EVT VT = N->getValueType(0);
9801 
9802   SmallVector<SDValue, 8> Ops;
9803   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9804   unsigned Opcode;
9805   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9806     Opcode = Intrinsic::arm_neon_vpaddls;
9807   else
9808     Opcode = Intrinsic::arm_neon_vpaddlu;
9809   Ops.push_back(DAG.getConstant(Opcode, dl,
9810                                 TLI.getPointerTy(DAG.getDataLayout())));
9811   EVT ElemTy = N00.getValueType().getVectorElementType();
9812   unsigned NumElts = VT.getVectorNumElements();
9813   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9814   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9815                                N00.getOperand(0), N00.getOperand(1));
9816   Ops.push_back(Concat);
9817 
9818   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9819 }
9820 
9821 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9822 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9823 // much easier to match.
9824 static SDValue
9825 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9826                                TargetLowering::DAGCombinerInfo &DCI,
9827                                const ARMSubtarget *Subtarget) {
9828   // Only perform optimization if after legalize, and if NEON is available. We
9829   // also expected both operands to be BUILD_VECTORs.
9830   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9831       || N0.getOpcode() != ISD::BUILD_VECTOR
9832       || N1.getOpcode() != ISD::BUILD_VECTOR)
9833     return SDValue();
9834 
9835   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9836   EVT VT = N->getValueType(0);
9837   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9838     return SDValue();
9839 
9840   // Check that the vector operands are of the right form.
9841   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9842   // operands, where N is the size of the formed vector.
9843   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9844   // index such that we have a pair wise add pattern.
9845 
9846   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9847   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9848     return SDValue();
9849   SDValue Vec = N0->getOperand(0)->getOperand(0);
9850   SDNode *V = Vec.getNode();
9851   unsigned nextIndex = 0;
9852 
9853   // For each operands to the ADD which are BUILD_VECTORs,
9854   // check to see if each of their operands are an EXTRACT_VECTOR with
9855   // the same vector and appropriate index.
9856   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9857     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9858         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9859 
9860       SDValue ExtVec0 = N0->getOperand(i);
9861       SDValue ExtVec1 = N1->getOperand(i);
9862 
9863       // First operand is the vector, verify its the same.
9864       if (V != ExtVec0->getOperand(0).getNode() ||
9865           V != ExtVec1->getOperand(0).getNode())
9866         return SDValue();
9867 
9868       // Second is the constant, verify its correct.
9869       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9870       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9871 
9872       // For the constant, we want to see all the even or all the odd.
9873       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9874           || C1->getZExtValue() != nextIndex+1)
9875         return SDValue();
9876 
9877       // Increment index.
9878       nextIndex+=2;
9879     } else
9880       return SDValue();
9881   }
9882 
9883   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9884   // we're using the entire input vector, otherwise there's a size/legality
9885   // mismatch somewhere.
9886   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9887       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9888     return SDValue();
9889 
9890   // Create VPADDL node.
9891   SelectionDAG &DAG = DCI.DAG;
9892   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9893 
9894   SDLoc dl(N);
9895 
9896   // Build operand list.
9897   SmallVector<SDValue, 8> Ops;
9898   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9899                                 TLI.getPointerTy(DAG.getDataLayout())));
9900 
9901   // Input is the vector.
9902   Ops.push_back(Vec);
9903 
9904   // Get widened type and narrowed type.
9905   MVT widenType;
9906   unsigned numElem = VT.getVectorNumElements();
9907 
9908   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9909   switch (inputLaneType.getSimpleVT().SimpleTy) {
9910     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9911     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9912     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9913     default:
9914       llvm_unreachable("Invalid vector element type for padd optimization.");
9915   }
9916 
9917   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9918   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9919   return DAG.getNode(ExtOp, dl, VT, tmp);
9920 }
9921 
9922 static SDValue findMUL_LOHI(SDValue V) {
9923   if (V->getOpcode() == ISD::UMUL_LOHI ||
9924       V->getOpcode() == ISD::SMUL_LOHI)
9925     return V;
9926   return SDValue();
9927 }
9928 
9929 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9930                                         TargetLowering::DAGCombinerInfo &DCI,
9931                                         const ARMSubtarget *Subtarget) {
9932   if (Subtarget->isThumb()) {
9933     if (!Subtarget->hasDSP())
9934       return SDValue();
9935   } else if (!Subtarget->hasV5TEOps())
9936     return SDValue();
9937 
9938   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
9939   // accumulates the product into a 64-bit value. The 16-bit values will
9940   // be sign extended somehow or SRA'd into 32-bit values
9941   // (addc (adde (mul 16bit, 16bit), lo), hi)
9942   SDValue Mul = AddcNode->getOperand(0);
9943   SDValue Lo = AddcNode->getOperand(1);
9944   if (Mul.getOpcode() != ISD::MUL) {
9945     Lo = AddcNode->getOperand(0);
9946     Mul = AddcNode->getOperand(1);
9947     if (Mul.getOpcode() != ISD::MUL)
9948       return SDValue();
9949   }
9950 
9951   SDValue SRA = AddeNode->getOperand(0);
9952   SDValue Hi = AddeNode->getOperand(1);
9953   if (SRA.getOpcode() != ISD::SRA) {
9954     SRA = AddeNode->getOperand(1);
9955     Hi = AddeNode->getOperand(0);
9956     if (SRA.getOpcode() != ISD::SRA)
9957       return SDValue();
9958   }
9959   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
9960     if (Const->getZExtValue() != 31)
9961       return SDValue();
9962   } else
9963     return SDValue();
9964 
9965   if (SRA.getOperand(0) != Mul)
9966     return SDValue();
9967 
9968   SelectionDAG &DAG = DCI.DAG;
9969   SDLoc dl(AddcNode);
9970   unsigned Opcode = 0;
9971   SDValue Op0;
9972   SDValue Op1;
9973 
9974   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
9975     Opcode = ARMISD::SMLALBB;
9976     Op0 = Mul.getOperand(0);
9977     Op1 = Mul.getOperand(1);
9978   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
9979     Opcode = ARMISD::SMLALBT;
9980     Op0 = Mul.getOperand(0);
9981     Op1 = Mul.getOperand(1).getOperand(0);
9982   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
9983     Opcode = ARMISD::SMLALTB;
9984     Op0 = Mul.getOperand(0).getOperand(0);
9985     Op1 = Mul.getOperand(1);
9986   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
9987     Opcode = ARMISD::SMLALTT;
9988     Op0 = Mul->getOperand(0).getOperand(0);
9989     Op1 = Mul->getOperand(1).getOperand(0);
9990   }
9991 
9992   if (!Op0 || !Op1)
9993     return SDValue();
9994 
9995   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
9996                               Op0, Op1, Lo, Hi);
9997   // Replace the ADDs' nodes uses by the MLA node's values.
9998   SDValue HiMLALResult(SMLAL.getNode(), 1);
9999   SDValue LoMLALResult(SMLAL.getNode(), 0);
10000 
10001   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
10002   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
10003 
10004   // Return original node to notify the driver to stop replacing.
10005   SDValue resNode(AddcNode, 0);
10006   return resNode;
10007 }
10008 
10009 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
10010                                      TargetLowering::DAGCombinerInfo &DCI,
10011                                      const ARMSubtarget *Subtarget) {
10012   // Look for multiply add opportunities.
10013   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
10014   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
10015   // a glue link from the first add to the second add.
10016   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
10017   // a S/UMLAL instruction.
10018   //                  UMUL_LOHI
10019   //                 / :lo    \ :hi
10020   //                V          \          [no multiline comment]
10021   //    loAdd ->  ADDC         |
10022   //                 \ :carry /
10023   //                  V      V
10024   //                    ADDE   <- hiAdd
10025   //
10026   // In the special case where only the higher part of a signed result is used
10027   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
10028   // a constant with the exact value of 0x80000000, we recognize we are dealing
10029   // with a "rounded multiply and add" (or subtract) and transform it into
10030   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
10031 
10032   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
10033           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
10034          "Expect an ADDE or SUBE");
10035 
10036   assert(AddeSubeNode->getNumOperands() == 3 &&
10037          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
10038          "ADDE node has the wrong inputs");
10039 
10040   // Check that we are chained to the right ADDC or SUBC node.
10041   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
10042   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10043        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
10044       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
10045        AddcSubcNode->getOpcode() != ARMISD::SUBC))
10046     return SDValue();
10047 
10048   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
10049   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
10050 
10051   // Check if the two operands are from the same mul_lohi node.
10052   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
10053     return SDValue();
10054 
10055   assert(AddcSubcNode->getNumValues() == 2 &&
10056          AddcSubcNode->getValueType(0) == MVT::i32 &&
10057          "Expect ADDC with two result values. First: i32");
10058 
10059   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
10060   // maybe a SMLAL which multiplies two 16-bit values.
10061   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10062       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
10063       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
10064       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
10065       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
10066     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
10067 
10068   // Check for the triangle shape.
10069   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
10070   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
10071 
10072   // Make sure that the ADDE/SUBE operands are not coming from the same node.
10073   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
10074     return SDValue();
10075 
10076   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
10077   bool IsLeftOperandMUL = false;
10078   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
10079   if (MULOp == SDValue())
10080     MULOp = findMUL_LOHI(AddeSubeOp1);
10081   else
10082     IsLeftOperandMUL = true;
10083   if (MULOp == SDValue())
10084     return SDValue();
10085 
10086   // Figure out the right opcode.
10087   unsigned Opc = MULOp->getOpcode();
10088   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
10089 
10090   // Figure out the high and low input values to the MLAL node.
10091   SDValue *HiAddSub = nullptr;
10092   SDValue *LoMul = nullptr;
10093   SDValue *LowAddSub = nullptr;
10094 
10095   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
10096   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
10097     return SDValue();
10098 
10099   if (IsLeftOperandMUL)
10100     HiAddSub = &AddeSubeOp1;
10101   else
10102     HiAddSub = &AddeSubeOp0;
10103 
10104   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
10105   // whose low result is fed to the ADDC/SUBC we are checking.
10106 
10107   if (AddcSubcOp0 == MULOp.getValue(0)) {
10108     LoMul = &AddcSubcOp0;
10109     LowAddSub = &AddcSubcOp1;
10110   }
10111   if (AddcSubcOp1 == MULOp.getValue(0)) {
10112     LoMul = &AddcSubcOp1;
10113     LowAddSub = &AddcSubcOp0;
10114   }
10115 
10116   if (!LoMul)
10117     return SDValue();
10118 
10119   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
10120   // the replacement below will create a cycle.
10121   if (AddcSubcNode == HiAddSub->getNode() ||
10122       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
10123     return SDValue();
10124 
10125   // Create the merged node.
10126   SelectionDAG &DAG = DCI.DAG;
10127 
10128   // Start building operand list.
10129   SmallVector<SDValue, 8> Ops;
10130   Ops.push_back(LoMul->getOperand(0));
10131   Ops.push_back(LoMul->getOperand(1));
10132 
10133   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
10134   // the case, we must be doing signed multiplication and only use the higher
10135   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
10136   // addition or subtraction with the value of 0x800000.
10137   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
10138       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
10139       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
10140       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
10141           0x80000000) {
10142     Ops.push_back(*HiAddSub);
10143     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
10144       FinalOpc = ARMISD::SMMLSR;
10145     } else {
10146       FinalOpc = ARMISD::SMMLAR;
10147     }
10148     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
10149     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
10150 
10151     return SDValue(AddeSubeNode, 0);
10152   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
10153     // SMMLS is generated during instruction selection and the rest of this
10154     // function can not handle the case where AddcSubcNode is a SUBC.
10155     return SDValue();
10156 
10157   // Finish building the operand list for {U/S}MLAL
10158   Ops.push_back(*LowAddSub);
10159   Ops.push_back(*HiAddSub);
10160 
10161   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
10162                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10163 
10164   // Replace the ADDs' nodes uses by the MLA node's values.
10165   SDValue HiMLALResult(MLALNode.getNode(), 1);
10166   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
10167 
10168   SDValue LoMLALResult(MLALNode.getNode(), 0);
10169   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
10170 
10171   // Return original node to notify the driver to stop replacing.
10172   return SDValue(AddeSubeNode, 0);
10173 }
10174 
10175 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
10176                                       TargetLowering::DAGCombinerInfo &DCI,
10177                                       const ARMSubtarget *Subtarget) {
10178   // UMAAL is similar to UMLAL except that it adds two unsigned values.
10179   // While trying to combine for the other MLAL nodes, first search for the
10180   // chance to use UMAAL. Check if Addc uses a node which has already
10181   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
10182   // as the addend, and it's handled in PerformUMLALCombine.
10183 
10184   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10185     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10186 
10187   // Check that we have a glued ADDC node.
10188   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
10189   if (AddcNode->getOpcode() != ARMISD::ADDC)
10190     return SDValue();
10191 
10192   // Find the converted UMAAL or quit if it doesn't exist.
10193   SDNode *UmlalNode = nullptr;
10194   SDValue AddHi;
10195   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
10196     UmlalNode = AddcNode->getOperand(0).getNode();
10197     AddHi = AddcNode->getOperand(1);
10198   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
10199     UmlalNode = AddcNode->getOperand(1).getNode();
10200     AddHi = AddcNode->getOperand(0);
10201   } else {
10202     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10203   }
10204 
10205   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
10206   // the ADDC as well as Zero.
10207   if (!isNullConstant(UmlalNode->getOperand(3)))
10208     return SDValue();
10209 
10210   if ((isNullConstant(AddeNode->getOperand(0)) &&
10211        AddeNode->getOperand(1).getNode() == UmlalNode) ||
10212       (AddeNode->getOperand(0).getNode() == UmlalNode &&
10213        isNullConstant(AddeNode->getOperand(1)))) {
10214     SelectionDAG &DAG = DCI.DAG;
10215     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
10216                       UmlalNode->getOperand(2), AddHi };
10217     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
10218                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10219 
10220     // Replace the ADDs' nodes uses by the UMAAL node's values.
10221     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
10222     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
10223 
10224     // Return original node to notify the driver to stop replacing.
10225     return SDValue(AddeNode, 0);
10226   }
10227   return SDValue();
10228 }
10229 
10230 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
10231                                    const ARMSubtarget *Subtarget) {
10232   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10233     return SDValue();
10234 
10235   // Check that we have a pair of ADDC and ADDE as operands.
10236   // Both addends of the ADDE must be zero.
10237   SDNode* AddcNode = N->getOperand(2).getNode();
10238   SDNode* AddeNode = N->getOperand(3).getNode();
10239   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
10240       (AddeNode->getOpcode() == ARMISD::ADDE) &&
10241       isNullConstant(AddeNode->getOperand(0)) &&
10242       isNullConstant(AddeNode->getOperand(1)) &&
10243       (AddeNode->getOperand(2).getNode() == AddcNode))
10244     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
10245                        DAG.getVTList(MVT::i32, MVT::i32),
10246                        {N->getOperand(0), N->getOperand(1),
10247                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
10248   else
10249     return SDValue();
10250 }
10251 
10252 static SDValue PerformAddcSubcCombine(SDNode *N,
10253                                       TargetLowering::DAGCombinerInfo &DCI,
10254                                       const ARMSubtarget *Subtarget) {
10255   SelectionDAG &DAG(DCI.DAG);
10256 
10257   if (N->getOpcode() == ARMISD::ADDC) {
10258     // (ADDC (ADDE 0, 0, C), -1) -> C
10259     SDValue LHS = N->getOperand(0);
10260     SDValue RHS = N->getOperand(1);
10261     if (LHS->getOpcode() == ARMISD::ADDE &&
10262         isNullConstant(LHS->getOperand(0)) &&
10263         isNullConstant(LHS->getOperand(1)) && isAllOnesConstant(RHS)) {
10264       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
10265     }
10266   }
10267 
10268   if (Subtarget->isThumb1Only()) {
10269     SDValue RHS = N->getOperand(1);
10270     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10271       int32_t imm = C->getSExtValue();
10272       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
10273         SDLoc DL(N);
10274         RHS = DAG.getConstant(-imm, DL, MVT::i32);
10275         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
10276                                                            : ARMISD::ADDC;
10277         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
10278       }
10279     }
10280   }
10281   return SDValue();
10282 }
10283 
10284 static SDValue PerformAddeSubeCombine(SDNode *N,
10285                                       TargetLowering::DAGCombinerInfo &DCI,
10286                                       const ARMSubtarget *Subtarget) {
10287   if (Subtarget->isThumb1Only()) {
10288     SelectionDAG &DAG = DCI.DAG;
10289     SDValue RHS = N->getOperand(1);
10290     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10291       int64_t imm = C->getSExtValue();
10292       if (imm < 0) {
10293         SDLoc DL(N);
10294 
10295         // The with-carry-in form matches bitwise not instead of the negation.
10296         // Effectively, the inverse interpretation of the carry flag already
10297         // accounts for part of the negation.
10298         RHS = DAG.getConstant(~imm, DL, MVT::i32);
10299 
10300         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
10301                                                            : ARMISD::ADDE;
10302         return DAG.getNode(Opcode, DL, N->getVTList(),
10303                            N->getOperand(0), RHS, N->getOperand(2));
10304       }
10305     }
10306   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
10307     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
10308   }
10309   return SDValue();
10310 }
10311 
10312 /// PerformADDECombine - Target-specific dag combine transform from
10313 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
10314 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
10315 static SDValue PerformADDECombine(SDNode *N,
10316                                   TargetLowering::DAGCombinerInfo &DCI,
10317                                   const ARMSubtarget *Subtarget) {
10318   // Only ARM and Thumb2 support UMLAL/SMLAL.
10319   if (Subtarget->isThumb1Only())
10320     return PerformAddeSubeCombine(N, DCI, Subtarget);
10321 
10322   // Only perform the checks after legalize when the pattern is available.
10323   if (DCI.isBeforeLegalize()) return SDValue();
10324 
10325   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
10326 }
10327 
10328 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
10329 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
10330 /// called with the default operands, and if that fails, with commuted
10331 /// operands.
10332 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
10333                                           TargetLowering::DAGCombinerInfo &DCI,
10334                                           const ARMSubtarget *Subtarget){
10335   // Attempt to create vpadd for this add.
10336   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
10337     return Result;
10338 
10339   // Attempt to create vpaddl for this add.
10340   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
10341     return Result;
10342   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
10343                                                       Subtarget))
10344     return Result;
10345 
10346   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10347   if (N0.getNode()->hasOneUse())
10348     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
10349       return Result;
10350   return SDValue();
10351 }
10352 
10353 static SDValue PerformSHLSimplify(SDNode *N,
10354                                 TargetLowering::DAGCombinerInfo &DCI,
10355                                 const ARMSubtarget *ST) {
10356   // Allow the generic combiner to identify potential bswaps.
10357   if (DCI.isBeforeLegalize())
10358     return SDValue();
10359 
10360   // DAG combiner will fold:
10361   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
10362   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
10363   // Other code patterns that can be also be modified have the following form:
10364   // b + ((a << 1) | 510)
10365   // b + ((a << 1) & 510)
10366   // b + ((a << 1) ^ 510)
10367   // b + ((a << 1) + 510)
10368 
10369   // Many instructions can  perform the shift for free, but it requires both
10370   // the operands to be registers. If c1 << c2 is too large, a mov immediate
10371   // instruction will needed. So, unfold back to the original pattern if:
10372   // - if c1 and c2 are small enough that they don't require mov imms.
10373   // - the user(s) of the node can perform an shl
10374 
10375   // No shifted operands for 16-bit instructions.
10376   if (ST->isThumb() && ST->isThumb1Only())
10377     return SDValue();
10378 
10379   // Check that all the users could perform the shl themselves.
10380   for (auto U : N->uses()) {
10381     switch(U->getOpcode()) {
10382     default:
10383       return SDValue();
10384     case ISD::SUB:
10385     case ISD::ADD:
10386     case ISD::AND:
10387     case ISD::OR:
10388     case ISD::XOR:
10389     case ISD::SETCC:
10390     case ARMISD::CMP:
10391       // Check that its not already using a shl.
10392       if (U->getOperand(0).getOpcode() == ISD::SHL ||
10393           U->getOperand(1).getOpcode() == ISD::SHL)
10394         return SDValue();
10395       break;
10396     }
10397   }
10398 
10399   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
10400       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
10401     return SDValue();
10402 
10403   if (N->getOperand(0).getOpcode() != ISD::SHL)
10404     return SDValue();
10405 
10406   SDValue SHL = N->getOperand(0);
10407 
10408   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
10409   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
10410   if (!C1ShlC2 || !C2)
10411     return SDValue();
10412 
10413   DEBUG(dbgs() << "Trying to simplify shl: "; N->dump());
10414 
10415   APInt C2Int = C2->getAPIntValue();
10416   APInt C1Int = C1ShlC2->getAPIntValue();
10417 
10418   // Check that performing a lshr will not lose any information.
10419   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
10420                                      C2Int.getBitWidth() - C2->getZExtValue());
10421   if ((C1Int & Mask) != C1Int)
10422     return SDValue();
10423 
10424   // Shift the first constant.
10425   C1Int.lshrInPlace(C2Int);
10426 
10427   // The immediates are encoded as an 8-bit value that can be rotated.
10428   unsigned Zeros = C1Int.countLeadingZeros() + C1Int.countTrailingZeros();
10429   if (C1Int.getBitWidth() - Zeros > 8)
10430     return SDValue();
10431 
10432   Zeros = C2Int.countLeadingZeros() + C2Int.countTrailingZeros();
10433   if (C2Int.getBitWidth() - Zeros > 8)
10434     return SDValue();
10435 
10436   SelectionDAG &DAG = DCI.DAG;
10437   SDLoc dl(N);
10438   SDValue X = SHL.getOperand(0);
10439   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
10440                               DAG.getConstant(C1Int, dl, MVT::i32));
10441   // Shift left to compensate for the lshr of C1Int.
10442   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
10443 
10444   DAG.ReplaceAllUsesWith(SDValue(N, 0), Res);
10445   return SDValue(N, 0);
10446 }
10447 
10448 
10449 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
10450 ///
10451 static SDValue PerformADDCombine(SDNode *N,
10452                                  TargetLowering::DAGCombinerInfo &DCI,
10453                                  const ARMSubtarget *Subtarget) {
10454   SDValue N0 = N->getOperand(0);
10455   SDValue N1 = N->getOperand(1);
10456 
10457   // Only works one way, because it needs an immediate operand.
10458   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10459     return Result;
10460 
10461   // First try with the default operand order.
10462   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
10463     return Result;
10464 
10465   // If that didn't work, try again with the operands commuted.
10466   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
10467 }
10468 
10469 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
10470 ///
10471 static SDValue PerformSUBCombine(SDNode *N,
10472                                  TargetLowering::DAGCombinerInfo &DCI) {
10473   SDValue N0 = N->getOperand(0);
10474   SDValue N1 = N->getOperand(1);
10475 
10476   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10477   if (N1.getNode()->hasOneUse())
10478     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10479       return Result;
10480 
10481   return SDValue();
10482 }
10483 
10484 /// PerformVMULCombine
10485 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10486 /// special multiplier accumulator forwarding.
10487 ///   vmul d3, d0, d2
10488 ///   vmla d3, d1, d2
10489 /// is faster than
10490 ///   vadd d3, d0, d1
10491 ///   vmul d3, d3, d2
10492 //  However, for (A + B) * (A + B),
10493 //    vadd d2, d0, d1
10494 //    vmul d3, d0, d2
10495 //    vmla d3, d1, d2
10496 //  is slower than
10497 //    vadd d2, d0, d1
10498 //    vmul d3, d2, d2
10499 static SDValue PerformVMULCombine(SDNode *N,
10500                                   TargetLowering::DAGCombinerInfo &DCI,
10501                                   const ARMSubtarget *Subtarget) {
10502   if (!Subtarget->hasVMLxForwarding())
10503     return SDValue();
10504 
10505   SelectionDAG &DAG = DCI.DAG;
10506   SDValue N0 = N->getOperand(0);
10507   SDValue N1 = N->getOperand(1);
10508   unsigned Opcode = N0.getOpcode();
10509   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10510       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10511     Opcode = N1.getOpcode();
10512     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10513         Opcode != ISD::FADD && Opcode != ISD::FSUB)
10514       return SDValue();
10515     std::swap(N0, N1);
10516   }
10517 
10518   if (N0 == N1)
10519     return SDValue();
10520 
10521   EVT VT = N->getValueType(0);
10522   SDLoc DL(N);
10523   SDValue N00 = N0->getOperand(0);
10524   SDValue N01 = N0->getOperand(1);
10525   return DAG.getNode(Opcode, DL, VT,
10526                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10527                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10528 }
10529 
10530 static SDValue PerformMULCombine(SDNode *N,
10531                                  TargetLowering::DAGCombinerInfo &DCI,
10532                                  const ARMSubtarget *Subtarget) {
10533   SelectionDAG &DAG = DCI.DAG;
10534 
10535   if (Subtarget->isThumb1Only())
10536     return SDValue();
10537 
10538   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10539     return SDValue();
10540 
10541   EVT VT = N->getValueType(0);
10542   if (VT.is64BitVector() || VT.is128BitVector())
10543     return PerformVMULCombine(N, DCI, Subtarget);
10544   if (VT != MVT::i32)
10545     return SDValue();
10546 
10547   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10548   if (!C)
10549     return SDValue();
10550 
10551   int64_t MulAmt = C->getSExtValue();
10552   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10553 
10554   ShiftAmt = ShiftAmt & (32 - 1);
10555   SDValue V = N->getOperand(0);
10556   SDLoc DL(N);
10557 
10558   SDValue Res;
10559   MulAmt >>= ShiftAmt;
10560 
10561   if (MulAmt >= 0) {
10562     if (isPowerOf2_32(MulAmt - 1)) {
10563       // (mul x, 2^N + 1) => (add (shl x, N), x)
10564       Res = DAG.getNode(ISD::ADD, DL, VT,
10565                         V,
10566                         DAG.getNode(ISD::SHL, DL, VT,
10567                                     V,
10568                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
10569                                                     MVT::i32)));
10570     } else if (isPowerOf2_32(MulAmt + 1)) {
10571       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10572       Res = DAG.getNode(ISD::SUB, DL, VT,
10573                         DAG.getNode(ISD::SHL, DL, VT,
10574                                     V,
10575                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10576                                                     MVT::i32)),
10577                         V);
10578     } else
10579       return SDValue();
10580   } else {
10581     uint64_t MulAmtAbs = -MulAmt;
10582     if (isPowerOf2_32(MulAmtAbs + 1)) {
10583       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10584       Res = DAG.getNode(ISD::SUB, DL, VT,
10585                         V,
10586                         DAG.getNode(ISD::SHL, DL, VT,
10587                                     V,
10588                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10589                                                     MVT::i32)));
10590     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10591       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10592       Res = DAG.getNode(ISD::ADD, DL, VT,
10593                         V,
10594                         DAG.getNode(ISD::SHL, DL, VT,
10595                                     V,
10596                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10597                                                     MVT::i32)));
10598       Res = DAG.getNode(ISD::SUB, DL, VT,
10599                         DAG.getConstant(0, DL, MVT::i32), Res);
10600     } else
10601       return SDValue();
10602   }
10603 
10604   if (ShiftAmt != 0)
10605     Res = DAG.getNode(ISD::SHL, DL, VT,
10606                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10607 
10608   // Do not add new nodes to DAG combiner worklist.
10609   DCI.CombineTo(N, Res, false);
10610   return SDValue();
10611 }
10612 
10613 static SDValue PerformANDCombine(SDNode *N,
10614                                  TargetLowering::DAGCombinerInfo &DCI,
10615                                  const ARMSubtarget *Subtarget) {
10616   // Attempt to use immediate-form VBIC
10617   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10618   SDLoc dl(N);
10619   EVT VT = N->getValueType(0);
10620   SelectionDAG &DAG = DCI.DAG;
10621 
10622   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10623     return SDValue();
10624 
10625   APInt SplatBits, SplatUndef;
10626   unsigned SplatBitSize;
10627   bool HasAnyUndefs;
10628   if (BVN &&
10629       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10630     if (SplatBitSize <= 64) {
10631       EVT VbicVT;
10632       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10633                                       SplatUndef.getZExtValue(), SplatBitSize,
10634                                       DAG, dl, VbicVT, VT.is128BitVector(),
10635                                       OtherModImm);
10636       if (Val.getNode()) {
10637         SDValue Input =
10638           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10639         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10640         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10641       }
10642     }
10643   }
10644 
10645   if (!Subtarget->isThumb1Only()) {
10646     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10647     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10648       return Result;
10649 
10650     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10651       return Result;
10652   }
10653 
10654   return SDValue();
10655 }
10656 
10657 // Try combining OR nodes to SMULWB, SMULWT.
10658 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10659                                          TargetLowering::DAGCombinerInfo &DCI,
10660                                          const ARMSubtarget *Subtarget) {
10661   if (!Subtarget->hasV6Ops() ||
10662       (Subtarget->isThumb() &&
10663        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10664     return SDValue();
10665 
10666   SDValue SRL = OR->getOperand(0);
10667   SDValue SHL = OR->getOperand(1);
10668 
10669   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10670     SRL = OR->getOperand(1);
10671     SHL = OR->getOperand(0);
10672   }
10673   if (!isSRL16(SRL) || !isSHL16(SHL))
10674     return SDValue();
10675 
10676   // The first operands to the shifts need to be the two results from the
10677   // same smul_lohi node.
10678   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10679        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10680     return SDValue();
10681 
10682   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10683   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10684       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10685     return SDValue();
10686 
10687   // Now we have:
10688   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10689   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10690   // For SMUWB the 16-bit value will signed extended somehow.
10691   // For SMULWT only the SRA is required.
10692   // Check both sides of SMUL_LOHI
10693   SDValue OpS16 = SMULLOHI->getOperand(0);
10694   SDValue OpS32 = SMULLOHI->getOperand(1);
10695 
10696   SelectionDAG &DAG = DCI.DAG;
10697   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10698     OpS16 = OpS32;
10699     OpS32 = SMULLOHI->getOperand(0);
10700   }
10701 
10702   SDLoc dl(OR);
10703   unsigned Opcode = 0;
10704   if (isS16(OpS16, DAG))
10705     Opcode = ARMISD::SMULWB;
10706   else if (isSRA16(OpS16)) {
10707     Opcode = ARMISD::SMULWT;
10708     OpS16 = OpS16->getOperand(0);
10709   }
10710   else
10711     return SDValue();
10712 
10713   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10714   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10715   return SDValue(OR, 0);
10716 }
10717 
10718 static SDValue PerformORCombineToBFI(SDNode *N,
10719                                      TargetLowering::DAGCombinerInfo &DCI,
10720                                      const ARMSubtarget *Subtarget) {
10721   // BFI is only available on V6T2+
10722   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10723     return SDValue();
10724 
10725   EVT VT = N->getValueType(0);
10726   SDValue N0 = N->getOperand(0);
10727   SDValue N1 = N->getOperand(1);
10728   SelectionDAG &DAG = DCI.DAG;
10729   SDLoc DL(N);
10730   // 1) or (and A, mask), val => ARMbfi A, val, mask
10731   //      iff (val & mask) == val
10732   //
10733   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10734   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10735   //          && mask == ~mask2
10736   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10737   //          && ~mask == mask2
10738   //  (i.e., copy a bitfield value into another bitfield of the same width)
10739 
10740   if (VT != MVT::i32)
10741     return SDValue();
10742 
10743   SDValue N00 = N0.getOperand(0);
10744 
10745   // The value and the mask need to be constants so we can verify this is
10746   // actually a bitfield set. If the mask is 0xffff, we can do better
10747   // via a movt instruction, so don't use BFI in that case.
10748   SDValue MaskOp = N0.getOperand(1);
10749   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10750   if (!MaskC)
10751     return SDValue();
10752   unsigned Mask = MaskC->getZExtValue();
10753   if (Mask == 0xffff)
10754     return SDValue();
10755   SDValue Res;
10756   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10757   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10758   if (N1C) {
10759     unsigned Val = N1C->getZExtValue();
10760     if ((Val & ~Mask) != Val)
10761       return SDValue();
10762 
10763     if (ARM::isBitFieldInvertedMask(Mask)) {
10764       Val >>= countTrailingZeros(~Mask);
10765 
10766       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10767                         DAG.getConstant(Val, DL, MVT::i32),
10768                         DAG.getConstant(Mask, DL, MVT::i32));
10769 
10770       DCI.CombineTo(N, Res, false);
10771       // Return value from the original node to inform the combiner than N is
10772       // now dead.
10773       return SDValue(N, 0);
10774     }
10775   } else if (N1.getOpcode() == ISD::AND) {
10776     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10777     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10778     if (!N11C)
10779       return SDValue();
10780     unsigned Mask2 = N11C->getZExtValue();
10781 
10782     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10783     // as is to match.
10784     if (ARM::isBitFieldInvertedMask(Mask) &&
10785         (Mask == ~Mask2)) {
10786       // The pack halfword instruction works better for masks that fit it,
10787       // so use that when it's available.
10788       if (Subtarget->hasDSP() &&
10789           (Mask == 0xffff || Mask == 0xffff0000))
10790         return SDValue();
10791       // 2a
10792       unsigned amt = countTrailingZeros(Mask2);
10793       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10794                         DAG.getConstant(amt, DL, MVT::i32));
10795       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10796                         DAG.getConstant(Mask, DL, MVT::i32));
10797       DCI.CombineTo(N, Res, false);
10798       // Return value from the original node to inform the combiner than N is
10799       // now dead.
10800       return SDValue(N, 0);
10801     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10802                (~Mask == Mask2)) {
10803       // The pack halfword instruction works better for masks that fit it,
10804       // so use that when it's available.
10805       if (Subtarget->hasDSP() &&
10806           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10807         return SDValue();
10808       // 2b
10809       unsigned lsb = countTrailingZeros(Mask);
10810       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10811                         DAG.getConstant(lsb, DL, MVT::i32));
10812       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10813                         DAG.getConstant(Mask2, DL, MVT::i32));
10814       DCI.CombineTo(N, Res, false);
10815       // Return value from the original node to inform the combiner than N is
10816       // now dead.
10817       return SDValue(N, 0);
10818     }
10819   }
10820 
10821   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10822       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10823       ARM::isBitFieldInvertedMask(~Mask)) {
10824     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10825     // where lsb(mask) == #shamt and masked bits of B are known zero.
10826     SDValue ShAmt = N00.getOperand(1);
10827     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10828     unsigned LSB = countTrailingZeros(Mask);
10829     if (ShAmtC != LSB)
10830       return SDValue();
10831 
10832     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10833                       DAG.getConstant(~Mask, DL, MVT::i32));
10834 
10835     DCI.CombineTo(N, Res, false);
10836     // Return value from the original node to inform the combiner than N is
10837     // now dead.
10838     return SDValue(N, 0);
10839   }
10840 
10841   return SDValue();
10842 }
10843 
10844 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
10845 static SDValue PerformORCombine(SDNode *N,
10846                                 TargetLowering::DAGCombinerInfo &DCI,
10847                                 const ARMSubtarget *Subtarget) {
10848   // Attempt to use immediate-form VORR
10849   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10850   SDLoc dl(N);
10851   EVT VT = N->getValueType(0);
10852   SelectionDAG &DAG = DCI.DAG;
10853 
10854   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10855     return SDValue();
10856 
10857   APInt SplatBits, SplatUndef;
10858   unsigned SplatBitSize;
10859   bool HasAnyUndefs;
10860   if (BVN && Subtarget->hasNEON() &&
10861       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10862     if (SplatBitSize <= 64) {
10863       EVT VorrVT;
10864       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
10865                                       SplatUndef.getZExtValue(), SplatBitSize,
10866                                       DAG, dl, VorrVT, VT.is128BitVector(),
10867                                       OtherModImm);
10868       if (Val.getNode()) {
10869         SDValue Input =
10870           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
10871         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
10872         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
10873       }
10874     }
10875   }
10876 
10877   if (!Subtarget->isThumb1Only()) {
10878     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10879     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10880       return Result;
10881     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
10882       return Result;
10883   }
10884 
10885   SDValue N0 = N->getOperand(0);
10886   SDValue N1 = N->getOperand(1);
10887 
10888   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
10889   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
10890       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10891 
10892     // The code below optimizes (or (and X, Y), Z).
10893     // The AND operand needs to have a single user to make these optimizations
10894     // profitable.
10895     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
10896       return SDValue();
10897 
10898     APInt SplatUndef;
10899     unsigned SplatBitSize;
10900     bool HasAnyUndefs;
10901 
10902     APInt SplatBits0, SplatBits1;
10903     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
10904     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
10905     // Ensure that the second operand of both ands are constants
10906     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
10907                                       HasAnyUndefs) && !HasAnyUndefs) {
10908         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
10909                                           HasAnyUndefs) && !HasAnyUndefs) {
10910             // Ensure that the bit width of the constants are the same and that
10911             // the splat arguments are logical inverses as per the pattern we
10912             // are trying to simplify.
10913             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
10914                 SplatBits0 == ~SplatBits1) {
10915                 // Canonicalize the vector type to make instruction selection
10916                 // simpler.
10917                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
10918                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
10919                                              N0->getOperand(1),
10920                                              N0->getOperand(0),
10921                                              N1->getOperand(0));
10922                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10923             }
10924         }
10925     }
10926   }
10927 
10928   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
10929   // reasonable.
10930   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
10931     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
10932       return Res;
10933   }
10934 
10935   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10936     return Result;
10937 
10938   return SDValue();
10939 }
10940 
10941 static SDValue PerformXORCombine(SDNode *N,
10942                                  TargetLowering::DAGCombinerInfo &DCI,
10943                                  const ARMSubtarget *Subtarget) {
10944   EVT VT = N->getValueType(0);
10945   SelectionDAG &DAG = DCI.DAG;
10946 
10947   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10948     return SDValue();
10949 
10950   if (!Subtarget->isThumb1Only()) {
10951     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10952     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10953       return Result;
10954 
10955     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10956       return Result;
10957   }
10958 
10959   return SDValue();
10960 }
10961 
10962 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
10963 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
10964 // their position in "to" (Rd).
10965 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
10966   assert(N->getOpcode() == ARMISD::BFI);
10967 
10968   SDValue From = N->getOperand(1);
10969   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
10970   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
10971 
10972   // If the Base came from a SHR #C, we can deduce that it is really testing bit
10973   // #C in the base of the SHR.
10974   if (From->getOpcode() == ISD::SRL &&
10975       isa<ConstantSDNode>(From->getOperand(1))) {
10976     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
10977     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
10978     FromMask <<= Shift.getLimitedValue(31);
10979     From = From->getOperand(0);
10980   }
10981 
10982   return From;
10983 }
10984 
10985 // If A and B contain one contiguous set of bits, does A | B == A . B?
10986 //
10987 // Neither A nor B must be zero.
10988 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
10989   unsigned LastActiveBitInA =  A.countTrailingZeros();
10990   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
10991   return LastActiveBitInA - 1 == FirstActiveBitInB;
10992 }
10993 
10994 static SDValue FindBFIToCombineWith(SDNode *N) {
10995   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
10996   // if one exists.
10997   APInt ToMask, FromMask;
10998   SDValue From = ParseBFI(N, ToMask, FromMask);
10999   SDValue To = N->getOperand(0);
11000 
11001   // Now check for a compatible BFI to merge with. We can pass through BFIs that
11002   // aren't compatible, but not if they set the same bit in their destination as
11003   // we do (or that of any BFI we're going to combine with).
11004   SDValue V = To;
11005   APInt CombinedToMask = ToMask;
11006   while (V.getOpcode() == ARMISD::BFI) {
11007     APInt NewToMask, NewFromMask;
11008     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
11009     if (NewFrom != From) {
11010       // This BFI has a different base. Keep going.
11011       CombinedToMask |= NewToMask;
11012       V = V.getOperand(0);
11013       continue;
11014     }
11015 
11016     // Do the written bits conflict with any we've seen so far?
11017     if ((NewToMask & CombinedToMask).getBoolValue())
11018       // Conflicting bits - bail out because going further is unsafe.
11019       return SDValue();
11020 
11021     // Are the new bits contiguous when combined with the old bits?
11022     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
11023         BitsProperlyConcatenate(FromMask, NewFromMask))
11024       return V;
11025     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
11026         BitsProperlyConcatenate(NewFromMask, FromMask))
11027       return V;
11028 
11029     // We've seen a write to some bits, so track it.
11030     CombinedToMask |= NewToMask;
11031     // Keep going...
11032     V = V.getOperand(0);
11033   }
11034 
11035   return SDValue();
11036 }
11037 
11038 static SDValue PerformBFICombine(SDNode *N,
11039                                  TargetLowering::DAGCombinerInfo &DCI) {
11040   SDValue N1 = N->getOperand(1);
11041   if (N1.getOpcode() == ISD::AND) {
11042     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
11043     // the bits being cleared by the AND are not demanded by the BFI.
11044     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11045     if (!N11C)
11046       return SDValue();
11047     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11048     unsigned LSB = countTrailingZeros(~InvMask);
11049     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
11050     assert(Width <
11051                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
11052            "undefined behavior");
11053     unsigned Mask = (1u << Width) - 1;
11054     unsigned Mask2 = N11C->getZExtValue();
11055     if ((Mask & (~Mask2)) == 0)
11056       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
11057                              N->getOperand(0), N1.getOperand(0),
11058                              N->getOperand(2));
11059   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
11060     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
11061     // Keep track of any consecutive bits set that all come from the same base
11062     // value. We can combine these together into a single BFI.
11063     SDValue CombineBFI = FindBFIToCombineWith(N);
11064     if (CombineBFI == SDValue())
11065       return SDValue();
11066 
11067     // We've found a BFI.
11068     APInt ToMask1, FromMask1;
11069     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
11070 
11071     APInt ToMask2, FromMask2;
11072     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
11073     assert(From1 == From2);
11074     (void)From2;
11075 
11076     // First, unlink CombineBFI.
11077     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
11078     // Then create a new BFI, combining the two together.
11079     APInt NewFromMask = FromMask1 | FromMask2;
11080     APInt NewToMask = ToMask1 | ToMask2;
11081 
11082     EVT VT = N->getValueType(0);
11083     SDLoc dl(N);
11084 
11085     if (NewFromMask[0] == 0)
11086       From1 = DCI.DAG.getNode(
11087         ISD::SRL, dl, VT, From1,
11088         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
11089     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
11090                            DCI.DAG.getConstant(~NewToMask, dl, VT));
11091   }
11092   return SDValue();
11093 }
11094 
11095 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
11096 /// ARMISD::VMOVRRD.
11097 static SDValue PerformVMOVRRDCombine(SDNode *N,
11098                                      TargetLowering::DAGCombinerInfo &DCI,
11099                                      const ARMSubtarget *Subtarget) {
11100   // vmovrrd(vmovdrr x, y) -> x,y
11101   SDValue InDouble = N->getOperand(0);
11102   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
11103     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
11104 
11105   // vmovrrd(load f64) -> (load i32), (load i32)
11106   SDNode *InNode = InDouble.getNode();
11107   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
11108       InNode->getValueType(0) == MVT::f64 &&
11109       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
11110       !cast<LoadSDNode>(InNode)->isVolatile()) {
11111     // TODO: Should this be done for non-FrameIndex operands?
11112     LoadSDNode *LD = cast<LoadSDNode>(InNode);
11113 
11114     SelectionDAG &DAG = DCI.DAG;
11115     SDLoc DL(LD);
11116     SDValue BasePtr = LD->getBasePtr();
11117     SDValue NewLD1 =
11118         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
11119                     LD->getAlignment(), LD->getMemOperand()->getFlags());
11120 
11121     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11122                                     DAG.getConstant(4, DL, MVT::i32));
11123     SDValue NewLD2 = DAG.getLoad(
11124         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
11125         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
11126 
11127     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
11128     if (DCI.DAG.getDataLayout().isBigEndian())
11129       std::swap (NewLD1, NewLD2);
11130     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
11131     return Result;
11132   }
11133 
11134   return SDValue();
11135 }
11136 
11137 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
11138 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
11139 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
11140   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
11141   SDValue Op0 = N->getOperand(0);
11142   SDValue Op1 = N->getOperand(1);
11143   if (Op0.getOpcode() == ISD::BITCAST)
11144     Op0 = Op0.getOperand(0);
11145   if (Op1.getOpcode() == ISD::BITCAST)
11146     Op1 = Op1.getOperand(0);
11147   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
11148       Op0.getNode() == Op1.getNode() &&
11149       Op0.getResNo() == 0 && Op1.getResNo() == 1)
11150     return DAG.getNode(ISD::BITCAST, SDLoc(N),
11151                        N->getValueType(0), Op0.getOperand(0));
11152   return SDValue();
11153 }
11154 
11155 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
11156 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
11157 /// i64 vector to have f64 elements, since the value can then be loaded
11158 /// directly into a VFP register.
11159 static bool hasNormalLoadOperand(SDNode *N) {
11160   unsigned NumElts = N->getValueType(0).getVectorNumElements();
11161   for (unsigned i = 0; i < NumElts; ++i) {
11162     SDNode *Elt = N->getOperand(i).getNode();
11163     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
11164       return true;
11165   }
11166   return false;
11167 }
11168 
11169 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
11170 /// ISD::BUILD_VECTOR.
11171 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
11172                                           TargetLowering::DAGCombinerInfo &DCI,
11173                                           const ARMSubtarget *Subtarget) {
11174   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
11175   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
11176   // into a pair of GPRs, which is fine when the value is used as a scalar,
11177   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
11178   SelectionDAG &DAG = DCI.DAG;
11179   if (N->getNumOperands() == 2)
11180     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
11181       return RV;
11182 
11183   // Load i64 elements as f64 values so that type legalization does not split
11184   // them up into i32 values.
11185   EVT VT = N->getValueType(0);
11186   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
11187     return SDValue();
11188   SDLoc dl(N);
11189   SmallVector<SDValue, 8> Ops;
11190   unsigned NumElts = VT.getVectorNumElements();
11191   for (unsigned i = 0; i < NumElts; ++i) {
11192     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
11193     Ops.push_back(V);
11194     // Make the DAGCombiner fold the bitcast.
11195     DCI.AddToWorklist(V.getNode());
11196   }
11197   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
11198   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
11199   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11200 }
11201 
11202 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
11203 static SDValue
11204 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11205   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
11206   // At that time, we may have inserted bitcasts from integer to float.
11207   // If these bitcasts have survived DAGCombine, change the lowering of this
11208   // BUILD_VECTOR in something more vector friendly, i.e., that does not
11209   // force to use floating point types.
11210 
11211   // Make sure we can change the type of the vector.
11212   // This is possible iff:
11213   // 1. The vector is only used in a bitcast to a integer type. I.e.,
11214   //    1.1. Vector is used only once.
11215   //    1.2. Use is a bit convert to an integer type.
11216   // 2. The size of its operands are 32-bits (64-bits are not legal).
11217   EVT VT = N->getValueType(0);
11218   EVT EltVT = VT.getVectorElementType();
11219 
11220   // Check 1.1. and 2.
11221   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
11222     return SDValue();
11223 
11224   // By construction, the input type must be float.
11225   assert(EltVT == MVT::f32 && "Unexpected type!");
11226 
11227   // Check 1.2.
11228   SDNode *Use = *N->use_begin();
11229   if (Use->getOpcode() != ISD::BITCAST ||
11230       Use->getValueType(0).isFloatingPoint())
11231     return SDValue();
11232 
11233   // Check profitability.
11234   // Model is, if more than half of the relevant operands are bitcast from
11235   // i32, turn the build_vector into a sequence of insert_vector_elt.
11236   // Relevant operands are everything that is not statically
11237   // (i.e., at compile time) bitcasted.
11238   unsigned NumOfBitCastedElts = 0;
11239   unsigned NumElts = VT.getVectorNumElements();
11240   unsigned NumOfRelevantElts = NumElts;
11241   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
11242     SDValue Elt = N->getOperand(Idx);
11243     if (Elt->getOpcode() == ISD::BITCAST) {
11244       // Assume only bit cast to i32 will go away.
11245       if (Elt->getOperand(0).getValueType() == MVT::i32)
11246         ++NumOfBitCastedElts;
11247     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
11248       // Constants are statically casted, thus do not count them as
11249       // relevant operands.
11250       --NumOfRelevantElts;
11251   }
11252 
11253   // Check if more than half of the elements require a non-free bitcast.
11254   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
11255     return SDValue();
11256 
11257   SelectionDAG &DAG = DCI.DAG;
11258   // Create the new vector type.
11259   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
11260   // Check if the type is legal.
11261   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11262   if (!TLI.isTypeLegal(VecVT))
11263     return SDValue();
11264 
11265   // Combine:
11266   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
11267   // => BITCAST INSERT_VECTOR_ELT
11268   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
11269   //                      (BITCAST EN), N.
11270   SDValue Vec = DAG.getUNDEF(VecVT);
11271   SDLoc dl(N);
11272   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
11273     SDValue V = N->getOperand(Idx);
11274     if (V.isUndef())
11275       continue;
11276     if (V.getOpcode() == ISD::BITCAST &&
11277         V->getOperand(0).getValueType() == MVT::i32)
11278       // Fold obvious case.
11279       V = V.getOperand(0);
11280     else {
11281       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
11282       // Make the DAGCombiner fold the bitcasts.
11283       DCI.AddToWorklist(V.getNode());
11284     }
11285     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
11286     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
11287   }
11288   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
11289   // Make the DAGCombiner fold the bitcasts.
11290   DCI.AddToWorklist(Vec.getNode());
11291   return Vec;
11292 }
11293 
11294 /// PerformInsertEltCombine - Target-specific dag combine xforms for
11295 /// ISD::INSERT_VECTOR_ELT.
11296 static SDValue PerformInsertEltCombine(SDNode *N,
11297                                        TargetLowering::DAGCombinerInfo &DCI) {
11298   // Bitcast an i64 load inserted into a vector to f64.
11299   // Otherwise, the i64 value will be legalized to a pair of i32 values.
11300   EVT VT = N->getValueType(0);
11301   SDNode *Elt = N->getOperand(1).getNode();
11302   if (VT.getVectorElementType() != MVT::i64 ||
11303       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
11304     return SDValue();
11305 
11306   SelectionDAG &DAG = DCI.DAG;
11307   SDLoc dl(N);
11308   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11309                                  VT.getVectorNumElements());
11310   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
11311   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
11312   // Make the DAGCombiner fold the bitcasts.
11313   DCI.AddToWorklist(Vec.getNode());
11314   DCI.AddToWorklist(V.getNode());
11315   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
11316                                Vec, V, N->getOperand(2));
11317   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
11318 }
11319 
11320 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
11321 /// ISD::VECTOR_SHUFFLE.
11322 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
11323   // The LLVM shufflevector instruction does not require the shuffle mask
11324   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
11325   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
11326   // operands do not match the mask length, they are extended by concatenating
11327   // them with undef vectors.  That is probably the right thing for other
11328   // targets, but for NEON it is better to concatenate two double-register
11329   // size vector operands into a single quad-register size vector.  Do that
11330   // transformation here:
11331   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
11332   //   shuffle(concat(v1, v2), undef)
11333   SDValue Op0 = N->getOperand(0);
11334   SDValue Op1 = N->getOperand(1);
11335   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
11336       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
11337       Op0.getNumOperands() != 2 ||
11338       Op1.getNumOperands() != 2)
11339     return SDValue();
11340   SDValue Concat0Op1 = Op0.getOperand(1);
11341   SDValue Concat1Op1 = Op1.getOperand(1);
11342   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
11343     return SDValue();
11344   // Skip the transformation if any of the types are illegal.
11345   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11346   EVT VT = N->getValueType(0);
11347   if (!TLI.isTypeLegal(VT) ||
11348       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
11349       !TLI.isTypeLegal(Concat1Op1.getValueType()))
11350     return SDValue();
11351 
11352   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11353                                   Op0.getOperand(0), Op1.getOperand(0));
11354   // Translate the shuffle mask.
11355   SmallVector<int, 16> NewMask;
11356   unsigned NumElts = VT.getVectorNumElements();
11357   unsigned HalfElts = NumElts/2;
11358   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11359   for (unsigned n = 0; n < NumElts; ++n) {
11360     int MaskElt = SVN->getMaskElt(n);
11361     int NewElt = -1;
11362     if (MaskElt < (int)HalfElts)
11363       NewElt = MaskElt;
11364     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
11365       NewElt = HalfElts + MaskElt - NumElts;
11366     NewMask.push_back(NewElt);
11367   }
11368   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
11369                               DAG.getUNDEF(VT), NewMask);
11370 }
11371 
11372 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
11373 /// NEON load/store intrinsics, and generic vector load/stores, to merge
11374 /// base address updates.
11375 /// For generic load/stores, the memory type is assumed to be a vector.
11376 /// The caller is assumed to have checked legality.
11377 static SDValue CombineBaseUpdate(SDNode *N,
11378                                  TargetLowering::DAGCombinerInfo &DCI) {
11379   SelectionDAG &DAG = DCI.DAG;
11380   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
11381                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
11382   const bool isStore = N->getOpcode() == ISD::STORE;
11383   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
11384   SDValue Addr = N->getOperand(AddrOpIdx);
11385   MemSDNode *MemN = cast<MemSDNode>(N);
11386   SDLoc dl(N);
11387 
11388   // Search for a use of the address operand that is an increment.
11389   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11390          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11391     SDNode *User = *UI;
11392     if (User->getOpcode() != ISD::ADD ||
11393         UI.getUse().getResNo() != Addr.getResNo())
11394       continue;
11395 
11396     // Check that the add is independent of the load/store.  Otherwise, folding
11397     // it would create a cycle.
11398     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
11399       continue;
11400 
11401     // Find the new opcode for the updating load/store.
11402     bool isLoadOp = true;
11403     bool isLaneOp = false;
11404     unsigned NewOpc = 0;
11405     unsigned NumVecs = 0;
11406     if (isIntrinsic) {
11407       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11408       switch (IntNo) {
11409       default: llvm_unreachable("unexpected intrinsic for Neon base update");
11410       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
11411         NumVecs = 1; break;
11412       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
11413         NumVecs = 2; break;
11414       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
11415         NumVecs = 3; break;
11416       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
11417         NumVecs = 4; break;
11418       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
11419         NumVecs = 2; isLaneOp = true; break;
11420       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
11421         NumVecs = 3; isLaneOp = true; break;
11422       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
11423         NumVecs = 4; isLaneOp = true; break;
11424       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
11425         NumVecs = 1; isLoadOp = false; break;
11426       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
11427         NumVecs = 2; isLoadOp = false; break;
11428       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
11429         NumVecs = 3; isLoadOp = false; break;
11430       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
11431         NumVecs = 4; isLoadOp = false; break;
11432       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
11433         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
11434       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
11435         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
11436       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
11437         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
11438       }
11439     } else {
11440       isLaneOp = true;
11441       switch (N->getOpcode()) {
11442       default: llvm_unreachable("unexpected opcode for Neon base update");
11443       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
11444       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
11445       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
11446       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
11447       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
11448         NumVecs = 1; isLaneOp = false; break;
11449       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
11450         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
11451       }
11452     }
11453 
11454     // Find the size of memory referenced by the load/store.
11455     EVT VecTy;
11456     if (isLoadOp) {
11457       VecTy = N->getValueType(0);
11458     } else if (isIntrinsic) {
11459       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
11460     } else {
11461       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
11462       VecTy = N->getOperand(1).getValueType();
11463     }
11464 
11465     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11466     if (isLaneOp)
11467       NumBytes /= VecTy.getVectorNumElements();
11468 
11469     // If the increment is a constant, it must match the memory ref size.
11470     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11471     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
11472     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
11473       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
11474       // separate instructions that make it harder to use a non-constant update.
11475       continue;
11476     }
11477 
11478     // OK, we found an ADD we can fold into the base update.
11479     // Now, create a _UPD node, taking care of not breaking alignment.
11480 
11481     EVT AlignedVecTy = VecTy;
11482     unsigned Alignment = MemN->getAlignment();
11483 
11484     // If this is a less-than-standard-aligned load/store, change the type to
11485     // match the standard alignment.
11486     // The alignment is overlooked when selecting _UPD variants; and it's
11487     // easier to introduce bitcasts here than fix that.
11488     // There are 3 ways to get to this base-update combine:
11489     // - intrinsics: they are assumed to be properly aligned (to the standard
11490     //   alignment of the memory type), so we don't need to do anything.
11491     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
11492     //   intrinsics, so, likewise, there's nothing to do.
11493     // - generic load/store instructions: the alignment is specified as an
11494     //   explicit operand, rather than implicitly as the standard alignment
11495     //   of the memory type (like the intrisics).  We need to change the
11496     //   memory type to match the explicit alignment.  That way, we don't
11497     //   generate non-standard-aligned ARMISD::VLDx nodes.
11498     if (isa<LSBaseSDNode>(N)) {
11499       if (Alignment == 0)
11500         Alignment = 1;
11501       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
11502         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
11503         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
11504         assert(!isLaneOp && "Unexpected generic load/store lane.");
11505         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
11506         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
11507       }
11508       // Don't set an explicit alignment on regular load/stores that we want
11509       // to transform to VLD/VST 1_UPD nodes.
11510       // This matches the behavior of regular load/stores, which only get an
11511       // explicit alignment if the MMO alignment is larger than the standard
11512       // alignment of the memory type.
11513       // Intrinsics, however, always get an explicit alignment, set to the
11514       // alignment of the MMO.
11515       Alignment = 1;
11516     }
11517 
11518     // Create the new updating load/store node.
11519     // First, create an SDVTList for the new updating node's results.
11520     EVT Tys[6];
11521     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
11522     unsigned n;
11523     for (n = 0; n < NumResultVecs; ++n)
11524       Tys[n] = AlignedVecTy;
11525     Tys[n++] = MVT::i32;
11526     Tys[n] = MVT::Other;
11527     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
11528 
11529     // Then, gather the new node's operands.
11530     SmallVector<SDValue, 8> Ops;
11531     Ops.push_back(N->getOperand(0)); // incoming chain
11532     Ops.push_back(N->getOperand(AddrOpIdx));
11533     Ops.push_back(Inc);
11534 
11535     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
11536       // Try to match the intrinsic's signature
11537       Ops.push_back(StN->getValue());
11538     } else {
11539       // Loads (and of course intrinsics) match the intrinsics' signature,
11540       // so just add all but the alignment operand.
11541       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
11542         Ops.push_back(N->getOperand(i));
11543     }
11544 
11545     // For all node types, the alignment operand is always the last one.
11546     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
11547 
11548     // If this is a non-standard-aligned STORE, the penultimate operand is the
11549     // stored value.  Bitcast it to the aligned type.
11550     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11551       SDValue &StVal = Ops[Ops.size()-2];
11552       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11553     }
11554 
11555     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11556     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11557                                            MemN->getMemOperand());
11558 
11559     // Update the uses.
11560     SmallVector<SDValue, 5> NewResults;
11561     for (unsigned i = 0; i < NumResultVecs; ++i)
11562       NewResults.push_back(SDValue(UpdN.getNode(), i));
11563 
11564     // If this is an non-standard-aligned LOAD, the first result is the loaded
11565     // value.  Bitcast it to the expected result type.
11566     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11567       SDValue &LdVal = NewResults[0];
11568       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11569     }
11570 
11571     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11572     DCI.CombineTo(N, NewResults);
11573     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11574 
11575     break;
11576   }
11577   return SDValue();
11578 }
11579 
11580 static SDValue PerformVLDCombine(SDNode *N,
11581                                  TargetLowering::DAGCombinerInfo &DCI) {
11582   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11583     return SDValue();
11584 
11585   return CombineBaseUpdate(N, DCI);
11586 }
11587 
11588 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11589 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11590 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
11591 /// return true.
11592 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11593   SelectionDAG &DAG = DCI.DAG;
11594   EVT VT = N->getValueType(0);
11595   // vldN-dup instructions only support 64-bit vectors for N > 1.
11596   if (!VT.is64BitVector())
11597     return false;
11598 
11599   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11600   SDNode *VLD = N->getOperand(0).getNode();
11601   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11602     return false;
11603   unsigned NumVecs = 0;
11604   unsigned NewOpc = 0;
11605   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11606   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11607     NumVecs = 2;
11608     NewOpc = ARMISD::VLD2DUP;
11609   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11610     NumVecs = 3;
11611     NewOpc = ARMISD::VLD3DUP;
11612   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11613     NumVecs = 4;
11614     NewOpc = ARMISD::VLD4DUP;
11615   } else {
11616     return false;
11617   }
11618 
11619   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11620   // numbers match the load.
11621   unsigned VLDLaneNo =
11622     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11623   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11624        UI != UE; ++UI) {
11625     // Ignore uses of the chain result.
11626     if (UI.getUse().getResNo() == NumVecs)
11627       continue;
11628     SDNode *User = *UI;
11629     if (User->getOpcode() != ARMISD::VDUPLANE ||
11630         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11631       return false;
11632   }
11633 
11634   // Create the vldN-dup node.
11635   EVT Tys[5];
11636   unsigned n;
11637   for (n = 0; n < NumVecs; ++n)
11638     Tys[n] = VT;
11639   Tys[n] = MVT::Other;
11640   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11641   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11642   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11643   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11644                                            Ops, VLDMemInt->getMemoryVT(),
11645                                            VLDMemInt->getMemOperand());
11646 
11647   // Update the uses.
11648   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11649        UI != UE; ++UI) {
11650     unsigned ResNo = UI.getUse().getResNo();
11651     // Ignore uses of the chain result.
11652     if (ResNo == NumVecs)
11653       continue;
11654     SDNode *User = *UI;
11655     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11656   }
11657 
11658   // Now the vldN-lane intrinsic is dead except for its chain result.
11659   // Update uses of the chain.
11660   std::vector<SDValue> VLDDupResults;
11661   for (unsigned n = 0; n < NumVecs; ++n)
11662     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11663   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11664   DCI.CombineTo(VLD, VLDDupResults);
11665 
11666   return true;
11667 }
11668 
11669 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11670 /// ARMISD::VDUPLANE.
11671 static SDValue PerformVDUPLANECombine(SDNode *N,
11672                                       TargetLowering::DAGCombinerInfo &DCI) {
11673   SDValue Op = N->getOperand(0);
11674 
11675   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11676   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11677   if (CombineVLDDUP(N, DCI))
11678     return SDValue(N, 0);
11679 
11680   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11681   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11682   while (Op.getOpcode() == ISD::BITCAST)
11683     Op = Op.getOperand(0);
11684   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11685     return SDValue();
11686 
11687   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11688   unsigned EltSize = Op.getScalarValueSizeInBits();
11689   // The canonical VMOV for a zero vector uses a 32-bit element size.
11690   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11691   unsigned EltBits;
11692   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11693     EltSize = 8;
11694   EVT VT = N->getValueType(0);
11695   if (EltSize > VT.getScalarSizeInBits())
11696     return SDValue();
11697 
11698   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11699 }
11700 
11701 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11702 static SDValue PerformVDUPCombine(SDNode *N,
11703                                   TargetLowering::DAGCombinerInfo &DCI) {
11704   SelectionDAG &DAG = DCI.DAG;
11705   SDValue Op = N->getOperand(0);
11706 
11707   // Match VDUP(LOAD) -> VLD1DUP.
11708   // We match this pattern here rather than waiting for isel because the
11709   // transform is only legal for unindexed loads.
11710   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11711   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11712       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11713     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11714                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11715     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11716     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11717                                              Ops, LD->getMemoryVT(),
11718                                              LD->getMemOperand());
11719     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11720     return VLDDup;
11721   }
11722 
11723   return SDValue();
11724 }
11725 
11726 static SDValue PerformLOADCombine(SDNode *N,
11727                                   TargetLowering::DAGCombinerInfo &DCI) {
11728   EVT VT = N->getValueType(0);
11729 
11730   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11731   if (ISD::isNormalLoad(N) && VT.isVector() &&
11732       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11733     return CombineBaseUpdate(N, DCI);
11734 
11735   return SDValue();
11736 }
11737 
11738 /// PerformSTORECombine - Target-specific dag combine xforms for
11739 /// ISD::STORE.
11740 static SDValue PerformSTORECombine(SDNode *N,
11741                                    TargetLowering::DAGCombinerInfo &DCI) {
11742   StoreSDNode *St = cast<StoreSDNode>(N);
11743   if (St->isVolatile())
11744     return SDValue();
11745 
11746   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11747   // pack all of the elements in one place.  Next, store to memory in fewer
11748   // chunks.
11749   SDValue StVal = St->getValue();
11750   EVT VT = StVal.getValueType();
11751   if (St->isTruncatingStore() && VT.isVector()) {
11752     SelectionDAG &DAG = DCI.DAG;
11753     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11754     EVT StVT = St->getMemoryVT();
11755     unsigned NumElems = VT.getVectorNumElements();
11756     assert(StVT != VT && "Cannot truncate to the same type");
11757     unsigned FromEltSz = VT.getScalarSizeInBits();
11758     unsigned ToEltSz = StVT.getScalarSizeInBits();
11759 
11760     // From, To sizes and ElemCount must be pow of two
11761     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11762 
11763     // We are going to use the original vector elt for storing.
11764     // Accumulated smaller vector elements must be a multiple of the store size.
11765     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11766 
11767     unsigned SizeRatio  = FromEltSz / ToEltSz;
11768     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11769 
11770     // Create a type on which we perform the shuffle.
11771     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11772                                      NumElems*SizeRatio);
11773     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11774 
11775     SDLoc DL(St);
11776     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11777     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11778     for (unsigned i = 0; i < NumElems; ++i)
11779       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11780                           ? (i + 1) * SizeRatio - 1
11781                           : i * SizeRatio;
11782 
11783     // Can't shuffle using an illegal type.
11784     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11785 
11786     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11787                                 DAG.getUNDEF(WideVec.getValueType()),
11788                                 ShuffleVec);
11789     // At this point all of the data is stored at the bottom of the
11790     // register. We now need to save it to mem.
11791 
11792     // Find the largest store unit
11793     MVT StoreType = MVT::i8;
11794     for (MVT Tp : MVT::integer_valuetypes()) {
11795       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11796         StoreType = Tp;
11797     }
11798     // Didn't find a legal store type.
11799     if (!TLI.isTypeLegal(StoreType))
11800       return SDValue();
11801 
11802     // Bitcast the original vector into a vector of store-size units
11803     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11804             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11805     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11806     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11807     SmallVector<SDValue, 8> Chains;
11808     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11809                                         TLI.getPointerTy(DAG.getDataLayout()));
11810     SDValue BasePtr = St->getBasePtr();
11811 
11812     // Perform one or more big stores into memory.
11813     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11814     for (unsigned I = 0; I < E; I++) {
11815       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11816                                    StoreType, ShuffWide,
11817                                    DAG.getIntPtrConstant(I, DL));
11818       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
11819                                 St->getPointerInfo(), St->getAlignment(),
11820                                 St->getMemOperand()->getFlags());
11821       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
11822                             Increment);
11823       Chains.push_back(Ch);
11824     }
11825     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11826   }
11827 
11828   if (!ISD::isNormalStore(St))
11829     return SDValue();
11830 
11831   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
11832   // ARM stores of arguments in the same cache line.
11833   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
11834       StVal.getNode()->hasOneUse()) {
11835     SelectionDAG  &DAG = DCI.DAG;
11836     bool isBigEndian = DAG.getDataLayout().isBigEndian();
11837     SDLoc DL(St);
11838     SDValue BasePtr = St->getBasePtr();
11839     SDValue NewST1 = DAG.getStore(
11840         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
11841         BasePtr, St->getPointerInfo(), St->getAlignment(),
11842         St->getMemOperand()->getFlags());
11843 
11844     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11845                                     DAG.getConstant(4, DL, MVT::i32));
11846     return DAG.getStore(NewST1.getValue(0), DL,
11847                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
11848                         OffsetPtr, St->getPointerInfo(),
11849                         std::min(4U, St->getAlignment() / 2),
11850                         St->getMemOperand()->getFlags());
11851   }
11852 
11853   if (StVal.getValueType() == MVT::i64 &&
11854       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11855 
11856     // Bitcast an i64 store extracted from a vector to f64.
11857     // Otherwise, the i64 value will be legalized to a pair of i32 values.
11858     SelectionDAG &DAG = DCI.DAG;
11859     SDLoc dl(StVal);
11860     SDValue IntVec = StVal.getOperand(0);
11861     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11862                                    IntVec.getValueType().getVectorNumElements());
11863     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
11864     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11865                                  Vec, StVal.getOperand(1));
11866     dl = SDLoc(N);
11867     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
11868     // Make the DAGCombiner fold the bitcasts.
11869     DCI.AddToWorklist(Vec.getNode());
11870     DCI.AddToWorklist(ExtElt.getNode());
11871     DCI.AddToWorklist(V.getNode());
11872     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
11873                         St->getPointerInfo(), St->getAlignment(),
11874                         St->getMemOperand()->getFlags(), St->getAAInfo());
11875   }
11876 
11877   // If this is a legal vector store, try to combine it into a VST1_UPD.
11878   if (ISD::isNormalStore(N) && VT.isVector() &&
11879       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11880     return CombineBaseUpdate(N, DCI);
11881 
11882   return SDValue();
11883 }
11884 
11885 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11886 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11887 /// when the VMUL has a constant operand that is a power of 2.
11888 ///
11889 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11890 ///  vmul.f32        d16, d17, d16
11891 ///  vcvt.s32.f32    d16, d16
11892 /// becomes:
11893 ///  vcvt.s32.f32    d16, d16, #3
11894 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11895                                   const ARMSubtarget *Subtarget) {
11896   if (!Subtarget->hasNEON())
11897     return SDValue();
11898 
11899   SDValue Op = N->getOperand(0);
11900   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11901       Op.getOpcode() != ISD::FMUL)
11902     return SDValue();
11903 
11904   SDValue ConstVec = Op->getOperand(1);
11905   if (!isa<BuildVectorSDNode>(ConstVec))
11906     return SDValue();
11907 
11908   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11909   uint32_t FloatBits = FloatTy.getSizeInBits();
11910   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11911   uint32_t IntBits = IntTy.getSizeInBits();
11912   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11913   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11914     // These instructions only exist converting from f32 to i32. We can handle
11915     // smaller integers by generating an extra truncate, but larger ones would
11916     // be lossy. We also can't handle more then 4 lanes, since these intructions
11917     // only support v2i32/v4i32 types.
11918     return SDValue();
11919   }
11920 
11921   BitVector UndefElements;
11922   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11923   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11924   if (C == -1 || C == 0 || C > 32)
11925     return SDValue();
11926 
11927   SDLoc dl(N);
11928   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
11929   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
11930     Intrinsic::arm_neon_vcvtfp2fxu;
11931   SDValue FixConv = DAG.getNode(
11932       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11933       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
11934       DAG.getConstant(C, dl, MVT::i32));
11935 
11936   if (IntBits < FloatBits)
11937     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
11938 
11939   return FixConv;
11940 }
11941 
11942 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
11943 /// can replace combinations of VCVT (integer to floating-point) and VDIV
11944 /// when the VDIV has a constant operand that is a power of 2.
11945 ///
11946 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11947 ///  vcvt.f32.s32    d16, d16
11948 ///  vdiv.f32        d16, d17, d16
11949 /// becomes:
11950 ///  vcvt.f32.s32    d16, d16, #3
11951 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
11952                                   const ARMSubtarget *Subtarget) {
11953   if (!Subtarget->hasNEON())
11954     return SDValue();
11955 
11956   SDValue Op = N->getOperand(0);
11957   unsigned OpOpcode = Op.getNode()->getOpcode();
11958   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
11959       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
11960     return SDValue();
11961 
11962   SDValue ConstVec = N->getOperand(1);
11963   if (!isa<BuildVectorSDNode>(ConstVec))
11964     return SDValue();
11965 
11966   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11967   uint32_t FloatBits = FloatTy.getSizeInBits();
11968   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11969   uint32_t IntBits = IntTy.getSizeInBits();
11970   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11971   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11972     // These instructions only exist converting from i32 to f32. We can handle
11973     // smaller integers by generating an extra extend, but larger ones would
11974     // be lossy. We also can't handle more then 4 lanes, since these intructions
11975     // only support v2i32/v4i32 types.
11976     return SDValue();
11977   }
11978 
11979   BitVector UndefElements;
11980   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11981   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11982   if (C == -1 || C == 0 || C > 32)
11983     return SDValue();
11984 
11985   SDLoc dl(N);
11986   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
11987   SDValue ConvInput = Op.getOperand(0);
11988   if (IntBits < FloatBits)
11989     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
11990                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11991                             ConvInput);
11992 
11993   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
11994     Intrinsic::arm_neon_vcvtfxu2fp;
11995   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
11996                      Op.getValueType(),
11997                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
11998                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
11999 }
12000 
12001 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
12002 /// operand of a vector shift operation, where all the elements of the
12003 /// build_vector must have the same constant integer value.
12004 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
12005   // Ignore bit_converts.
12006   while (Op.getOpcode() == ISD::BITCAST)
12007     Op = Op.getOperand(0);
12008   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
12009   APInt SplatBits, SplatUndef;
12010   unsigned SplatBitSize;
12011   bool HasAnyUndefs;
12012   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
12013                                       HasAnyUndefs, ElementBits) ||
12014       SplatBitSize > ElementBits)
12015     return false;
12016   Cnt = SplatBits.getSExtValue();
12017   return true;
12018 }
12019 
12020 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
12021 /// operand of a vector shift left operation.  That value must be in the range:
12022 ///   0 <= Value < ElementBits for a left shift; or
12023 ///   0 <= Value <= ElementBits for a long left shift.
12024 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
12025   assert(VT.isVector() && "vector shift count is not a vector type");
12026   int64_t ElementBits = VT.getScalarSizeInBits();
12027   if (! getVShiftImm(Op, ElementBits, Cnt))
12028     return false;
12029   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
12030 }
12031 
12032 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
12033 /// operand of a vector shift right operation.  For a shift opcode, the value
12034 /// is positive, but for an intrinsic the value count must be negative. The
12035 /// absolute value must be in the range:
12036 ///   1 <= |Value| <= ElementBits for a right shift; or
12037 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
12038 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
12039                          int64_t &Cnt) {
12040   assert(VT.isVector() && "vector shift count is not a vector type");
12041   int64_t ElementBits = VT.getScalarSizeInBits();
12042   if (! getVShiftImm(Op, ElementBits, Cnt))
12043     return false;
12044   if (!isIntrinsic)
12045     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
12046   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
12047     Cnt = -Cnt;
12048     return true;
12049   }
12050   return false;
12051 }
12052 
12053 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
12054 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
12055   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12056   switch (IntNo) {
12057   default:
12058     // Don't do anything for most intrinsics.
12059     break;
12060 
12061   // Vector shifts: check for immediate versions and lower them.
12062   // Note: This is done during DAG combining instead of DAG legalizing because
12063   // the build_vectors for 64-bit vector element shift counts are generally
12064   // not legal, and it is hard to see their values after they get legalized to
12065   // loads from a constant pool.
12066   case Intrinsic::arm_neon_vshifts:
12067   case Intrinsic::arm_neon_vshiftu:
12068   case Intrinsic::arm_neon_vrshifts:
12069   case Intrinsic::arm_neon_vrshiftu:
12070   case Intrinsic::arm_neon_vrshiftn:
12071   case Intrinsic::arm_neon_vqshifts:
12072   case Intrinsic::arm_neon_vqshiftu:
12073   case Intrinsic::arm_neon_vqshiftsu:
12074   case Intrinsic::arm_neon_vqshiftns:
12075   case Intrinsic::arm_neon_vqshiftnu:
12076   case Intrinsic::arm_neon_vqshiftnsu:
12077   case Intrinsic::arm_neon_vqrshiftns:
12078   case Intrinsic::arm_neon_vqrshiftnu:
12079   case Intrinsic::arm_neon_vqrshiftnsu: {
12080     EVT VT = N->getOperand(1).getValueType();
12081     int64_t Cnt;
12082     unsigned VShiftOpc = 0;
12083 
12084     switch (IntNo) {
12085     case Intrinsic::arm_neon_vshifts:
12086     case Intrinsic::arm_neon_vshiftu:
12087       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
12088         VShiftOpc = ARMISD::VSHL;
12089         break;
12090       }
12091       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
12092         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
12093                      ARMISD::VSHRs : ARMISD::VSHRu);
12094         break;
12095       }
12096       return SDValue();
12097 
12098     case Intrinsic::arm_neon_vrshifts:
12099     case Intrinsic::arm_neon_vrshiftu:
12100       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
12101         break;
12102       return SDValue();
12103 
12104     case Intrinsic::arm_neon_vqshifts:
12105     case Intrinsic::arm_neon_vqshiftu:
12106       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12107         break;
12108       return SDValue();
12109 
12110     case Intrinsic::arm_neon_vqshiftsu:
12111       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12112         break;
12113       llvm_unreachable("invalid shift count for vqshlu intrinsic");
12114 
12115     case Intrinsic::arm_neon_vrshiftn:
12116     case Intrinsic::arm_neon_vqshiftns:
12117     case Intrinsic::arm_neon_vqshiftnu:
12118     case Intrinsic::arm_neon_vqshiftnsu:
12119     case Intrinsic::arm_neon_vqrshiftns:
12120     case Intrinsic::arm_neon_vqrshiftnu:
12121     case Intrinsic::arm_neon_vqrshiftnsu:
12122       // Narrowing shifts require an immediate right shift.
12123       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
12124         break;
12125       llvm_unreachable("invalid shift count for narrowing vector shift "
12126                        "intrinsic");
12127 
12128     default:
12129       llvm_unreachable("unhandled vector shift");
12130     }
12131 
12132     switch (IntNo) {
12133     case Intrinsic::arm_neon_vshifts:
12134     case Intrinsic::arm_neon_vshiftu:
12135       // Opcode already set above.
12136       break;
12137     case Intrinsic::arm_neon_vrshifts:
12138       VShiftOpc = ARMISD::VRSHRs; break;
12139     case Intrinsic::arm_neon_vrshiftu:
12140       VShiftOpc = ARMISD::VRSHRu; break;
12141     case Intrinsic::arm_neon_vrshiftn:
12142       VShiftOpc = ARMISD::VRSHRN; break;
12143     case Intrinsic::arm_neon_vqshifts:
12144       VShiftOpc = ARMISD::VQSHLs; break;
12145     case Intrinsic::arm_neon_vqshiftu:
12146       VShiftOpc = ARMISD::VQSHLu; break;
12147     case Intrinsic::arm_neon_vqshiftsu:
12148       VShiftOpc = ARMISD::VQSHLsu; break;
12149     case Intrinsic::arm_neon_vqshiftns:
12150       VShiftOpc = ARMISD::VQSHRNs; break;
12151     case Intrinsic::arm_neon_vqshiftnu:
12152       VShiftOpc = ARMISD::VQSHRNu; break;
12153     case Intrinsic::arm_neon_vqshiftnsu:
12154       VShiftOpc = ARMISD::VQSHRNsu; break;
12155     case Intrinsic::arm_neon_vqrshiftns:
12156       VShiftOpc = ARMISD::VQRSHRNs; break;
12157     case Intrinsic::arm_neon_vqrshiftnu:
12158       VShiftOpc = ARMISD::VQRSHRNu; break;
12159     case Intrinsic::arm_neon_vqrshiftnsu:
12160       VShiftOpc = ARMISD::VQRSHRNsu; break;
12161     }
12162 
12163     SDLoc dl(N);
12164     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12165                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
12166   }
12167 
12168   case Intrinsic::arm_neon_vshiftins: {
12169     EVT VT = N->getOperand(1).getValueType();
12170     int64_t Cnt;
12171     unsigned VShiftOpc = 0;
12172 
12173     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
12174       VShiftOpc = ARMISD::VSLI;
12175     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
12176       VShiftOpc = ARMISD::VSRI;
12177     else {
12178       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
12179     }
12180 
12181     SDLoc dl(N);
12182     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12183                        N->getOperand(1), N->getOperand(2),
12184                        DAG.getConstant(Cnt, dl, MVT::i32));
12185   }
12186 
12187   case Intrinsic::arm_neon_vqrshifts:
12188   case Intrinsic::arm_neon_vqrshiftu:
12189     // No immediate versions of these to check for.
12190     break;
12191   }
12192 
12193   return SDValue();
12194 }
12195 
12196 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
12197 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
12198 /// combining instead of DAG legalizing because the build_vectors for 64-bit
12199 /// vector element shift counts are generally not legal, and it is hard to see
12200 /// their values after they get legalized to loads from a constant pool.
12201 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
12202                                    const ARMSubtarget *ST) {
12203   EVT VT = N->getValueType(0);
12204   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
12205     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
12206     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
12207     SDValue N1 = N->getOperand(1);
12208     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
12209       SDValue N0 = N->getOperand(0);
12210       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
12211           DAG.MaskedValueIsZero(N0.getOperand(0),
12212                                 APInt::getHighBitsSet(32, 16)))
12213         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
12214     }
12215   }
12216 
12217   // Nothing to be done for scalar shifts.
12218   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12219   if (!VT.isVector() || !TLI.isTypeLegal(VT))
12220     return SDValue();
12221 
12222   assert(ST->hasNEON() && "unexpected vector shift");
12223   int64_t Cnt;
12224 
12225   switch (N->getOpcode()) {
12226   default: llvm_unreachable("unexpected shift opcode");
12227 
12228   case ISD::SHL:
12229     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
12230       SDLoc dl(N);
12231       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
12232                          DAG.getConstant(Cnt, dl, MVT::i32));
12233     }
12234     break;
12235 
12236   case ISD::SRA:
12237   case ISD::SRL:
12238     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
12239       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
12240                             ARMISD::VSHRs : ARMISD::VSHRu);
12241       SDLoc dl(N);
12242       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
12243                          DAG.getConstant(Cnt, dl, MVT::i32));
12244     }
12245   }
12246   return SDValue();
12247 }
12248 
12249 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
12250 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
12251 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
12252                                     const ARMSubtarget *ST) {
12253   SDValue N0 = N->getOperand(0);
12254 
12255   // Check for sign- and zero-extensions of vector extract operations of 8-
12256   // and 16-bit vector elements.  NEON supports these directly.  They are
12257   // handled during DAG combining because type legalization will promote them
12258   // to 32-bit types and it is messy to recognize the operations after that.
12259   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12260     SDValue Vec = N0.getOperand(0);
12261     SDValue Lane = N0.getOperand(1);
12262     EVT VT = N->getValueType(0);
12263     EVT EltVT = N0.getValueType();
12264     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12265 
12266     if (VT == MVT::i32 &&
12267         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
12268         TLI.isTypeLegal(Vec.getValueType()) &&
12269         isa<ConstantSDNode>(Lane)) {
12270 
12271       unsigned Opc = 0;
12272       switch (N->getOpcode()) {
12273       default: llvm_unreachable("unexpected opcode");
12274       case ISD::SIGN_EXTEND:
12275         Opc = ARMISD::VGETLANEs;
12276         break;
12277       case ISD::ZERO_EXTEND:
12278       case ISD::ANY_EXTEND:
12279         Opc = ARMISD::VGETLANEu;
12280         break;
12281       }
12282       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
12283     }
12284   }
12285 
12286   return SDValue();
12287 }
12288 
12289 static const APInt *isPowerOf2Constant(SDValue V) {
12290   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12291   if (!C)
12292     return nullptr;
12293   const APInt *CV = &C->getAPIntValue();
12294   return CV->isPowerOf2() ? CV : nullptr;
12295 }
12296 
12297 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
12298   // If we have a CMOV, OR and AND combination such as:
12299   //   if (x & CN)
12300   //     y |= CM;
12301   //
12302   // And:
12303   //   * CN is a single bit;
12304   //   * All bits covered by CM are known zero in y
12305   //
12306   // Then we can convert this into a sequence of BFI instructions. This will
12307   // always be a win if CM is a single bit, will always be no worse than the
12308   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
12309   // three bits (due to the extra IT instruction).
12310 
12311   SDValue Op0 = CMOV->getOperand(0);
12312   SDValue Op1 = CMOV->getOperand(1);
12313   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
12314   auto CC = CCNode->getAPIntValue().getLimitedValue();
12315   SDValue CmpZ = CMOV->getOperand(4);
12316 
12317   // The compare must be against zero.
12318   if (!isNullConstant(CmpZ->getOperand(1)))
12319     return SDValue();
12320 
12321   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
12322   SDValue And = CmpZ->getOperand(0);
12323   if (And->getOpcode() != ISD::AND)
12324     return SDValue();
12325   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
12326   if (!AndC)
12327     return SDValue();
12328   SDValue X = And->getOperand(0);
12329 
12330   if (CC == ARMCC::EQ) {
12331     // We're performing an "equal to zero" compare. Swap the operands so we
12332     // canonicalize on a "not equal to zero" compare.
12333     std::swap(Op0, Op1);
12334   } else {
12335     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
12336   }
12337 
12338   if (Op1->getOpcode() != ISD::OR)
12339     return SDValue();
12340 
12341   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
12342   if (!OrC)
12343     return SDValue();
12344   SDValue Y = Op1->getOperand(0);
12345 
12346   if (Op0 != Y)
12347     return SDValue();
12348 
12349   // Now, is it profitable to continue?
12350   APInt OrCI = OrC->getAPIntValue();
12351   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
12352   if (OrCI.countPopulation() > Heuristic)
12353     return SDValue();
12354 
12355   // Lastly, can we determine that the bits defined by OrCI
12356   // are zero in Y?
12357   KnownBits Known;
12358   DAG.computeKnownBits(Y, Known);
12359   if ((OrCI & Known.Zero) != OrCI)
12360     return SDValue();
12361 
12362   // OK, we can do the combine.
12363   SDValue V = Y;
12364   SDLoc dl(X);
12365   EVT VT = X.getValueType();
12366   unsigned BitInX = AndC->logBase2();
12367 
12368   if (BitInX != 0) {
12369     // We must shift X first.
12370     X = DAG.getNode(ISD::SRL, dl, VT, X,
12371                     DAG.getConstant(BitInX, dl, VT));
12372   }
12373 
12374   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
12375        BitInY < NumActiveBits; ++BitInY) {
12376     if (OrCI[BitInY] == 0)
12377       continue;
12378     APInt Mask(VT.getSizeInBits(), 0);
12379     Mask.setBit(BitInY);
12380     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
12381                     // Confusingly, the operand is an *inverted* mask.
12382                     DAG.getConstant(~Mask, dl, VT));
12383   }
12384 
12385   return V;
12386 }
12387 
12388 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
12389 SDValue
12390 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
12391   SDValue Cmp = N->getOperand(4);
12392   if (Cmp.getOpcode() != ARMISD::CMPZ)
12393     // Only looking at NE cases.
12394     return SDValue();
12395 
12396   EVT VT = N->getValueType(0);
12397   SDLoc dl(N);
12398   SDValue LHS = Cmp.getOperand(0);
12399   SDValue RHS = Cmp.getOperand(1);
12400   SDValue Chain = N->getOperand(0);
12401   SDValue BB = N->getOperand(1);
12402   SDValue ARMcc = N->getOperand(2);
12403   ARMCC::CondCodes CC =
12404     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12405 
12406   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
12407   // -> (brcond Chain BB CC CPSR Cmp)
12408   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
12409       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
12410       LHS->getOperand(0)->hasOneUse()) {
12411     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
12412     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
12413     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12414     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12415     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
12416         (LHS01C && LHS01C->getZExtValue() == 1) &&
12417         (LHS1C && LHS1C->getZExtValue() == 1) &&
12418         (RHSC && RHSC->getZExtValue() == 0)) {
12419       return DAG.getNode(
12420           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
12421           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
12422     }
12423   }
12424 
12425   return SDValue();
12426 }
12427 
12428 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
12429 SDValue
12430 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
12431   SDValue Cmp = N->getOperand(4);
12432   if (Cmp.getOpcode() != ARMISD::CMPZ)
12433     // Only looking at EQ and NE cases.
12434     return SDValue();
12435 
12436   EVT VT = N->getValueType(0);
12437   SDLoc dl(N);
12438   SDValue LHS = Cmp.getOperand(0);
12439   SDValue RHS = Cmp.getOperand(1);
12440   SDValue FalseVal = N->getOperand(0);
12441   SDValue TrueVal = N->getOperand(1);
12442   SDValue ARMcc = N->getOperand(2);
12443   ARMCC::CondCodes CC =
12444     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12445 
12446   // BFI is only available on V6T2+.
12447   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
12448     SDValue R = PerformCMOVToBFICombine(N, DAG);
12449     if (R)
12450       return R;
12451   }
12452 
12453   // Simplify
12454   //   mov     r1, r0
12455   //   cmp     r1, x
12456   //   mov     r0, y
12457   //   moveq   r0, x
12458   // to
12459   //   cmp     r0, x
12460   //   movne   r0, y
12461   //
12462   //   mov     r1, r0
12463   //   cmp     r1, x
12464   //   mov     r0, x
12465   //   movne   r0, y
12466   // to
12467   //   cmp     r0, x
12468   //   movne   r0, y
12469   /// FIXME: Turn this into a target neutral optimization?
12470   SDValue Res;
12471   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
12472     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
12473                       N->getOperand(3), Cmp);
12474   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
12475     SDValue ARMcc;
12476     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
12477     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
12478                       N->getOperand(3), NewCmp);
12479   }
12480 
12481   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
12482   // -> (cmov F T CC CPSR Cmp)
12483   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
12484     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
12485     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12486     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12487     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
12488         (LHS1C && LHS1C->getZExtValue() == 1) &&
12489         (RHSC && RHSC->getZExtValue() == 0)) {
12490       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
12491                          LHS->getOperand(2), LHS->getOperand(3),
12492                          LHS->getOperand(4));
12493     }
12494   }
12495 
12496   if (Res.getNode()) {
12497     KnownBits Known;
12498     DAG.computeKnownBits(SDValue(N,0), Known);
12499     // Capture demanded bits information that would be otherwise lost.
12500     if (Known.Zero == 0xfffffffe)
12501       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12502                         DAG.getValueType(MVT::i1));
12503     else if (Known.Zero == 0xffffff00)
12504       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12505                         DAG.getValueType(MVT::i8));
12506     else if (Known.Zero == 0xffff0000)
12507       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12508                         DAG.getValueType(MVT::i16));
12509   }
12510 
12511   return Res;
12512 }
12513 
12514 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
12515                                              DAGCombinerInfo &DCI) const {
12516   switch (N->getOpcode()) {
12517   default: break;
12518   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
12519   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
12520   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
12521   case ISD::SUB:        return PerformSUBCombine(N, DCI);
12522   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
12523   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
12524   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
12525   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
12526   case ARMISD::ADDC:
12527   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
12528   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
12529   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
12530   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
12531   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
12532   case ISD::STORE:      return PerformSTORECombine(N, DCI);
12533   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
12534   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
12535   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
12536   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
12537   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
12538   case ISD::FP_TO_SINT:
12539   case ISD::FP_TO_UINT:
12540     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
12541   case ISD::FDIV:
12542     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
12543   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
12544   case ISD::SHL:
12545   case ISD::SRA:
12546   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
12547   case ISD::SIGN_EXTEND:
12548   case ISD::ZERO_EXTEND:
12549   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
12550   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
12551   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
12552   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
12553   case ARMISD::VLD1DUP:
12554   case ARMISD::VLD2DUP:
12555   case ARMISD::VLD3DUP:
12556   case ARMISD::VLD4DUP:
12557     return PerformVLDCombine(N, DCI);
12558   case ARMISD::BUILD_VECTOR:
12559     return PerformARMBUILD_VECTORCombine(N, DCI);
12560   case ARMISD::SMULWB: {
12561     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12562     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12563     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12564       return SDValue();
12565     break;
12566   }
12567   case ARMISD::SMULWT: {
12568     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12569     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12570     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12571       return SDValue();
12572     break;
12573   }
12574   case ARMISD::SMLALBB: {
12575     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12576     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12577     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12578         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12579       return SDValue();
12580     break;
12581   }
12582   case ARMISD::SMLALBT: {
12583     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12584     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12585     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12586     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12587     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12588         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12589       return SDValue();
12590     break;
12591   }
12592   case ARMISD::SMLALTB: {
12593     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12594     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12595     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12596     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12597     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12598         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12599       return SDValue();
12600     break;
12601   }
12602   case ARMISD::SMLALTT: {
12603     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12604     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12605     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12606         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12607       return SDValue();
12608     break;
12609   }
12610   case ISD::INTRINSIC_VOID:
12611   case ISD::INTRINSIC_W_CHAIN:
12612     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12613     case Intrinsic::arm_neon_vld1:
12614     case Intrinsic::arm_neon_vld2:
12615     case Intrinsic::arm_neon_vld3:
12616     case Intrinsic::arm_neon_vld4:
12617     case Intrinsic::arm_neon_vld2lane:
12618     case Intrinsic::arm_neon_vld3lane:
12619     case Intrinsic::arm_neon_vld4lane:
12620     case Intrinsic::arm_neon_vst1:
12621     case Intrinsic::arm_neon_vst2:
12622     case Intrinsic::arm_neon_vst3:
12623     case Intrinsic::arm_neon_vst4:
12624     case Intrinsic::arm_neon_vst2lane:
12625     case Intrinsic::arm_neon_vst3lane:
12626     case Intrinsic::arm_neon_vst4lane:
12627       return PerformVLDCombine(N, DCI);
12628     default: break;
12629     }
12630     break;
12631   }
12632   return SDValue();
12633 }
12634 
12635 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12636                                                           EVT VT) const {
12637   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12638 }
12639 
12640 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12641                                                        unsigned,
12642                                                        unsigned,
12643                                                        bool *Fast) const {
12644   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12645   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12646 
12647   switch (VT.getSimpleVT().SimpleTy) {
12648   default:
12649     return false;
12650   case MVT::i8:
12651   case MVT::i16:
12652   case MVT::i32: {
12653     // Unaligned access can use (for example) LRDB, LRDH, LDR
12654     if (AllowsUnaligned) {
12655       if (Fast)
12656         *Fast = Subtarget->hasV7Ops();
12657       return true;
12658     }
12659     return false;
12660   }
12661   case MVT::f64:
12662   case MVT::v2f64: {
12663     // For any little-endian targets with neon, we can support unaligned ld/st
12664     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12665     // A big-endian target may also explicitly support unaligned accesses
12666     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12667       if (Fast)
12668         *Fast = true;
12669       return true;
12670     }
12671     return false;
12672   }
12673   }
12674 }
12675 
12676 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12677                        unsigned AlignCheck) {
12678   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12679           (DstAlign == 0 || DstAlign % AlignCheck == 0));
12680 }
12681 
12682 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12683                                            unsigned DstAlign, unsigned SrcAlign,
12684                                            bool IsMemset, bool ZeroMemset,
12685                                            bool MemcpyStrSrc,
12686                                            MachineFunction &MF) const {
12687   const Function &F = MF.getFunction();
12688 
12689   // See if we can use NEON instructions for this...
12690   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12691       !F.hasFnAttribute(Attribute::NoImplicitFloat)) {
12692     bool Fast;
12693     if (Size >= 16 &&
12694         (memOpAlign(SrcAlign, DstAlign, 16) ||
12695          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12696       return MVT::v2f64;
12697     } else if (Size >= 8 &&
12698                (memOpAlign(SrcAlign, DstAlign, 8) ||
12699                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12700                  Fast))) {
12701       return MVT::f64;
12702     }
12703   }
12704 
12705   // Let the target-independent logic figure it out.
12706   return MVT::Other;
12707 }
12708 
12709 // 64-bit integers are split into their high and low parts and held in two
12710 // different registers, so the trunc is free since the low register can just
12711 // be used.
12712 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
12713   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
12714     return false;
12715   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
12716   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
12717   return (SrcBits == 64 && DestBits == 32);
12718 }
12719 
12720 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
12721   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
12722       !DstVT.isInteger())
12723     return false;
12724   unsigned SrcBits = SrcVT.getSizeInBits();
12725   unsigned DestBits = DstVT.getSizeInBits();
12726   return (SrcBits == 64 && DestBits == 32);
12727 }
12728 
12729 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12730   if (Val.getOpcode() != ISD::LOAD)
12731     return false;
12732 
12733   EVT VT1 = Val.getValueType();
12734   if (!VT1.isSimple() || !VT1.isInteger() ||
12735       !VT2.isSimple() || !VT2.isInteger())
12736     return false;
12737 
12738   switch (VT1.getSimpleVT().SimpleTy) {
12739   default: break;
12740   case MVT::i1:
12741   case MVT::i8:
12742   case MVT::i16:
12743     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
12744     return true;
12745   }
12746 
12747   return false;
12748 }
12749 
12750 bool ARMTargetLowering::isFNegFree(EVT VT) const {
12751   if (!VT.isSimple())
12752     return false;
12753 
12754   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
12755   // negate values directly (fneg is free). So, we don't want to let the DAG
12756   // combiner rewrite fneg into xors and some other instructions.  For f16 and
12757   // FullFP16 argument passing, some bitcast nodes may be introduced,
12758   // triggering this DAG combine rewrite, so we are avoiding that with this.
12759   switch (VT.getSimpleVT().SimpleTy) {
12760   default: break;
12761   case MVT::f16:
12762     return Subtarget->hasFullFP16();
12763   }
12764 
12765   return false;
12766 }
12767 
12768 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
12769   EVT VT = ExtVal.getValueType();
12770 
12771   if (!isTypeLegal(VT))
12772     return false;
12773 
12774   // Don't create a loadext if we can fold the extension into a wide/long
12775   // instruction.
12776   // If there's more than one user instruction, the loadext is desirable no
12777   // matter what.  There can be two uses by the same instruction.
12778   if (ExtVal->use_empty() ||
12779       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
12780     return true;
12781 
12782   SDNode *U = *ExtVal->use_begin();
12783   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
12784        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
12785     return false;
12786 
12787   return true;
12788 }
12789 
12790 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
12791   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12792     return false;
12793 
12794   if (!isTypeLegal(EVT::getEVT(Ty1)))
12795     return false;
12796 
12797   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
12798 
12799   // Assuming the caller doesn't have a zeroext or signext return parameter,
12800   // truncation all the way down to i1 is valid.
12801   return true;
12802 }
12803 
12804 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
12805                                                 const AddrMode &AM, Type *Ty,
12806                                                 unsigned AS) const {
12807   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
12808     if (Subtarget->hasFPAO())
12809       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
12810     return 0;
12811   }
12812   return -1;
12813 }
12814 
12815 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
12816   if (V < 0)
12817     return false;
12818 
12819   unsigned Scale = 1;
12820   switch (VT.getSimpleVT().SimpleTy) {
12821   default: return false;
12822   case MVT::i1:
12823   case MVT::i8:
12824     // Scale == 1;
12825     break;
12826   case MVT::i16:
12827     // Scale == 2;
12828     Scale = 2;
12829     break;
12830   case MVT::i32:
12831     // Scale == 4;
12832     Scale = 4;
12833     break;
12834   }
12835 
12836   if ((V & (Scale - 1)) != 0)
12837     return false;
12838   V /= Scale;
12839   return V == (V & ((1LL << 5) - 1));
12840 }
12841 
12842 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
12843                                       const ARMSubtarget *Subtarget) {
12844   bool isNeg = false;
12845   if (V < 0) {
12846     isNeg = true;
12847     V = - V;
12848   }
12849 
12850   switch (VT.getSimpleVT().SimpleTy) {
12851   default: return false;
12852   case MVT::i1:
12853   case MVT::i8:
12854   case MVT::i16:
12855   case MVT::i32:
12856     // + imm12 or - imm8
12857     if (isNeg)
12858       return V == (V & ((1LL << 8) - 1));
12859     return V == (V & ((1LL << 12) - 1));
12860   case MVT::f32:
12861   case MVT::f64:
12862     // Same as ARM mode. FIXME: NEON?
12863     if (!Subtarget->hasVFP2())
12864       return false;
12865     if ((V & 3) != 0)
12866       return false;
12867     V >>= 2;
12868     return V == (V & ((1LL << 8) - 1));
12869   }
12870 }
12871 
12872 /// isLegalAddressImmediate - Return true if the integer value can be used
12873 /// as the offset of the target addressing mode for load / store of the
12874 /// given type.
12875 static bool isLegalAddressImmediate(int64_t V, EVT VT,
12876                                     const ARMSubtarget *Subtarget) {
12877   if (V == 0)
12878     return true;
12879 
12880   if (!VT.isSimple())
12881     return false;
12882 
12883   if (Subtarget->isThumb1Only())
12884     return isLegalT1AddressImmediate(V, VT);
12885   else if (Subtarget->isThumb2())
12886     return isLegalT2AddressImmediate(V, VT, Subtarget);
12887 
12888   // ARM mode.
12889   if (V < 0)
12890     V = - V;
12891   switch (VT.getSimpleVT().SimpleTy) {
12892   default: return false;
12893   case MVT::i1:
12894   case MVT::i8:
12895   case MVT::i32:
12896     // +- imm12
12897     return V == (V & ((1LL << 12) - 1));
12898   case MVT::i16:
12899     // +- imm8
12900     return V == (V & ((1LL << 8) - 1));
12901   case MVT::f32:
12902   case MVT::f64:
12903     if (!Subtarget->hasVFP2()) // FIXME: NEON?
12904       return false;
12905     if ((V & 3) != 0)
12906       return false;
12907     V >>= 2;
12908     return V == (V & ((1LL << 8) - 1));
12909   }
12910 }
12911 
12912 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
12913                                                       EVT VT) const {
12914   int Scale = AM.Scale;
12915   if (Scale < 0)
12916     return false;
12917 
12918   switch (VT.getSimpleVT().SimpleTy) {
12919   default: return false;
12920   case MVT::i1:
12921   case MVT::i8:
12922   case MVT::i16:
12923   case MVT::i32:
12924     if (Scale == 1)
12925       return true;
12926     // r + r << imm
12927     Scale = Scale & ~1;
12928     return Scale == 2 || Scale == 4 || Scale == 8;
12929   case MVT::i64:
12930     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
12931     // version in Thumb mode.
12932     // r + r
12933     if (Scale == 1)
12934       return true;
12935     // r * 2 (this can be lowered to r + r).
12936     if (!AM.HasBaseReg && Scale == 2)
12937       return true;
12938     return false;
12939   case MVT::isVoid:
12940     // Note, we allow "void" uses (basically, uses that aren't loads or
12941     // stores), because arm allows folding a scale into many arithmetic
12942     // operations.  This should be made more precise and revisited later.
12943 
12944     // Allow r << imm, but the imm has to be a multiple of two.
12945     if (Scale & 1) return false;
12946     return isPowerOf2_32(Scale);
12947   }
12948 }
12949 
12950 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
12951                                                       EVT VT) const {
12952   const int Scale = AM.Scale;
12953 
12954   // Negative scales are not supported in Thumb1.
12955   if (Scale < 0)
12956     return false;
12957 
12958   // Thumb1 addressing modes do not support register scaling excepting the
12959   // following cases:
12960   // 1. Scale == 1 means no scaling.
12961   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
12962   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
12963 }
12964 
12965 /// isLegalAddressingMode - Return true if the addressing mode represented
12966 /// by AM is legal for this target, for a load/store of the specified type.
12967 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12968                                               const AddrMode &AM, Type *Ty,
12969                                               unsigned AS, Instruction *I) const {
12970   EVT VT = getValueType(DL, Ty, true);
12971   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
12972     return false;
12973 
12974   // Can never fold addr of global into load/store.
12975   if (AM.BaseGV)
12976     return false;
12977 
12978   switch (AM.Scale) {
12979   case 0:  // no scale reg, must be "r+i" or "r", or "i".
12980     break;
12981   default:
12982     // ARM doesn't support any R+R*scale+imm addr modes.
12983     if (AM.BaseOffs)
12984       return false;
12985 
12986     if (!VT.isSimple())
12987       return false;
12988 
12989     if (Subtarget->isThumb1Only())
12990       return isLegalT1ScaledAddressingMode(AM, VT);
12991 
12992     if (Subtarget->isThumb2())
12993       return isLegalT2ScaledAddressingMode(AM, VT);
12994 
12995     int Scale = AM.Scale;
12996     switch (VT.getSimpleVT().SimpleTy) {
12997     default: return false;
12998     case MVT::i1:
12999     case MVT::i8:
13000     case MVT::i32:
13001       if (Scale < 0) Scale = -Scale;
13002       if (Scale == 1)
13003         return true;
13004       // r + r << imm
13005       return isPowerOf2_32(Scale & ~1);
13006     case MVT::i16:
13007     case MVT::i64:
13008       // r +/- r
13009       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
13010         return true;
13011       // r * 2 (this can be lowered to r + r).
13012       if (!AM.HasBaseReg && Scale == 2)
13013         return true;
13014       return false;
13015 
13016     case MVT::isVoid:
13017       // Note, we allow "void" uses (basically, uses that aren't loads or
13018       // stores), because arm allows folding a scale into many arithmetic
13019       // operations.  This should be made more precise and revisited later.
13020 
13021       // Allow r << imm, but the imm has to be a multiple of two.
13022       if (Scale & 1) return false;
13023       return isPowerOf2_32(Scale);
13024     }
13025   }
13026   return true;
13027 }
13028 
13029 /// isLegalICmpImmediate - Return true if the specified immediate is legal
13030 /// icmp immediate, that is the target has icmp instructions which can compare
13031 /// a register against the immediate without having to materialize the
13032 /// immediate into a register.
13033 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13034   // Thumb2 and ARM modes can use cmn for negative immediates.
13035   if (!Subtarget->isThumb())
13036     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
13037   if (Subtarget->isThumb2())
13038     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
13039   // Thumb1 doesn't have cmn, and only 8-bit immediates.
13040   return Imm >= 0 && Imm <= 255;
13041 }
13042 
13043 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
13044 /// *or sub* immediate, that is the target has add or sub instructions which can
13045 /// add a register with the immediate without having to materialize the
13046 /// immediate into a register.
13047 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13048   // Same encoding for add/sub, just flip the sign.
13049   int64_t AbsImm = std::abs(Imm);
13050   if (!Subtarget->isThumb())
13051     return ARM_AM::getSOImmVal(AbsImm) != -1;
13052   if (Subtarget->isThumb2())
13053     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
13054   // Thumb1 only has 8-bit unsigned immediate.
13055   return AbsImm >= 0 && AbsImm <= 255;
13056 }
13057 
13058 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
13059                                       bool isSEXTLoad, SDValue &Base,
13060                                       SDValue &Offset, bool &isInc,
13061                                       SelectionDAG &DAG) {
13062   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13063     return false;
13064 
13065   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
13066     // AddressingMode 3
13067     Base = Ptr->getOperand(0);
13068     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13069       int RHSC = (int)RHS->getZExtValue();
13070       if (RHSC < 0 && RHSC > -256) {
13071         assert(Ptr->getOpcode() == ISD::ADD);
13072         isInc = false;
13073         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13074         return true;
13075       }
13076     }
13077     isInc = (Ptr->getOpcode() == ISD::ADD);
13078     Offset = Ptr->getOperand(1);
13079     return true;
13080   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
13081     // AddressingMode 2
13082     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13083       int RHSC = (int)RHS->getZExtValue();
13084       if (RHSC < 0 && RHSC > -0x1000) {
13085         assert(Ptr->getOpcode() == ISD::ADD);
13086         isInc = false;
13087         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13088         Base = Ptr->getOperand(0);
13089         return true;
13090       }
13091     }
13092 
13093     if (Ptr->getOpcode() == ISD::ADD) {
13094       isInc = true;
13095       ARM_AM::ShiftOpc ShOpcVal=
13096         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
13097       if (ShOpcVal != ARM_AM::no_shift) {
13098         Base = Ptr->getOperand(1);
13099         Offset = Ptr->getOperand(0);
13100       } else {
13101         Base = Ptr->getOperand(0);
13102         Offset = Ptr->getOperand(1);
13103       }
13104       return true;
13105     }
13106 
13107     isInc = (Ptr->getOpcode() == ISD::ADD);
13108     Base = Ptr->getOperand(0);
13109     Offset = Ptr->getOperand(1);
13110     return true;
13111   }
13112 
13113   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
13114   return false;
13115 }
13116 
13117 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
13118                                      bool isSEXTLoad, SDValue &Base,
13119                                      SDValue &Offset, bool &isInc,
13120                                      SelectionDAG &DAG) {
13121   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13122     return false;
13123 
13124   Base = Ptr->getOperand(0);
13125   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13126     int RHSC = (int)RHS->getZExtValue();
13127     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
13128       assert(Ptr->getOpcode() == ISD::ADD);
13129       isInc = false;
13130       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13131       return true;
13132     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
13133       isInc = Ptr->getOpcode() == ISD::ADD;
13134       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
13135       return true;
13136     }
13137   }
13138 
13139   return false;
13140 }
13141 
13142 /// getPreIndexedAddressParts - returns true by value, base pointer and
13143 /// offset pointer and addressing mode by reference if the node's address
13144 /// can be legally represented as pre-indexed load / store address.
13145 bool
13146 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
13147                                              SDValue &Offset,
13148                                              ISD::MemIndexedMode &AM,
13149                                              SelectionDAG &DAG) const {
13150   if (Subtarget->isThumb1Only())
13151     return false;
13152 
13153   EVT VT;
13154   SDValue Ptr;
13155   bool isSEXTLoad = false;
13156   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13157     Ptr = LD->getBasePtr();
13158     VT  = LD->getMemoryVT();
13159     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13160   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13161     Ptr = ST->getBasePtr();
13162     VT  = ST->getMemoryVT();
13163   } else
13164     return false;
13165 
13166   bool isInc;
13167   bool isLegal = false;
13168   if (Subtarget->isThumb2())
13169     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13170                                        Offset, isInc, DAG);
13171   else
13172     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13173                                         Offset, isInc, DAG);
13174   if (!isLegal)
13175     return false;
13176 
13177   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
13178   return true;
13179 }
13180 
13181 /// getPostIndexedAddressParts - returns true by value, base pointer and
13182 /// offset pointer and addressing mode by reference if this node can be
13183 /// combined with a load / store to form a post-indexed load / store.
13184 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
13185                                                    SDValue &Base,
13186                                                    SDValue &Offset,
13187                                                    ISD::MemIndexedMode &AM,
13188                                                    SelectionDAG &DAG) const {
13189   EVT VT;
13190   SDValue Ptr;
13191   bool isSEXTLoad = false, isNonExt;
13192   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13193     VT  = LD->getMemoryVT();
13194     Ptr = LD->getBasePtr();
13195     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13196     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
13197   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13198     VT  = ST->getMemoryVT();
13199     Ptr = ST->getBasePtr();
13200     isNonExt = !ST->isTruncatingStore();
13201   } else
13202     return false;
13203 
13204   if (Subtarget->isThumb1Only()) {
13205     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
13206     // must be non-extending/truncating, i32, with an offset of 4.
13207     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
13208     if (Op->getOpcode() != ISD::ADD || !isNonExt)
13209       return false;
13210     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
13211     if (!RHS || RHS->getZExtValue() != 4)
13212       return false;
13213 
13214     Offset = Op->getOperand(1);
13215     Base = Op->getOperand(0);
13216     AM = ISD::POST_INC;
13217     return true;
13218   }
13219 
13220   bool isInc;
13221   bool isLegal = false;
13222   if (Subtarget->isThumb2())
13223     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13224                                        isInc, DAG);
13225   else
13226     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13227                                         isInc, DAG);
13228   if (!isLegal)
13229     return false;
13230 
13231   if (Ptr != Base) {
13232     // Swap base ptr and offset to catch more post-index load / store when
13233     // it's legal. In Thumb2 mode, offset must be an immediate.
13234     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
13235         !Subtarget->isThumb2())
13236       std::swap(Base, Offset);
13237 
13238     // Post-indexed load / store update the base pointer.
13239     if (Ptr != Base)
13240       return false;
13241   }
13242 
13243   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
13244   return true;
13245 }
13246 
13247 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13248                                                       KnownBits &Known,
13249                                                       const APInt &DemandedElts,
13250                                                       const SelectionDAG &DAG,
13251                                                       unsigned Depth) const {
13252   unsigned BitWidth = Known.getBitWidth();
13253   Known.resetAll();
13254   switch (Op.getOpcode()) {
13255   default: break;
13256   case ARMISD::ADDC:
13257   case ARMISD::ADDE:
13258   case ARMISD::SUBC:
13259   case ARMISD::SUBE:
13260     // Special cases when we convert a carry to a boolean.
13261     if (Op.getResNo() == 0) {
13262       SDValue LHS = Op.getOperand(0);
13263       SDValue RHS = Op.getOperand(1);
13264       // (ADDE 0, 0, C) will give us a single bit.
13265       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
13266           isNullConstant(RHS)) {
13267         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13268         return;
13269       }
13270     }
13271     break;
13272   case ARMISD::CMOV: {
13273     // Bits are known zero/one if known on the LHS and RHS.
13274     DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1);
13275     if (Known.isUnknown())
13276       return;
13277 
13278     KnownBits KnownRHS;
13279     DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1);
13280     Known.Zero &= KnownRHS.Zero;
13281     Known.One  &= KnownRHS.One;
13282     return;
13283   }
13284   case ISD::INTRINSIC_W_CHAIN: {
13285     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
13286     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
13287     switch (IntID) {
13288     default: return;
13289     case Intrinsic::arm_ldaex:
13290     case Intrinsic::arm_ldrex: {
13291       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
13292       unsigned MemBits = VT.getScalarSizeInBits();
13293       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
13294       return;
13295     }
13296     }
13297   }
13298   case ARMISD::BFI: {
13299     // Conservatively, we can recurse down the first operand
13300     // and just mask out all affected bits.
13301     DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1);
13302 
13303     // The operand to BFI is already a mask suitable for removing the bits it
13304     // sets.
13305     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
13306     const APInt &Mask = CI->getAPIntValue();
13307     Known.Zero &= Mask;
13308     Known.One &= Mask;
13309     return;
13310   }
13311   }
13312 }
13313 
13314 //===----------------------------------------------------------------------===//
13315 //                           ARM Inline Assembly Support
13316 //===----------------------------------------------------------------------===//
13317 
13318 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
13319   // Looking for "rev" which is V6+.
13320   if (!Subtarget->hasV6Ops())
13321     return false;
13322 
13323   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13324   std::string AsmStr = IA->getAsmString();
13325   SmallVector<StringRef, 4> AsmPieces;
13326   SplitString(AsmStr, AsmPieces, ";\n");
13327 
13328   switch (AsmPieces.size()) {
13329   default: return false;
13330   case 1:
13331     AsmStr = AsmPieces[0];
13332     AsmPieces.clear();
13333     SplitString(AsmStr, AsmPieces, " \t,");
13334 
13335     // rev $0, $1
13336     if (AsmPieces.size() == 3 &&
13337         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
13338         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
13339       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13340       if (Ty && Ty->getBitWidth() == 32)
13341         return IntrinsicLowering::LowerToByteSwap(CI);
13342     }
13343     break;
13344   }
13345 
13346   return false;
13347 }
13348 
13349 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
13350   // At this point, we have to lower this constraint to something else, so we
13351   // lower it to an "r" or "w". However, by doing this we will force the result
13352   // to be in register, while the X constraint is much more permissive.
13353   //
13354   // Although we are correct (we are free to emit anything, without
13355   // constraints), we might break use cases that would expect us to be more
13356   // efficient and emit something else.
13357   if (!Subtarget->hasVFP2())
13358     return "r";
13359   if (ConstraintVT.isFloatingPoint())
13360     return "w";
13361   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
13362      (ConstraintVT.getSizeInBits() == 64 ||
13363       ConstraintVT.getSizeInBits() == 128))
13364     return "w";
13365 
13366   return "r";
13367 }
13368 
13369 /// getConstraintType - Given a constraint letter, return the type of
13370 /// constraint it is for this target.
13371 ARMTargetLowering::ConstraintType
13372 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
13373   if (Constraint.size() == 1) {
13374     switch (Constraint[0]) {
13375     default:  break;
13376     case 'l': return C_RegisterClass;
13377     case 'w': return C_RegisterClass;
13378     case 'h': return C_RegisterClass;
13379     case 'x': return C_RegisterClass;
13380     case 't': return C_RegisterClass;
13381     case 'j': return C_Other; // Constant for movw.
13382       // An address with a single base register. Due to the way we
13383       // currently handle addresses it is the same as an 'r' memory constraint.
13384     case 'Q': return C_Memory;
13385     }
13386   } else if (Constraint.size() == 2) {
13387     switch (Constraint[0]) {
13388     default: break;
13389     // All 'U+' constraints are addresses.
13390     case 'U': return C_Memory;
13391     }
13392   }
13393   return TargetLowering::getConstraintType(Constraint);
13394 }
13395 
13396 /// Examine constraint type and operand type and determine a weight value.
13397 /// This object must already have been set up with the operand type
13398 /// and the current alternative constraint selected.
13399 TargetLowering::ConstraintWeight
13400 ARMTargetLowering::getSingleConstraintMatchWeight(
13401     AsmOperandInfo &info, const char *constraint) const {
13402   ConstraintWeight weight = CW_Invalid;
13403   Value *CallOperandVal = info.CallOperandVal;
13404     // If we don't have a value, we can't do a match,
13405     // but allow it at the lowest weight.
13406   if (!CallOperandVal)
13407     return CW_Default;
13408   Type *type = CallOperandVal->getType();
13409   // Look at the constraint type.
13410   switch (*constraint) {
13411   default:
13412     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13413     break;
13414   case 'l':
13415     if (type->isIntegerTy()) {
13416       if (Subtarget->isThumb())
13417         weight = CW_SpecificReg;
13418       else
13419         weight = CW_Register;
13420     }
13421     break;
13422   case 'w':
13423     if (type->isFloatingPointTy())
13424       weight = CW_Register;
13425     break;
13426   }
13427   return weight;
13428 }
13429 
13430 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
13431 
13432 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
13433     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
13434   if (Constraint.size() == 1) {
13435     // GCC ARM Constraint Letters
13436     switch (Constraint[0]) {
13437     case 'l': // Low regs or general regs.
13438       if (Subtarget->isThumb())
13439         return RCPair(0U, &ARM::tGPRRegClass);
13440       return RCPair(0U, &ARM::GPRRegClass);
13441     case 'h': // High regs or no regs.
13442       if (Subtarget->isThumb())
13443         return RCPair(0U, &ARM::hGPRRegClass);
13444       break;
13445     case 'r':
13446       if (Subtarget->isThumb1Only())
13447         return RCPair(0U, &ARM::tGPRRegClass);
13448       return RCPair(0U, &ARM::GPRRegClass);
13449     case 'w':
13450       if (VT == MVT::Other)
13451         break;
13452       if (VT == MVT::f32)
13453         return RCPair(0U, &ARM::SPRRegClass);
13454       if (VT.getSizeInBits() == 64)
13455         return RCPair(0U, &ARM::DPRRegClass);
13456       if (VT.getSizeInBits() == 128)
13457         return RCPair(0U, &ARM::QPRRegClass);
13458       break;
13459     case 'x':
13460       if (VT == MVT::Other)
13461         break;
13462       if (VT == MVT::f32)
13463         return RCPair(0U, &ARM::SPR_8RegClass);
13464       if (VT.getSizeInBits() == 64)
13465         return RCPair(0U, &ARM::DPR_8RegClass);
13466       if (VT.getSizeInBits() == 128)
13467         return RCPair(0U, &ARM::QPR_8RegClass);
13468       break;
13469     case 't':
13470       if (VT == MVT::f32 || VT == MVT::i32)
13471         return RCPair(0U, &ARM::SPRRegClass);
13472       break;
13473     }
13474   }
13475   if (StringRef("{cc}").equals_lower(Constraint))
13476     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
13477 
13478   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13479 }
13480 
13481 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13482 /// vector.  If it is invalid, don't add anything to Ops.
13483 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13484                                                      std::string &Constraint,
13485                                                      std::vector<SDValue>&Ops,
13486                                                      SelectionDAG &DAG) const {
13487   SDValue Result;
13488 
13489   // Currently only support length 1 constraints.
13490   if (Constraint.length() != 1) return;
13491 
13492   char ConstraintLetter = Constraint[0];
13493   switch (ConstraintLetter) {
13494   default: break;
13495   case 'j':
13496   case 'I': case 'J': case 'K': case 'L':
13497   case 'M': case 'N': case 'O':
13498     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
13499     if (!C)
13500       return;
13501 
13502     int64_t CVal64 = C->getSExtValue();
13503     int CVal = (int) CVal64;
13504     // None of these constraints allow values larger than 32 bits.  Check
13505     // that the value fits in an int.
13506     if (CVal != CVal64)
13507       return;
13508 
13509     switch (ConstraintLetter) {
13510       case 'j':
13511         // Constant suitable for movw, must be between 0 and
13512         // 65535.
13513         if (Subtarget->hasV6T2Ops())
13514           if (CVal >= 0 && CVal <= 65535)
13515             break;
13516         return;
13517       case 'I':
13518         if (Subtarget->isThumb1Only()) {
13519           // This must be a constant between 0 and 255, for ADD
13520           // immediates.
13521           if (CVal >= 0 && CVal <= 255)
13522             break;
13523         } else if (Subtarget->isThumb2()) {
13524           // A constant that can be used as an immediate value in a
13525           // data-processing instruction.
13526           if (ARM_AM::getT2SOImmVal(CVal) != -1)
13527             break;
13528         } else {
13529           // A constant that can be used as an immediate value in a
13530           // data-processing instruction.
13531           if (ARM_AM::getSOImmVal(CVal) != -1)
13532             break;
13533         }
13534         return;
13535 
13536       case 'J':
13537         if (Subtarget->isThumb1Only()) {
13538           // This must be a constant between -255 and -1, for negated ADD
13539           // immediates. This can be used in GCC with an "n" modifier that
13540           // prints the negated value, for use with SUB instructions. It is
13541           // not useful otherwise but is implemented for compatibility.
13542           if (CVal >= -255 && CVal <= -1)
13543             break;
13544         } else {
13545           // This must be a constant between -4095 and 4095. It is not clear
13546           // what this constraint is intended for. Implemented for
13547           // compatibility with GCC.
13548           if (CVal >= -4095 && CVal <= 4095)
13549             break;
13550         }
13551         return;
13552 
13553       case 'K':
13554         if (Subtarget->isThumb1Only()) {
13555           // A 32-bit value where only one byte has a nonzero value. Exclude
13556           // zero to match GCC. This constraint is used by GCC internally for
13557           // constants that can be loaded with a move/shift combination.
13558           // It is not useful otherwise but is implemented for compatibility.
13559           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
13560             break;
13561         } else if (Subtarget->isThumb2()) {
13562           // A constant whose bitwise inverse can be used as an immediate
13563           // value in a data-processing instruction. This can be used in GCC
13564           // with a "B" modifier that prints the inverted value, for use with
13565           // BIC and MVN instructions. It is not useful otherwise but is
13566           // implemented for compatibility.
13567           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
13568             break;
13569         } else {
13570           // A constant whose bitwise inverse can be used as an immediate
13571           // value in a data-processing instruction. This can be used in GCC
13572           // with a "B" modifier that prints the inverted value, for use with
13573           // BIC and MVN instructions. It is not useful otherwise but is
13574           // implemented for compatibility.
13575           if (ARM_AM::getSOImmVal(~CVal) != -1)
13576             break;
13577         }
13578         return;
13579 
13580       case 'L':
13581         if (Subtarget->isThumb1Only()) {
13582           // This must be a constant between -7 and 7,
13583           // for 3-operand ADD/SUB immediate instructions.
13584           if (CVal >= -7 && CVal < 7)
13585             break;
13586         } else if (Subtarget->isThumb2()) {
13587           // A constant whose negation can be used as an immediate value in a
13588           // data-processing instruction. This can be used in GCC with an "n"
13589           // modifier that prints the negated value, for use with SUB
13590           // instructions. It is not useful otherwise but is implemented for
13591           // compatibility.
13592           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
13593             break;
13594         } else {
13595           // A constant whose negation can be used as an immediate value in a
13596           // data-processing instruction. This can be used in GCC with an "n"
13597           // modifier that prints the negated value, for use with SUB
13598           // instructions. It is not useful otherwise but is implemented for
13599           // compatibility.
13600           if (ARM_AM::getSOImmVal(-CVal) != -1)
13601             break;
13602         }
13603         return;
13604 
13605       case 'M':
13606         if (Subtarget->isThumb1Only()) {
13607           // This must be a multiple of 4 between 0 and 1020, for
13608           // ADD sp + immediate.
13609           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
13610             break;
13611         } else {
13612           // A power of two or a constant between 0 and 32.  This is used in
13613           // GCC for the shift amount on shifted register operands, but it is
13614           // useful in general for any shift amounts.
13615           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
13616             break;
13617         }
13618         return;
13619 
13620       case 'N':
13621         if (Subtarget->isThumb()) {  // FIXME thumb2
13622           // This must be a constant between 0 and 31, for shift amounts.
13623           if (CVal >= 0 && CVal <= 31)
13624             break;
13625         }
13626         return;
13627 
13628       case 'O':
13629         if (Subtarget->isThumb()) {  // FIXME thumb2
13630           // This must be a multiple of 4 between -508 and 508, for
13631           // ADD/SUB sp = sp + immediate.
13632           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
13633             break;
13634         }
13635         return;
13636     }
13637     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
13638     break;
13639   }
13640 
13641   if (Result.getNode()) {
13642     Ops.push_back(Result);
13643     return;
13644   }
13645   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13646 }
13647 
13648 static RTLIB::Libcall getDivRemLibcall(
13649     const SDNode *N, MVT::SimpleValueType SVT) {
13650   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13651           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13652          "Unhandled Opcode in getDivRemLibcall");
13653   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13654                   N->getOpcode() == ISD::SREM;
13655   RTLIB::Libcall LC;
13656   switch (SVT) {
13657   default: llvm_unreachable("Unexpected request for libcall!");
13658   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
13659   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
13660   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
13661   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
13662   }
13663   return LC;
13664 }
13665 
13666 static TargetLowering::ArgListTy getDivRemArgList(
13667     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
13668   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13669           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13670          "Unhandled Opcode in getDivRemArgList");
13671   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13672                   N->getOpcode() == ISD::SREM;
13673   TargetLowering::ArgListTy Args;
13674   TargetLowering::ArgListEntry Entry;
13675   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13676     EVT ArgVT = N->getOperand(i).getValueType();
13677     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
13678     Entry.Node = N->getOperand(i);
13679     Entry.Ty = ArgTy;
13680     Entry.IsSExt = isSigned;
13681     Entry.IsZExt = !isSigned;
13682     Args.push_back(Entry);
13683   }
13684   if (Subtarget->isTargetWindows() && Args.size() >= 2)
13685     std::swap(Args[0], Args[1]);
13686   return Args;
13687 }
13688 
13689 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
13690   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
13691           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
13692           Subtarget->isTargetWindows()) &&
13693          "Register-based DivRem lowering only");
13694   unsigned Opcode = Op->getOpcode();
13695   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
13696          "Invalid opcode for Div/Rem lowering");
13697   bool isSigned = (Opcode == ISD::SDIVREM);
13698   EVT VT = Op->getValueType(0);
13699   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
13700   SDLoc dl(Op);
13701 
13702   // If the target has hardware divide, use divide + multiply + subtract:
13703   //     div = a / b
13704   //     rem = a - b * div
13705   //     return {div, rem}
13706   // This should be lowered into UDIV/SDIV + MLS later on.
13707   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
13708                                         : Subtarget->hasDivideInARMMode();
13709   if (hasDivide && Op->getValueType(0).isSimple() &&
13710       Op->getSimpleValueType(0) == MVT::i32) {
13711     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
13712     const SDValue Dividend = Op->getOperand(0);
13713     const SDValue Divisor = Op->getOperand(1);
13714     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
13715     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
13716     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13717 
13718     SDValue Values[2] = {Div, Rem};
13719     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
13720   }
13721 
13722   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
13723                                        VT.getSimpleVT().SimpleTy);
13724   SDValue InChain = DAG.getEntryNode();
13725 
13726   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
13727                                                     DAG.getContext(),
13728                                                     Subtarget);
13729 
13730   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13731                                          getPointerTy(DAG.getDataLayout()));
13732 
13733   Type *RetTy = StructType::get(Ty, Ty);
13734 
13735   if (Subtarget->isTargetWindows())
13736     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
13737 
13738   TargetLowering::CallLoweringInfo CLI(DAG);
13739   CLI.setDebugLoc(dl).setChain(InChain)
13740     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
13741     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13742 
13743   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13744   return CallInfo.first;
13745 }
13746 
13747 // Lowers REM using divmod helpers
13748 // see RTABI section 4.2/4.3
13749 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
13750   // Build return types (div and rem)
13751   std::vector<Type*> RetTyParams;
13752   Type *RetTyElement;
13753 
13754   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
13755   default: llvm_unreachable("Unexpected request for libcall!");
13756   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
13757   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
13758   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
13759   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
13760   }
13761 
13762   RetTyParams.push_back(RetTyElement);
13763   RetTyParams.push_back(RetTyElement);
13764   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
13765   Type *RetTy = StructType::get(*DAG.getContext(), ret);
13766 
13767   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
13768                                                              SimpleTy);
13769   SDValue InChain = DAG.getEntryNode();
13770   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
13771                                                     Subtarget);
13772   bool isSigned = N->getOpcode() == ISD::SREM;
13773   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13774                                          getPointerTy(DAG.getDataLayout()));
13775 
13776   if (Subtarget->isTargetWindows())
13777     InChain = WinDBZCheckDenominator(DAG, N, InChain);
13778 
13779   // Lower call
13780   CallLoweringInfo CLI(DAG);
13781   CLI.setChain(InChain)
13782      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
13783      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
13784   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
13785 
13786   // Return second (rem) result operand (first contains div)
13787   SDNode *ResNode = CallResult.first.getNode();
13788   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
13789   return ResNode->getOperand(1);
13790 }
13791 
13792 SDValue
13793 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
13794   assert(Subtarget->isTargetWindows() && "unsupported target platform");
13795   SDLoc DL(Op);
13796 
13797   // Get the inputs.
13798   SDValue Chain = Op.getOperand(0);
13799   SDValue Size  = Op.getOperand(1);
13800 
13801   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
13802                               DAG.getConstant(2, DL, MVT::i32));
13803 
13804   SDValue Flag;
13805   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
13806   Flag = Chain.getValue(1);
13807 
13808   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13809   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
13810 
13811   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
13812   Chain = NewSP.getValue(1);
13813 
13814   SDValue Ops[2] = { NewSP, Chain };
13815   return DAG.getMergeValues(Ops, DL);
13816 }
13817 
13818 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
13819   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
13820          "Unexpected type for custom-lowering FP_EXTEND");
13821 
13822   RTLIB::Libcall LC;
13823   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
13824 
13825   SDValue SrcVal = Op.getOperand(0);
13826   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13827                      SDLoc(Op)).first;
13828 }
13829 
13830 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
13831   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
13832          Subtarget->isFPOnlySP() &&
13833          "Unexpected type for custom-lowering FP_ROUND");
13834 
13835   RTLIB::Libcall LC;
13836   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
13837 
13838   SDValue SrcVal = Op.getOperand(0);
13839   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13840                      SDLoc(Op)).first;
13841 }
13842 
13843 bool
13844 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13845   // The ARM target isn't yet aware of offsets.
13846   return false;
13847 }
13848 
13849 bool ARM::isBitFieldInvertedMask(unsigned v) {
13850   if (v == 0xffffffff)
13851     return false;
13852 
13853   // there can be 1's on either or both "outsides", all the "inside"
13854   // bits must be 0's
13855   return isShiftedMask_32(~v);
13856 }
13857 
13858 /// isFPImmLegal - Returns true if the target can instruction select the
13859 /// specified FP immediate natively. If false, the legalizer will
13860 /// materialize the FP immediate as a load from a constant pool.
13861 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13862   if (!Subtarget->hasVFP3())
13863     return false;
13864   if (VT == MVT::f16 && Subtarget->hasFullFP16())
13865     return ARM_AM::getFP16Imm(Imm) != -1;
13866   if (VT == MVT::f32)
13867     return ARM_AM::getFP32Imm(Imm) != -1;
13868   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
13869     return ARM_AM::getFP64Imm(Imm) != -1;
13870   return false;
13871 }
13872 
13873 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
13874 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
13875 /// specified in the intrinsic calls.
13876 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13877                                            const CallInst &I,
13878                                            MachineFunction &MF,
13879                                            unsigned Intrinsic) const {
13880   switch (Intrinsic) {
13881   case Intrinsic::arm_neon_vld1:
13882   case Intrinsic::arm_neon_vld2:
13883   case Intrinsic::arm_neon_vld3:
13884   case Intrinsic::arm_neon_vld4:
13885   case Intrinsic::arm_neon_vld2lane:
13886   case Intrinsic::arm_neon_vld3lane:
13887   case Intrinsic::arm_neon_vld4lane: {
13888     Info.opc = ISD::INTRINSIC_W_CHAIN;
13889     // Conservatively set memVT to the entire set of vectors loaded.
13890     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13891     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
13892     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13893     Info.ptrVal = I.getArgOperand(0);
13894     Info.offset = 0;
13895     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13896     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13897     // volatile loads with NEON intrinsics not supported
13898     Info.flags = MachineMemOperand::MOLoad;
13899     return true;
13900   }
13901   case Intrinsic::arm_neon_vst1:
13902   case Intrinsic::arm_neon_vst2:
13903   case Intrinsic::arm_neon_vst3:
13904   case Intrinsic::arm_neon_vst4:
13905   case Intrinsic::arm_neon_vst2lane:
13906   case Intrinsic::arm_neon_vst3lane:
13907   case Intrinsic::arm_neon_vst4lane: {
13908     Info.opc = ISD::INTRINSIC_VOID;
13909     // Conservatively set memVT to the entire set of vectors stored.
13910     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13911     unsigned NumElts = 0;
13912     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
13913       Type *ArgTy = I.getArgOperand(ArgI)->getType();
13914       if (!ArgTy->isVectorTy())
13915         break;
13916       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
13917     }
13918     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13919     Info.ptrVal = I.getArgOperand(0);
13920     Info.offset = 0;
13921     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13922     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13923     // volatile stores with NEON intrinsics not supported
13924     Info.flags = MachineMemOperand::MOStore;
13925     return true;
13926   }
13927   case Intrinsic::arm_ldaex:
13928   case Intrinsic::arm_ldrex: {
13929     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13930     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
13931     Info.opc = ISD::INTRINSIC_W_CHAIN;
13932     Info.memVT = MVT::getVT(PtrTy->getElementType());
13933     Info.ptrVal = I.getArgOperand(0);
13934     Info.offset = 0;
13935     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13936     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
13937     return true;
13938   }
13939   case Intrinsic::arm_stlex:
13940   case Intrinsic::arm_strex: {
13941     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13942     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
13943     Info.opc = ISD::INTRINSIC_W_CHAIN;
13944     Info.memVT = MVT::getVT(PtrTy->getElementType());
13945     Info.ptrVal = I.getArgOperand(1);
13946     Info.offset = 0;
13947     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13948     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
13949     return true;
13950   }
13951   case Intrinsic::arm_stlexd:
13952   case Intrinsic::arm_strexd:
13953     Info.opc = ISD::INTRINSIC_W_CHAIN;
13954     Info.memVT = MVT::i64;
13955     Info.ptrVal = I.getArgOperand(2);
13956     Info.offset = 0;
13957     Info.align = 8;
13958     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
13959     return true;
13960 
13961   case Intrinsic::arm_ldaexd:
13962   case Intrinsic::arm_ldrexd:
13963     Info.opc = ISD::INTRINSIC_W_CHAIN;
13964     Info.memVT = MVT::i64;
13965     Info.ptrVal = I.getArgOperand(0);
13966     Info.offset = 0;
13967     Info.align = 8;
13968     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
13969     return true;
13970 
13971   default:
13972     break;
13973   }
13974 
13975   return false;
13976 }
13977 
13978 /// \brief Returns true if it is beneficial to convert a load of a constant
13979 /// to just the constant itself.
13980 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13981                                                           Type *Ty) const {
13982   assert(Ty->isIntegerTy());
13983 
13984   unsigned Bits = Ty->getPrimitiveSizeInBits();
13985   if (Bits == 0 || Bits > 32)
13986     return false;
13987   return true;
13988 }
13989 
13990 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
13991                                                 unsigned Index) const {
13992   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
13993     return false;
13994 
13995   return (Index == 0 || Index == ResVT.getVectorNumElements());
13996 }
13997 
13998 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
13999                                         ARM_MB::MemBOpt Domain) const {
14000   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14001 
14002   // First, if the target has no DMB, see what fallback we can use.
14003   if (!Subtarget->hasDataBarrier()) {
14004     // Some ARMv6 cpus can support data barriers with an mcr instruction.
14005     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
14006     // here.
14007     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
14008       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
14009       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
14010                         Builder.getInt32(0), Builder.getInt32(7),
14011                         Builder.getInt32(10), Builder.getInt32(5)};
14012       return Builder.CreateCall(MCR, args);
14013     } else {
14014       // Instead of using barriers, atomic accesses on these subtargets use
14015       // libcalls.
14016       llvm_unreachable("makeDMB on a target so old that it has no barriers");
14017     }
14018   } else {
14019     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
14020     // Only a full system barrier exists in the M-class architectures.
14021     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
14022     Constant *CDomain = Builder.getInt32(Domain);
14023     return Builder.CreateCall(DMB, CDomain);
14024   }
14025 }
14026 
14027 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
14028 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
14029                                                  Instruction *Inst,
14030                                                  AtomicOrdering Ord) const {
14031   switch (Ord) {
14032   case AtomicOrdering::NotAtomic:
14033   case AtomicOrdering::Unordered:
14034     llvm_unreachable("Invalid fence: unordered/non-atomic");
14035   case AtomicOrdering::Monotonic:
14036   case AtomicOrdering::Acquire:
14037     return nullptr; // Nothing to do
14038   case AtomicOrdering::SequentiallyConsistent:
14039     if (!Inst->hasAtomicStore())
14040       return nullptr; // Nothing to do
14041     LLVM_FALLTHROUGH;
14042   case AtomicOrdering::Release:
14043   case AtomicOrdering::AcquireRelease:
14044     if (Subtarget->preferISHSTBarriers())
14045       return makeDMB(Builder, ARM_MB::ISHST);
14046     // FIXME: add a comment with a link to documentation justifying this.
14047     else
14048       return makeDMB(Builder, ARM_MB::ISH);
14049   }
14050   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
14051 }
14052 
14053 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
14054                                                   Instruction *Inst,
14055                                                   AtomicOrdering Ord) const {
14056   switch (Ord) {
14057   case AtomicOrdering::NotAtomic:
14058   case AtomicOrdering::Unordered:
14059     llvm_unreachable("Invalid fence: unordered/not-atomic");
14060   case AtomicOrdering::Monotonic:
14061   case AtomicOrdering::Release:
14062     return nullptr; // Nothing to do
14063   case AtomicOrdering::Acquire:
14064   case AtomicOrdering::AcquireRelease:
14065   case AtomicOrdering::SequentiallyConsistent:
14066     return makeDMB(Builder, ARM_MB::ISH);
14067   }
14068   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
14069 }
14070 
14071 // Loads and stores less than 64-bits are already atomic; ones above that
14072 // are doomed anyway, so defer to the default libcall and blame the OS when
14073 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
14074 // anything for those.
14075 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
14076   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
14077   return (Size == 64) && !Subtarget->isMClass();
14078 }
14079 
14080 // Loads and stores less than 64-bits are already atomic; ones above that
14081 // are doomed anyway, so defer to the default libcall and blame the OS when
14082 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
14083 // anything for those.
14084 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
14085 // guarantee, see DDI0406C ARM architecture reference manual,
14086 // sections A8.8.72-74 LDRD)
14087 TargetLowering::AtomicExpansionKind
14088 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
14089   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
14090   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
14091                                                   : AtomicExpansionKind::None;
14092 }
14093 
14094 // For the real atomic operations, we have ldrex/strex up to 32 bits,
14095 // and up to 64 bits on the non-M profiles
14096 TargetLowering::AtomicExpansionKind
14097 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
14098   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
14099   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
14100   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
14101              ? AtomicExpansionKind::LLSC
14102              : AtomicExpansionKind::None;
14103 }
14104 
14105 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
14106     AtomicCmpXchgInst *AI) const {
14107   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
14108   // implement cmpxchg without spilling. If the address being exchanged is also
14109   // on the stack and close enough to the spill slot, this can lead to a
14110   // situation where the monitor always gets cleared and the atomic operation
14111   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
14112   bool hasAtomicCmpXchg =
14113       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
14114   return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg;
14115 }
14116 
14117 bool ARMTargetLowering::shouldInsertFencesForAtomic(
14118     const Instruction *I) const {
14119   return InsertFencesForAtomic;
14120 }
14121 
14122 // This has so far only been implemented for MachO.
14123 bool ARMTargetLowering::useLoadStackGuardNode() const {
14124   return Subtarget->isTargetMachO();
14125 }
14126 
14127 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
14128                                                   unsigned &Cost) const {
14129   // If we do not have NEON, vector types are not natively supported.
14130   if (!Subtarget->hasNEON())
14131     return false;
14132 
14133   // Floating point values and vector values map to the same register file.
14134   // Therefore, although we could do a store extract of a vector type, this is
14135   // better to leave at float as we have more freedom in the addressing mode for
14136   // those.
14137   if (VectorTy->isFPOrFPVectorTy())
14138     return false;
14139 
14140   // If the index is unknown at compile time, this is very expensive to lower
14141   // and it is not possible to combine the store with the extract.
14142   if (!isa<ConstantInt>(Idx))
14143     return false;
14144 
14145   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
14146   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
14147   // We can do a store + vector extract on any vector that fits perfectly in a D
14148   // or Q register.
14149   if (BitWidth == 64 || BitWidth == 128) {
14150     Cost = 0;
14151     return true;
14152   }
14153   return false;
14154 }
14155 
14156 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
14157   return Subtarget->hasV6T2Ops();
14158 }
14159 
14160 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
14161   return Subtarget->hasV6T2Ops();
14162 }
14163 
14164 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
14165                                          AtomicOrdering Ord) const {
14166   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14167   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
14168   bool IsAcquire = isAcquireOrStronger(Ord);
14169 
14170   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
14171   // intrinsic must return {i32, i32} and we have to recombine them into a
14172   // single i64 here.
14173   if (ValTy->getPrimitiveSizeInBits() == 64) {
14174     Intrinsic::ID Int =
14175         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
14176     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
14177 
14178     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14179     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
14180 
14181     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
14182     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
14183     if (!Subtarget->isLittle())
14184       std::swap (Lo, Hi);
14185     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
14186     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
14187     return Builder.CreateOr(
14188         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
14189   }
14190 
14191   Type *Tys[] = { Addr->getType() };
14192   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
14193   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
14194 
14195   return Builder.CreateTruncOrBitCast(
14196       Builder.CreateCall(Ldrex, Addr),
14197       cast<PointerType>(Addr->getType())->getElementType());
14198 }
14199 
14200 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
14201     IRBuilder<> &Builder) const {
14202   if (!Subtarget->hasV7Ops())
14203     return;
14204   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14205   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
14206 }
14207 
14208 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
14209                                                Value *Addr,
14210                                                AtomicOrdering Ord) const {
14211   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14212   bool IsRelease = isReleaseOrStronger(Ord);
14213 
14214   // Since the intrinsics must have legal type, the i64 intrinsics take two
14215   // parameters: "i32, i32". We must marshal Val into the appropriate form
14216   // before the call.
14217   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
14218     Intrinsic::ID Int =
14219         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
14220     Function *Strex = Intrinsic::getDeclaration(M, Int);
14221     Type *Int32Ty = Type::getInt32Ty(M->getContext());
14222 
14223     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
14224     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
14225     if (!Subtarget->isLittle())
14226       std::swap(Lo, Hi);
14227     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14228     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
14229   }
14230 
14231   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
14232   Type *Tys[] = { Addr->getType() };
14233   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
14234 
14235   return Builder.CreateCall(
14236       Strex, {Builder.CreateZExtOrBitCast(
14237                   Val, Strex->getFunctionType()->getParamType(0)),
14238               Addr});
14239 }
14240 
14241 /// A helper function for determining the number of interleaved accesses we
14242 /// will generate when lowering accesses of the given type.
14243 unsigned
14244 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
14245                                              const DataLayout &DL) const {
14246   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
14247 }
14248 
14249 bool ARMTargetLowering::isLegalInterleavedAccessType(
14250     VectorType *VecTy, const DataLayout &DL) const {
14251 
14252   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
14253   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
14254 
14255   // Ensure the vector doesn't have f16 elements. Even though we could do an
14256   // i16 vldN, we can't hold the f16 vectors and will end up converting via
14257   // f32.
14258   if (VecTy->getElementType()->isHalfTy())
14259     return false;
14260 
14261   // Ensure the number of vector elements is greater than 1.
14262   if (VecTy->getNumElements() < 2)
14263     return false;
14264 
14265   // Ensure the element type is legal.
14266   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
14267     return false;
14268 
14269   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
14270   // 128 will be split into multiple interleaved accesses.
14271   return VecSize == 64 || VecSize % 128 == 0;
14272 }
14273 
14274 /// \brief Lower an interleaved load into a vldN intrinsic.
14275 ///
14276 /// E.g. Lower an interleaved load (Factor = 2):
14277 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
14278 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
14279 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
14280 ///
14281 ///      Into:
14282 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
14283 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
14284 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
14285 bool ARMTargetLowering::lowerInterleavedLoad(
14286     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
14287     ArrayRef<unsigned> Indices, unsigned Factor) const {
14288   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14289          "Invalid interleave factor");
14290   assert(!Shuffles.empty() && "Empty shufflevector input");
14291   assert(Shuffles.size() == Indices.size() &&
14292          "Unmatched number of shufflevectors and indices");
14293 
14294   VectorType *VecTy = Shuffles[0]->getType();
14295   Type *EltTy = VecTy->getVectorElementType();
14296 
14297   const DataLayout &DL = LI->getModule()->getDataLayout();
14298 
14299   // Skip if we do not have NEON and skip illegal vector types. We can
14300   // "legalize" wide vector types into multiple interleaved accesses as long as
14301   // the vector types are divisible by 128.
14302   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
14303     return false;
14304 
14305   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
14306 
14307   // A pointer vector can not be the return type of the ldN intrinsics. Need to
14308   // load integer vectors first and then convert to pointer vectors.
14309   if (EltTy->isPointerTy())
14310     VecTy =
14311         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
14312 
14313   IRBuilder<> Builder(LI);
14314 
14315   // The base address of the load.
14316   Value *BaseAddr = LI->getPointerOperand();
14317 
14318   if (NumLoads > 1) {
14319     // If we're going to generate more than one load, reset the sub-vector type
14320     // to something legal.
14321     VecTy = VectorType::get(VecTy->getVectorElementType(),
14322                             VecTy->getVectorNumElements() / NumLoads);
14323 
14324     // We will compute the pointer operand of each load from the original base
14325     // address using GEPs. Cast the base address to a pointer to the scalar
14326     // element type.
14327     BaseAddr = Builder.CreateBitCast(
14328         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
14329                       LI->getPointerAddressSpace()));
14330   }
14331 
14332   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
14333 
14334   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
14335   Type *Tys[] = {VecTy, Int8Ptr};
14336   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
14337                                             Intrinsic::arm_neon_vld3,
14338                                             Intrinsic::arm_neon_vld4};
14339   Function *VldnFunc =
14340       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
14341 
14342   // Holds sub-vectors extracted from the load intrinsic return values. The
14343   // sub-vectors are associated with the shufflevector instructions they will
14344   // replace.
14345   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
14346 
14347   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
14348     // If we're generating more than one load, compute the base address of
14349     // subsequent loads as an offset from the previous.
14350     if (LoadCount > 0)
14351       BaseAddr = Builder.CreateConstGEP1_32(
14352           BaseAddr, VecTy->getVectorNumElements() * Factor);
14353 
14354     SmallVector<Value *, 2> Ops;
14355     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14356     Ops.push_back(Builder.getInt32(LI->getAlignment()));
14357 
14358     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
14359 
14360     // Replace uses of each shufflevector with the corresponding vector loaded
14361     // by ldN.
14362     for (unsigned i = 0; i < Shuffles.size(); i++) {
14363       ShuffleVectorInst *SV = Shuffles[i];
14364       unsigned Index = Indices[i];
14365 
14366       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
14367 
14368       // Convert the integer vector to pointer vector if the element is pointer.
14369       if (EltTy->isPointerTy())
14370         SubVec = Builder.CreateIntToPtr(
14371             SubVec, VectorType::get(SV->getType()->getVectorElementType(),
14372                                     VecTy->getVectorNumElements()));
14373 
14374       SubVecs[SV].push_back(SubVec);
14375     }
14376   }
14377 
14378   // Replace uses of the shufflevector instructions with the sub-vectors
14379   // returned by the load intrinsic. If a shufflevector instruction is
14380   // associated with more than one sub-vector, those sub-vectors will be
14381   // concatenated into a single wide vector.
14382   for (ShuffleVectorInst *SVI : Shuffles) {
14383     auto &SubVec = SubVecs[SVI];
14384     auto *WideVec =
14385         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
14386     SVI->replaceAllUsesWith(WideVec);
14387   }
14388 
14389   return true;
14390 }
14391 
14392 /// \brief Lower an interleaved store into a vstN intrinsic.
14393 ///
14394 /// E.g. Lower an interleaved store (Factor = 3):
14395 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
14396 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
14397 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
14398 ///
14399 ///      Into:
14400 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
14401 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
14402 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
14403 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14404 ///
14405 /// Note that the new shufflevectors will be removed and we'll only generate one
14406 /// vst3 instruction in CodeGen.
14407 ///
14408 /// Example for a more general valid mask (Factor 3). Lower:
14409 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
14410 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
14411 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
14412 ///
14413 ///      Into:
14414 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
14415 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
14416 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
14417 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14418 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
14419                                               ShuffleVectorInst *SVI,
14420                                               unsigned Factor) const {
14421   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14422          "Invalid interleave factor");
14423 
14424   VectorType *VecTy = SVI->getType();
14425   assert(VecTy->getVectorNumElements() % Factor == 0 &&
14426          "Invalid interleaved store");
14427 
14428   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
14429   Type *EltTy = VecTy->getVectorElementType();
14430   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
14431 
14432   const DataLayout &DL = SI->getModule()->getDataLayout();
14433 
14434   // Skip if we do not have NEON and skip illegal vector types. We can
14435   // "legalize" wide vector types into multiple interleaved accesses as long as
14436   // the vector types are divisible by 128.
14437   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
14438     return false;
14439 
14440   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
14441 
14442   Value *Op0 = SVI->getOperand(0);
14443   Value *Op1 = SVI->getOperand(1);
14444   IRBuilder<> Builder(SI);
14445 
14446   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
14447   // vectors to integer vectors.
14448   if (EltTy->isPointerTy()) {
14449     Type *IntTy = DL.getIntPtrType(EltTy);
14450 
14451     // Convert to the corresponding integer vector.
14452     Type *IntVecTy =
14453         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
14454     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
14455     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
14456 
14457     SubVecTy = VectorType::get(IntTy, LaneLen);
14458   }
14459 
14460   // The base address of the store.
14461   Value *BaseAddr = SI->getPointerOperand();
14462 
14463   if (NumStores > 1) {
14464     // If we're going to generate more than one store, reset the lane length
14465     // and sub-vector type to something legal.
14466     LaneLen /= NumStores;
14467     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
14468 
14469     // We will compute the pointer operand of each store from the original base
14470     // address using GEPs. Cast the base address to a pointer to the scalar
14471     // element type.
14472     BaseAddr = Builder.CreateBitCast(
14473         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
14474                       SI->getPointerAddressSpace()));
14475   }
14476 
14477   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
14478 
14479   auto Mask = SVI->getShuffleMask();
14480 
14481   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
14482   Type *Tys[] = {Int8Ptr, SubVecTy};
14483   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
14484                                              Intrinsic::arm_neon_vst3,
14485                                              Intrinsic::arm_neon_vst4};
14486 
14487   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
14488     // If we generating more than one store, we compute the base address of
14489     // subsequent stores as an offset from the previous.
14490     if (StoreCount > 0)
14491       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
14492 
14493     SmallVector<Value *, 6> Ops;
14494     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14495 
14496     Function *VstNFunc =
14497         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
14498 
14499     // Split the shufflevector operands into sub vectors for the new vstN call.
14500     for (unsigned i = 0; i < Factor; i++) {
14501       unsigned IdxI = StoreCount * LaneLen * Factor + i;
14502       if (Mask[IdxI] >= 0) {
14503         Ops.push_back(Builder.CreateShuffleVector(
14504             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
14505       } else {
14506         unsigned StartMask = 0;
14507         for (unsigned j = 1; j < LaneLen; j++) {
14508           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
14509           if (Mask[IdxJ * Factor + IdxI] >= 0) {
14510             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
14511             break;
14512           }
14513         }
14514         // Note: If all elements in a chunk are undefs, StartMask=0!
14515         // Note: Filling undef gaps with random elements is ok, since
14516         // those elements were being written anyway (with undefs).
14517         // In the case of all undefs we're defaulting to using elems from 0
14518         // Note: StartMask cannot be negative, it's checked in
14519         // isReInterleaveMask
14520         Ops.push_back(Builder.CreateShuffleVector(
14521             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
14522       }
14523     }
14524 
14525     Ops.push_back(Builder.getInt32(SI->getAlignment()));
14526     Builder.CreateCall(VstNFunc, Ops);
14527   }
14528   return true;
14529 }
14530 
14531 enum HABaseType {
14532   HA_UNKNOWN = 0,
14533   HA_FLOAT,
14534   HA_DOUBLE,
14535   HA_VECT64,
14536   HA_VECT128
14537 };
14538 
14539 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
14540                                    uint64_t &Members) {
14541   if (auto *ST = dyn_cast<StructType>(Ty)) {
14542     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
14543       uint64_t SubMembers = 0;
14544       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
14545         return false;
14546       Members += SubMembers;
14547     }
14548   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
14549     uint64_t SubMembers = 0;
14550     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
14551       return false;
14552     Members += SubMembers * AT->getNumElements();
14553   } else if (Ty->isFloatTy()) {
14554     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
14555       return false;
14556     Members = 1;
14557     Base = HA_FLOAT;
14558   } else if (Ty->isDoubleTy()) {
14559     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
14560       return false;
14561     Members = 1;
14562     Base = HA_DOUBLE;
14563   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
14564     Members = 1;
14565     switch (Base) {
14566     case HA_FLOAT:
14567     case HA_DOUBLE:
14568       return false;
14569     case HA_VECT64:
14570       return VT->getBitWidth() == 64;
14571     case HA_VECT128:
14572       return VT->getBitWidth() == 128;
14573     case HA_UNKNOWN:
14574       switch (VT->getBitWidth()) {
14575       case 64:
14576         Base = HA_VECT64;
14577         return true;
14578       case 128:
14579         Base = HA_VECT128;
14580         return true;
14581       default:
14582         return false;
14583       }
14584     }
14585   }
14586 
14587   return (Members > 0 && Members <= 4);
14588 }
14589 
14590 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
14591 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
14592 /// passing according to AAPCS rules.
14593 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
14594     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
14595   if (getEffectiveCallingConv(CallConv, isVarArg) !=
14596       CallingConv::ARM_AAPCS_VFP)
14597     return false;
14598 
14599   HABaseType Base = HA_UNKNOWN;
14600   uint64_t Members = 0;
14601   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
14602   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
14603 
14604   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
14605   return IsHA || IsIntArray;
14606 }
14607 
14608 unsigned ARMTargetLowering::getExceptionPointerRegister(
14609     const Constant *PersonalityFn) const {
14610   // Platforms which do not use SjLj EH may return values in these registers
14611   // via the personality function.
14612   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
14613 }
14614 
14615 unsigned ARMTargetLowering::getExceptionSelectorRegister(
14616     const Constant *PersonalityFn) const {
14617   // Platforms which do not use SjLj EH may return values in these registers
14618   // via the personality function.
14619   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
14620 }
14621 
14622 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14623   // Update IsSplitCSR in ARMFunctionInfo.
14624   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
14625   AFI->setIsSplitCSR(true);
14626 }
14627 
14628 void ARMTargetLowering::insertCopiesSplitCSR(
14629     MachineBasicBlock *Entry,
14630     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14631   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
14632   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14633   if (!IStart)
14634     return;
14635 
14636   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
14637   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14638   MachineBasicBlock::iterator MBBI = Entry->begin();
14639   for (const MCPhysReg *I = IStart; *I; ++I) {
14640     const TargetRegisterClass *RC = nullptr;
14641     if (ARM::GPRRegClass.contains(*I))
14642       RC = &ARM::GPRRegClass;
14643     else if (ARM::DPRRegClass.contains(*I))
14644       RC = &ARM::DPRRegClass;
14645     else
14646       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14647 
14648     unsigned NewVR = MRI->createVirtualRegister(RC);
14649     // Create copy from CSR to a virtual register.
14650     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14651     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14652     // nounwind. If we want to generalize this later, we may need to emit
14653     // CFI pseudo-instructions.
14654     assert(Entry->getParent()->getFunction().hasFnAttribute(
14655                Attribute::NoUnwind) &&
14656            "Function should be nounwind in insertCopiesSplitCSR!");
14657     Entry->addLiveIn(*I);
14658     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14659         .addReg(*I);
14660 
14661     // Insert the copy-back instructions right before the terminator.
14662     for (auto *Exit : Exits)
14663       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14664               TII->get(TargetOpcode::COPY), *I)
14665           .addReg(NewVR);
14666   }
14667 }
14668 
14669 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
14670   MF.getFrameInfo().computeMaxCallFrameSize(MF);
14671   TargetLoweringBase::finalizeLowering(MF);
14672 }
14673