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/RuntimeLibcalls.h"
57 #include "llvm/CodeGen/SelectionDAG.h"
58 #include "llvm/CodeGen/SelectionDAGNodes.h"
59 #include "llvm/CodeGen/TargetInstrInfo.h"
60 #include "llvm/CodeGen/TargetLowering.h"
61 #include "llvm/CodeGen/TargetOpcodes.h"
62 #include "llvm/CodeGen/TargetRegisterInfo.h"
63 #include "llvm/CodeGen/TargetSubtargetInfo.h"
64 #include "llvm/CodeGen/ValueTypes.h"
65 #include "llvm/IR/Attributes.h"
66 #include "llvm/IR/CallingConv.h"
67 #include "llvm/IR/Constant.h"
68 #include "llvm/IR/Constants.h"
69 #include "llvm/IR/DataLayout.h"
70 #include "llvm/IR/DebugLoc.h"
71 #include "llvm/IR/DerivedTypes.h"
72 #include "llvm/IR/Function.h"
73 #include "llvm/IR/GlobalAlias.h"
74 #include "llvm/IR/GlobalValue.h"
75 #include "llvm/IR/GlobalVariable.h"
76 #include "llvm/IR/IRBuilder.h"
77 #include "llvm/IR/InlineAsm.h"
78 #include "llvm/IR/Instruction.h"
79 #include "llvm/IR/Instructions.h"
80 #include "llvm/IR/IntrinsicInst.h"
81 #include "llvm/IR/Intrinsics.h"
82 #include "llvm/IR/Module.h"
83 #include "llvm/IR/Type.h"
84 #include "llvm/IR/User.h"
85 #include "llvm/IR/Value.h"
86 #include "llvm/MC/MCInstrDesc.h"
87 #include "llvm/MC/MCInstrItineraries.h"
88 #include "llvm/MC/MCRegisterInfo.h"
89 #include "llvm/MC/MCSchedule.h"
90 #include "llvm/Support/AtomicOrdering.h"
91 #include "llvm/Support/BranchProbability.h"
92 #include "llvm/Support/Casting.h"
93 #include "llvm/Support/CodeGen.h"
94 #include "llvm/Support/CommandLine.h"
95 #include "llvm/Support/Compiler.h"
96 #include "llvm/Support/Debug.h"
97 #include "llvm/Support/ErrorHandling.h"
98 #include "llvm/Support/KnownBits.h"
99 #include "llvm/Support/MachineValueType.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 
313   // These libcalls are not available in 32-bit.
314   setLibcallName(RTLIB::SHL_I128, nullptr);
315   setLibcallName(RTLIB::SRL_I128, nullptr);
316   setLibcallName(RTLIB::SRA_I128, nullptr);
317 
318   // RTLIB
319   if (Subtarget->isAAPCS_ABI() &&
320       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
321        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
322     static const struct {
323       const RTLIB::Libcall Op;
324       const char * const Name;
325       const CallingConv::ID CC;
326       const ISD::CondCode Cond;
327     } LibraryCalls[] = {
328       // Double-precision floating-point arithmetic helper functions
329       // RTABI chapter 4.1.2, Table 2
330       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
331       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
332       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
333       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
334 
335       // Double-precision floating-point comparison helper functions
336       // RTABI chapter 4.1.2, Table 3
337       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
338       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
339       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
340       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
341       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
342       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
343       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
344       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
345 
346       // Single-precision floating-point arithmetic helper functions
347       // RTABI chapter 4.1.2, Table 4
348       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
349       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
350       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
351       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
352 
353       // Single-precision floating-point comparison helper functions
354       // RTABI chapter 4.1.2, Table 5
355       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
356       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
357       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
358       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
359       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
360       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
361       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
362       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
363 
364       // Floating-point to integer conversions.
365       // RTABI chapter 4.1.2, Table 6
366       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
367       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
368       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
369       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
370       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
371       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
372       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
373       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
374 
375       // Conversions between floating types.
376       // RTABI chapter 4.1.2, Table 7
377       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
378       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
379       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380 
381       // Integer to floating-point conversions.
382       // RTABI chapter 4.1.2, Table 8
383       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
384       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
385       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
386       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
387       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
388       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
389       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
390       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
391 
392       // Long long helper functions
393       // RTABI chapter 4.2, Table 9
394       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
395       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
396       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
397       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
398 
399       // Integer division functions
400       // RTABI chapter 4.3.1
401       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
402       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
403       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
404       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
406       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
407       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
408       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
409     };
410 
411     for (const auto &LC : LibraryCalls) {
412       setLibcallName(LC.Op, LC.Name);
413       setLibcallCallingConv(LC.Op, LC.CC);
414       if (LC.Cond != ISD::SETCC_INVALID)
415         setCmpLibcallCC(LC.Op, LC.Cond);
416     }
417 
418     // EABI dependent RTLIB
419     if (TM.Options.EABIVersion == EABI::EABI4 ||
420         TM.Options.EABIVersion == EABI::EABI5) {
421       static const struct {
422         const RTLIB::Libcall Op;
423         const char *const Name;
424         const CallingConv::ID CC;
425         const ISD::CondCode Cond;
426       } MemOpsLibraryCalls[] = {
427         // Memory operations
428         // RTABI chapter 4.3.4
429         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
430         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
431         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
432       };
433 
434       for (const auto &LC : MemOpsLibraryCalls) {
435         setLibcallName(LC.Op, LC.Name);
436         setLibcallCallingConv(LC.Op, LC.CC);
437         if (LC.Cond != ISD::SETCC_INVALID)
438           setCmpLibcallCC(LC.Op, LC.Cond);
439       }
440     }
441   }
442 
443   if (Subtarget->isTargetWindows()) {
444     static const struct {
445       const RTLIB::Libcall Op;
446       const char * const Name;
447       const CallingConv::ID CC;
448     } LibraryCalls[] = {
449       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
450       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
451       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
452       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
453       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
454       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
455       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
456       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
457     };
458 
459     for (const auto &LC : LibraryCalls) {
460       setLibcallName(LC.Op, LC.Name);
461       setLibcallCallingConv(LC.Op, LC.CC);
462     }
463   }
464 
465   // Use divmod compiler-rt calls for iOS 5.0 and later.
466   if (Subtarget->isTargetMachO() &&
467       !(Subtarget->isTargetIOS() &&
468         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
469     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
470     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
471   }
472 
473   // The half <-> float conversion functions are always soft-float on
474   // non-watchos platforms, but are needed for some targets which use a
475   // hard-float calling convention by default.
476   if (!Subtarget->isTargetWatchABI()) {
477     if (Subtarget->isAAPCS_ABI()) {
478       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
479       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
480       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
481     } else {
482       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
483       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
484       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
485     }
486   }
487 
488   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
489   // a __gnu_ prefix (which is the default).
490   if (Subtarget->isTargetAEABI()) {
491     static const struct {
492       const RTLIB::Libcall Op;
493       const char * const Name;
494       const CallingConv::ID CC;
495     } LibraryCalls[] = {
496       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
497       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
498       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
499     };
500 
501     for (const auto &LC : LibraryCalls) {
502       setLibcallName(LC.Op, LC.Name);
503       setLibcallCallingConv(LC.Op, LC.CC);
504     }
505   }
506 
507   if (Subtarget->isThumb1Only())
508     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
509   else
510     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
511 
512   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
513       !Subtarget->isThumb1Only()) {
514     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
515     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
516   }
517 
518   if (Subtarget->hasFullFP16()) {
519     addRegisterClass(MVT::f16, &ARM::HPRRegClass);
520     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
521     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
522     setOperationAction(ISD::BITCAST, MVT::f16, Custom);
523 
524     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
525     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
526   }
527 
528   for (MVT VT : MVT::vector_valuetypes()) {
529     for (MVT InnerVT : MVT::vector_valuetypes()) {
530       setTruncStoreAction(VT, InnerVT, Expand);
531       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
532       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
533       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
534     }
535 
536     setOperationAction(ISD::MULHS, VT, Expand);
537     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
538     setOperationAction(ISD::MULHU, VT, Expand);
539     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
540 
541     setOperationAction(ISD::BSWAP, VT, Expand);
542   }
543 
544   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
545   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
546 
547   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
548   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
549 
550   if (Subtarget->hasNEON()) {
551     addDRTypeForNEON(MVT::v2f32);
552     addDRTypeForNEON(MVT::v8i8);
553     addDRTypeForNEON(MVT::v4i16);
554     addDRTypeForNEON(MVT::v2i32);
555     addDRTypeForNEON(MVT::v1i64);
556 
557     addQRTypeForNEON(MVT::v4f32);
558     addQRTypeForNEON(MVT::v2f64);
559     addQRTypeForNEON(MVT::v16i8);
560     addQRTypeForNEON(MVT::v8i16);
561     addQRTypeForNEON(MVT::v4i32);
562     addQRTypeForNEON(MVT::v2i64);
563 
564     if (Subtarget->hasFullFP16()) {
565       addQRTypeForNEON(MVT::v8f16);
566       addDRTypeForNEON(MVT::v4f16);
567     }
568 
569     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
570     // neither Neon nor VFP support any arithmetic operations on it.
571     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
572     // supported for v4f32.
573     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
574     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
575     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
576     // FIXME: Code duplication: FDIV and FREM are expanded always, see
577     // ARMTargetLowering::addTypeForNEON method for details.
578     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
579     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
580     // FIXME: Create unittest.
581     // In another words, find a way when "copysign" appears in DAG with vector
582     // operands.
583     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
584     // FIXME: Code duplication: SETCC has custom operation action, see
585     // ARMTargetLowering::addTypeForNEON method for details.
586     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
587     // FIXME: Create unittest for FNEG and for FABS.
588     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
589     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
590     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
591     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
592     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
593     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
594     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
595     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
596     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
597     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
598     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
599     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
600     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
601     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
602     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
603     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
604     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
605     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
606 
607     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
608     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
609     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
610     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
611     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
612     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
613     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
614     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
615     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
616     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
617     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
618     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
619     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
620     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
621 
622     // Mark v2f32 intrinsics.
623     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
624     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
625     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
626     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
627     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
628     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
629     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
630     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
631     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
632     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
633     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
634     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
635     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
636     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
637 
638     // Neon does not support some operations on v1i64 and v2i64 types.
639     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
640     // Custom handling for some quad-vector types to detect VMULL.
641     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
642     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
643     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
644     // Custom handling for some vector types to avoid expensive expansions
645     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
646     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
647     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
648     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
649     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
650     // a destination type that is wider than the source, and nor does
651     // it have a FP_TO_[SU]INT instruction with a narrower destination than
652     // source.
653     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
654     setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
655     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
656     setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
657     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
658     setOperationAction(ISD::FP_TO_UINT, MVT::v8i16, Custom);
659     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
660     setOperationAction(ISD::FP_TO_SINT, MVT::v8i16, Custom);
661 
662     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
663     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
664 
665     // NEON does not have single instruction CTPOP for vectors with element
666     // types wider than 8-bits.  However, custom lowering can leverage the
667     // v8i8/v16i8 vcnt instruction.
668     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
669     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
670     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
671     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
672     setOperationAction(ISD::CTPOP,      MVT::v1i64, Custom);
673     setOperationAction(ISD::CTPOP,      MVT::v2i64, Custom);
674 
675     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
676     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
677 
678     // NEON does not have single instruction CTTZ for vectors.
679     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
680     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
681     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
682     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
683 
684     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
685     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
686     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
687     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
688 
689     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
690     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
691     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
692     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
693 
694     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
695     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
696     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
697     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
698 
699     // NEON only has FMA instructions as of VFP4.
700     if (!Subtarget->hasVFP4()) {
701       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
702       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
703     }
704 
705     setTargetDAGCombine(ISD::INTRINSIC_VOID);
706     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
707     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
708     setTargetDAGCombine(ISD::SHL);
709     setTargetDAGCombine(ISD::SRL);
710     setTargetDAGCombine(ISD::SRA);
711     setTargetDAGCombine(ISD::SIGN_EXTEND);
712     setTargetDAGCombine(ISD::ZERO_EXTEND);
713     setTargetDAGCombine(ISD::ANY_EXTEND);
714     setTargetDAGCombine(ISD::BUILD_VECTOR);
715     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
716     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
717     setTargetDAGCombine(ISD::STORE);
718     setTargetDAGCombine(ISD::FP_TO_SINT);
719     setTargetDAGCombine(ISD::FP_TO_UINT);
720     setTargetDAGCombine(ISD::FDIV);
721     setTargetDAGCombine(ISD::LOAD);
722 
723     // It is legal to extload from v4i8 to v4i16 or v4i32.
724     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
725                    MVT::v2i32}) {
726       for (MVT VT : MVT::integer_vector_valuetypes()) {
727         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
728         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
729         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
730       }
731     }
732   }
733 
734   if (Subtarget->isFPOnlySP()) {
735     // When targeting a floating-point unit with only single-precision
736     // operations, f64 is legal for the few double-precision instructions which
737     // are present However, no double-precision operations other than moves,
738     // loads and stores are provided by the hardware.
739     setOperationAction(ISD::FADD,       MVT::f64, Expand);
740     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
741     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
742     setOperationAction(ISD::FMA,        MVT::f64, Expand);
743     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
744     setOperationAction(ISD::FREM,       MVT::f64, Expand);
745     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
746     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
747     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
748     setOperationAction(ISD::FABS,       MVT::f64, Expand);
749     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
750     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
751     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
752     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
753     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
754     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
755     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
756     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
757     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
758     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
759     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
760     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
761     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
762     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
763     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
764     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
765     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
766     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
767     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
768     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
769     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
770     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
771   }
772 
773   computeRegisterProperties(Subtarget->getRegisterInfo());
774 
775   // ARM does not have floating-point extending loads.
776   for (MVT VT : MVT::fp_valuetypes()) {
777     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
778     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
779   }
780 
781   // ... or truncating stores
782   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
783   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
784   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
785 
786   // ARM does not have i1 sign extending load.
787   for (MVT VT : MVT::integer_valuetypes())
788     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
789 
790   // ARM supports all 4 flavors of integer indexed load / store.
791   if (!Subtarget->isThumb1Only()) {
792     for (unsigned im = (unsigned)ISD::PRE_INC;
793          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
794       setIndexedLoadAction(im,  MVT::i1,  Legal);
795       setIndexedLoadAction(im,  MVT::i8,  Legal);
796       setIndexedLoadAction(im,  MVT::i16, Legal);
797       setIndexedLoadAction(im,  MVT::i32, Legal);
798       setIndexedStoreAction(im, MVT::i1,  Legal);
799       setIndexedStoreAction(im, MVT::i8,  Legal);
800       setIndexedStoreAction(im, MVT::i16, Legal);
801       setIndexedStoreAction(im, MVT::i32, Legal);
802     }
803   } else {
804     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
805     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
806     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
807   }
808 
809   setOperationAction(ISD::SADDO, MVT::i32, Custom);
810   setOperationAction(ISD::UADDO, MVT::i32, Custom);
811   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
812   setOperationAction(ISD::USUBO, MVT::i32, Custom);
813 
814   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
815   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
816 
817   // i64 operation support.
818   setOperationAction(ISD::MUL,     MVT::i64, Expand);
819   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
820   if (Subtarget->isThumb1Only()) {
821     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
822     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
823   }
824   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
825       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
826     setOperationAction(ISD::MULHS, MVT::i32, Expand);
827 
828   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
829   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
830   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
831   setOperationAction(ISD::SRL,       MVT::i64, Custom);
832   setOperationAction(ISD::SRA,       MVT::i64, Custom);
833   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
834 
835   // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
836   if (Subtarget->isThumb1Only()) {
837     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
838     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
839     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
840   }
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     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, LibCall);
856   }
857 
858   // @llvm.readcyclecounter requires the Performance Monitors extension.
859   // Default to the 0 expansion on unsupported platforms.
860   // FIXME: Technically there are older ARM CPUs that have
861   // implementation-specific ways of obtaining this information.
862   if (Subtarget->hasPerfMon())
863     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
864 
865   // Only ARMv6 has BSWAP.
866   if (!Subtarget->hasV6Ops())
867     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
868 
869   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
870                                         : Subtarget->hasDivideInARMMode();
871   if (!hasDivide) {
872     // These are expanded into libcalls if the cpu doesn't have HW divider.
873     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
874     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
875   }
876 
877   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
878     setOperationAction(ISD::SDIV, MVT::i32, Custom);
879     setOperationAction(ISD::UDIV, MVT::i32, Custom);
880 
881     setOperationAction(ISD::SDIV, MVT::i64, Custom);
882     setOperationAction(ISD::UDIV, MVT::i64, Custom);
883   }
884 
885   setOperationAction(ISD::SREM,  MVT::i32, Expand);
886   setOperationAction(ISD::UREM,  MVT::i32, Expand);
887 
888   // Register based DivRem for AEABI (RTABI 4.2)
889   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
890       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
891       Subtarget->isTargetWindows()) {
892     setOperationAction(ISD::SREM, MVT::i64, Custom);
893     setOperationAction(ISD::UREM, MVT::i64, Custom);
894     HasStandaloneRem = false;
895 
896     if (Subtarget->isTargetWindows()) {
897       const struct {
898         const RTLIB::Libcall Op;
899         const char * const Name;
900         const CallingConv::ID CC;
901       } LibraryCalls[] = {
902         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
903         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
904         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
905         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
906 
907         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
908         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
909         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
910         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
911       };
912 
913       for (const auto &LC : LibraryCalls) {
914         setLibcallName(LC.Op, LC.Name);
915         setLibcallCallingConv(LC.Op, LC.CC);
916       }
917     } else {
918       const struct {
919         const RTLIB::Libcall Op;
920         const char * const Name;
921         const CallingConv::ID CC;
922       } LibraryCalls[] = {
923         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
924         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
925         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
926         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
927 
928         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
929         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
930         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
931         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
932       };
933 
934       for (const auto &LC : LibraryCalls) {
935         setLibcallName(LC.Op, LC.Name);
936         setLibcallCallingConv(LC.Op, LC.CC);
937       }
938     }
939 
940     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
941     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
942     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
943     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
944   } else {
945     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
946     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
947   }
948 
949   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
950     for (auto &VT : {MVT::f32, MVT::f64})
951       setOperationAction(ISD::FPOWI, VT, Custom);
952 
953   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
954   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
955   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
956   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
957 
958   setOperationAction(ISD::TRAP, MVT::Other, Legal);
959   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
960 
961   // Use the default implementation.
962   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
963   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
964   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
965   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
966   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
967   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
968 
969   if (Subtarget->isTargetWindows())
970     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
971   else
972     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
973 
974   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
975   // the default expansion.
976   InsertFencesForAtomic = false;
977   if (Subtarget->hasAnyDataBarrier() &&
978       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
979     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
980     // to ldrex/strex loops already.
981     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
982     if (!Subtarget->isThumb() || !Subtarget->isMClass())
983       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
984 
985     // On v8, we have particularly efficient implementations of atomic fences
986     // if they can be combined with nearby atomic loads and stores.
987     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
988       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
989       InsertFencesForAtomic = true;
990     }
991   } else {
992     // If there's anything we can use as a barrier, go through custom lowering
993     // for ATOMIC_FENCE.
994     // If target has DMB in thumb, Fences can be inserted.
995     if (Subtarget->hasDataBarrier())
996       InsertFencesForAtomic = true;
997 
998     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
999                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1000 
1001     // Set them all for expansion, which will force libcalls.
1002     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1003     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1004     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1005     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1006     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1007     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1008     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1009     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1010     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1011     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1012     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1013     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1014     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1015     // Unordered/Monotonic case.
1016     if (!InsertFencesForAtomic) {
1017       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1018       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1019     }
1020   }
1021 
1022   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1023 
1024   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1025   if (!Subtarget->hasV6Ops()) {
1026     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1027     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1028   }
1029   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1030 
1031   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1032       !Subtarget->isThumb1Only()) {
1033     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1034     // iff target supports vfp2.
1035     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1036     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1037   }
1038 
1039   // We want to custom lower some of our intrinsics.
1040   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1041   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1042   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1043   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1044   if (Subtarget->useSjLjEH())
1045     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1046 
1047   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1048   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1049   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1050   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1051   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1052   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1053   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1054   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1055   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1056   if (Subtarget->hasFullFP16()) {
1057     setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1058     setOperationAction(ISD::SELECT,    MVT::f16, Custom);
1059     setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1060   }
1061 
1062   setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1063 
1064   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1065   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1066   if (Subtarget->hasFullFP16())
1067       setOperationAction(ISD::BR_CC, MVT::f16,   Custom);
1068   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1069   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1070   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1071 
1072   // We don't support sin/cos/fmod/copysign/pow
1073   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1074   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1075   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1076   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1077   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1078   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1079   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1080   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1081   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1082       !Subtarget->isThumb1Only()) {
1083     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1084     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1085   }
1086   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1087   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1088 
1089   if (!Subtarget->hasVFP4()) {
1090     setOperationAction(ISD::FMA, MVT::f64, Expand);
1091     setOperationAction(ISD::FMA, MVT::f32, Expand);
1092   }
1093 
1094   // Various VFP goodness
1095   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1096     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1097     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1098       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1099       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1100     }
1101 
1102     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1103     if (!Subtarget->hasFP16()) {
1104       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1105       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1106     }
1107   }
1108 
1109   // Use __sincos_stret if available.
1110   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1111       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1112     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1113     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1114   }
1115 
1116   // FP-ARMv8 implements a lot of rounding-like FP operations.
1117   if (Subtarget->hasFPARMv8()) {
1118     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1119     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1120     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1121     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1122     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1123     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1124     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1125     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1126     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1127     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1128     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1129     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1130 
1131     if (!Subtarget->isFPOnlySP()) {
1132       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1133       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1134       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1135       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1136       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1137       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1138       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1139       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1140     }
1141   }
1142 
1143   if (Subtarget->hasNEON()) {
1144     // vmin and vmax aren't available in a scalar form, so we use
1145     // a NEON instruction with an undef lane instead.
1146     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1147     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1148     setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1149     setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1150     setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1151     setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1152     setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1153     setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1154 
1155     if (Subtarget->hasFullFP16()) {
1156       setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1157       setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1158       setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1159       setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1160 
1161       setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1162       setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1163       setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1164       setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1165     }
1166   }
1167 
1168   // We have target-specific dag combine patterns for the following nodes:
1169   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1170   setTargetDAGCombine(ISD::ADD);
1171   setTargetDAGCombine(ISD::SUB);
1172   setTargetDAGCombine(ISD::MUL);
1173   setTargetDAGCombine(ISD::AND);
1174   setTargetDAGCombine(ISD::OR);
1175   setTargetDAGCombine(ISD::XOR);
1176 
1177   if (Subtarget->hasV6Ops())
1178     setTargetDAGCombine(ISD::SRL);
1179 
1180   setStackPointerRegisterToSaveRestore(ARM::SP);
1181 
1182   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1183       !Subtarget->hasVFP2())
1184     setSchedulingPreference(Sched::RegPressure);
1185   else
1186     setSchedulingPreference(Sched::Hybrid);
1187 
1188   //// temporary - rewrite interface to use type
1189   MaxStoresPerMemset = 8;
1190   MaxStoresPerMemsetOptSize = 4;
1191   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1192   MaxStoresPerMemcpyOptSize = 2;
1193   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1194   MaxStoresPerMemmoveOptSize = 2;
1195 
1196   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1197   // are at least 4 bytes aligned.
1198   setMinStackArgumentAlignment(4);
1199 
1200   // Prefer likely predicted branches to selects on out-of-order cores.
1201   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1202 
1203   setPrefLoopAlignment(Subtarget->getPrefLoopAlignment());
1204 
1205   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1206 }
1207 
1208 bool ARMTargetLowering::useSoftFloat() const {
1209   return Subtarget->useSoftFloat();
1210 }
1211 
1212 // FIXME: It might make sense to define the representative register class as the
1213 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1214 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1215 // SPR's representative would be DPR_VFP2. This should work well if register
1216 // pressure tracking were modified such that a register use would increment the
1217 // pressure of the register class's representative and all of it's super
1218 // classes' representatives transitively. We have not implemented this because
1219 // of the difficulty prior to coalescing of modeling operand register classes
1220 // due to the common occurrence of cross class copies and subregister insertions
1221 // and extractions.
1222 std::pair<const TargetRegisterClass *, uint8_t>
1223 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1224                                            MVT VT) const {
1225   const TargetRegisterClass *RRC = nullptr;
1226   uint8_t Cost = 1;
1227   switch (VT.SimpleTy) {
1228   default:
1229     return TargetLowering::findRepresentativeClass(TRI, VT);
1230   // Use DPR as representative register class for all floating point
1231   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1232   // the cost is 1 for both f32 and f64.
1233   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1234   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1235     RRC = &ARM::DPRRegClass;
1236     // When NEON is used for SP, only half of the register file is available
1237     // because operations that define both SP and DP results will be constrained
1238     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1239     // coalescing by double-counting the SP regs. See the FIXME above.
1240     if (Subtarget->useNEONForSinglePrecisionFP())
1241       Cost = 2;
1242     break;
1243   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1244   case MVT::v4f32: case MVT::v2f64:
1245     RRC = &ARM::DPRRegClass;
1246     Cost = 2;
1247     break;
1248   case MVT::v4i64:
1249     RRC = &ARM::DPRRegClass;
1250     Cost = 4;
1251     break;
1252   case MVT::v8i64:
1253     RRC = &ARM::DPRRegClass;
1254     Cost = 8;
1255     break;
1256   }
1257   return std::make_pair(RRC, Cost);
1258 }
1259 
1260 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1261   switch ((ARMISD::NodeType)Opcode) {
1262   case ARMISD::FIRST_NUMBER:  break;
1263   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1264   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1265   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1266   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1267   case ARMISD::CALL:          return "ARMISD::CALL";
1268   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1269   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1270   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1271   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1272   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1273   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1274   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1275   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1276   case ARMISD::CMP:           return "ARMISD::CMP";
1277   case ARMISD::CMN:           return "ARMISD::CMN";
1278   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1279   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1280   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1281   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1282   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1283 
1284   case ARMISD::CMOV:          return "ARMISD::CMOV";
1285 
1286   case ARMISD::SSAT:          return "ARMISD::SSAT";
1287   case ARMISD::USAT:          return "ARMISD::USAT";
1288 
1289   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1290   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1291   case ARMISD::RRX:           return "ARMISD::RRX";
1292 
1293   case ARMISD::ADDC:          return "ARMISD::ADDC";
1294   case ARMISD::ADDE:          return "ARMISD::ADDE";
1295   case ARMISD::SUBC:          return "ARMISD::SUBC";
1296   case ARMISD::SUBE:          return "ARMISD::SUBE";
1297 
1298   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1299   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1300   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
1301   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
1302   case ARMISD::VMOVSR:        return "ARMISD::VMOVSR";
1303 
1304   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1305   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1306   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1307 
1308   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1309 
1310   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1311 
1312   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1313 
1314   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1315 
1316   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1317 
1318   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1319   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1320 
1321   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1322   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1323   case ARMISD::VCGE:          return "ARMISD::VCGE";
1324   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1325   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1326   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1327   case ARMISD::VCGT:          return "ARMISD::VCGT";
1328   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1329   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1330   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1331   case ARMISD::VTST:          return "ARMISD::VTST";
1332 
1333   case ARMISD::VSHL:          return "ARMISD::VSHL";
1334   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1335   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1336   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1337   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1338   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1339   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1340   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1341   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1342   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1343   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1344   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1345   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1346   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1347   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1348   case ARMISD::VSLI:          return "ARMISD::VSLI";
1349   case ARMISD::VSRI:          return "ARMISD::VSRI";
1350   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1351   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1352   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1353   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1354   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1355   case ARMISD::VDUP:          return "ARMISD::VDUP";
1356   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1357   case ARMISD::VEXT:          return "ARMISD::VEXT";
1358   case ARMISD::VREV64:        return "ARMISD::VREV64";
1359   case ARMISD::VREV32:        return "ARMISD::VREV32";
1360   case ARMISD::VREV16:        return "ARMISD::VREV16";
1361   case ARMISD::VZIP:          return "ARMISD::VZIP";
1362   case ARMISD::VUZP:          return "ARMISD::VUZP";
1363   case ARMISD::VTRN:          return "ARMISD::VTRN";
1364   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1365   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1366   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1367   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1368   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1369   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1370   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1371   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1372   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1373   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1374   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1375   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1376   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1377   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1378   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1379   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1380   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1381   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1382   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1383   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1384   case ARMISD::BFI:           return "ARMISD::BFI";
1385   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1386   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1387   case ARMISD::VBSL:          return "ARMISD::VBSL";
1388   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1389   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1390   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1391   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1392   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1393   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1394   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1395   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1396   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1397   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1398   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1399   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1400   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1401   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1402   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1403   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1404   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1405   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1406   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1407   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1408   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1409   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1410   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1411   }
1412   return nullptr;
1413 }
1414 
1415 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1416                                           EVT VT) const {
1417   if (!VT.isVector())
1418     return getPointerTy(DL);
1419   return VT.changeVectorElementTypeToInteger();
1420 }
1421 
1422 /// getRegClassFor - Return the register class that should be used for the
1423 /// specified value type.
1424 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1425   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1426   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1427   // load / store 4 to 8 consecutive D registers.
1428   if (Subtarget->hasNEON()) {
1429     if (VT == MVT::v4i64)
1430       return &ARM::QQPRRegClass;
1431     if (VT == MVT::v8i64)
1432       return &ARM::QQQQPRRegClass;
1433   }
1434   return TargetLowering::getRegClassFor(VT);
1435 }
1436 
1437 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1438 // source/dest is aligned and the copy size is large enough. We therefore want
1439 // to align such objects passed to memory intrinsics.
1440 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1441                                                unsigned &PrefAlign) const {
1442   if (!isa<MemIntrinsic>(CI))
1443     return false;
1444   MinSize = 8;
1445   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1446   // cycle faster than 4-byte aligned LDM.
1447   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1448   return true;
1449 }
1450 
1451 // Create a fast isel object.
1452 FastISel *
1453 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1454                                   const TargetLibraryInfo *libInfo) const {
1455   return ARM::createFastISel(funcInfo, libInfo);
1456 }
1457 
1458 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1459   unsigned NumVals = N->getNumValues();
1460   if (!NumVals)
1461     return Sched::RegPressure;
1462 
1463   for (unsigned i = 0; i != NumVals; ++i) {
1464     EVT VT = N->getValueType(i);
1465     if (VT == MVT::Glue || VT == MVT::Other)
1466       continue;
1467     if (VT.isFloatingPoint() || VT.isVector())
1468       return Sched::ILP;
1469   }
1470 
1471   if (!N->isMachineOpcode())
1472     return Sched::RegPressure;
1473 
1474   // Load are scheduled for latency even if there instruction itinerary
1475   // is not available.
1476   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1477   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1478 
1479   if (MCID.getNumDefs() == 0)
1480     return Sched::RegPressure;
1481   if (!Itins->isEmpty() &&
1482       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1483     return Sched::ILP;
1484 
1485   return Sched::RegPressure;
1486 }
1487 
1488 //===----------------------------------------------------------------------===//
1489 // Lowering Code
1490 //===----------------------------------------------------------------------===//
1491 
1492 static bool isSRL16(const SDValue &Op) {
1493   if (Op.getOpcode() != ISD::SRL)
1494     return false;
1495   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1496     return Const->getZExtValue() == 16;
1497   return false;
1498 }
1499 
1500 static bool isSRA16(const SDValue &Op) {
1501   if (Op.getOpcode() != ISD::SRA)
1502     return false;
1503   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1504     return Const->getZExtValue() == 16;
1505   return false;
1506 }
1507 
1508 static bool isSHL16(const SDValue &Op) {
1509   if (Op.getOpcode() != ISD::SHL)
1510     return false;
1511   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1512     return Const->getZExtValue() == 16;
1513   return false;
1514 }
1515 
1516 // Check for a signed 16-bit value. We special case SRA because it makes it
1517 // more simple when also looking for SRAs that aren't sign extending a
1518 // smaller value. Without the check, we'd need to take extra care with
1519 // checking order for some operations.
1520 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1521   if (isSRA16(Op))
1522     return isSHL16(Op.getOperand(0));
1523   return DAG.ComputeNumSignBits(Op) == 17;
1524 }
1525 
1526 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1527 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1528   switch (CC) {
1529   default: llvm_unreachable("Unknown condition code!");
1530   case ISD::SETNE:  return ARMCC::NE;
1531   case ISD::SETEQ:  return ARMCC::EQ;
1532   case ISD::SETGT:  return ARMCC::GT;
1533   case ISD::SETGE:  return ARMCC::GE;
1534   case ISD::SETLT:  return ARMCC::LT;
1535   case ISD::SETLE:  return ARMCC::LE;
1536   case ISD::SETUGT: return ARMCC::HI;
1537   case ISD::SETUGE: return ARMCC::HS;
1538   case ISD::SETULT: return ARMCC::LO;
1539   case ISD::SETULE: return ARMCC::LS;
1540   }
1541 }
1542 
1543 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1544 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1545                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1546   CondCode2 = ARMCC::AL;
1547   InvalidOnQNaN = true;
1548   switch (CC) {
1549   default: llvm_unreachable("Unknown FP condition!");
1550   case ISD::SETEQ:
1551   case ISD::SETOEQ:
1552     CondCode = ARMCC::EQ;
1553     InvalidOnQNaN = false;
1554     break;
1555   case ISD::SETGT:
1556   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1557   case ISD::SETGE:
1558   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1559   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1560   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1561   case ISD::SETONE:
1562     CondCode = ARMCC::MI;
1563     CondCode2 = ARMCC::GT;
1564     InvalidOnQNaN = false;
1565     break;
1566   case ISD::SETO:   CondCode = ARMCC::VC; break;
1567   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1568   case ISD::SETUEQ:
1569     CondCode = ARMCC::EQ;
1570     CondCode2 = ARMCC::VS;
1571     InvalidOnQNaN = false;
1572     break;
1573   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1574   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1575   case ISD::SETLT:
1576   case ISD::SETULT: CondCode = ARMCC::LT; break;
1577   case ISD::SETLE:
1578   case ISD::SETULE: CondCode = ARMCC::LE; break;
1579   case ISD::SETNE:
1580   case ISD::SETUNE:
1581     CondCode = ARMCC::NE;
1582     InvalidOnQNaN = false;
1583     break;
1584   }
1585 }
1586 
1587 //===----------------------------------------------------------------------===//
1588 //                      Calling Convention Implementation
1589 //===----------------------------------------------------------------------===//
1590 
1591 #include "ARMGenCallingConv.inc"
1592 
1593 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1594 /// account presence of floating point hardware and calling convention
1595 /// limitations, such as support for variadic functions.
1596 CallingConv::ID
1597 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1598                                            bool isVarArg) const {
1599   switch (CC) {
1600   default:
1601     report_fatal_error("Unsupported calling convention");
1602   case CallingConv::ARM_AAPCS:
1603   case CallingConv::ARM_APCS:
1604   case CallingConv::GHC:
1605     return CC;
1606   case CallingConv::PreserveMost:
1607     return CallingConv::PreserveMost;
1608   case CallingConv::ARM_AAPCS_VFP:
1609   case CallingConv::Swift:
1610     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1611   case CallingConv::C:
1612     if (!Subtarget->isAAPCS_ABI())
1613       return CallingConv::ARM_APCS;
1614     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1615              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1616              !isVarArg)
1617       return CallingConv::ARM_AAPCS_VFP;
1618     else
1619       return CallingConv::ARM_AAPCS;
1620   case CallingConv::Fast:
1621   case CallingConv::CXX_FAST_TLS:
1622     if (!Subtarget->isAAPCS_ABI()) {
1623       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1624         return CallingConv::Fast;
1625       return CallingConv::ARM_APCS;
1626     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1627       return CallingConv::ARM_AAPCS_VFP;
1628     else
1629       return CallingConv::ARM_AAPCS;
1630   }
1631 }
1632 
1633 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1634                                                  bool isVarArg) const {
1635   return CCAssignFnForNode(CC, false, isVarArg);
1636 }
1637 
1638 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1639                                                    bool isVarArg) const {
1640   return CCAssignFnForNode(CC, true, isVarArg);
1641 }
1642 
1643 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1644 /// CallingConvention.
1645 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1646                                                  bool Return,
1647                                                  bool isVarArg) const {
1648   switch (getEffectiveCallingConv(CC, isVarArg)) {
1649   default:
1650     report_fatal_error("Unsupported calling convention");
1651   case CallingConv::ARM_APCS:
1652     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1653   case CallingConv::ARM_AAPCS:
1654     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1655   case CallingConv::ARM_AAPCS_VFP:
1656     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1657   case CallingConv::Fast:
1658     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1659   case CallingConv::GHC:
1660     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1661   case CallingConv::PreserveMost:
1662     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1663   }
1664 }
1665 
1666 /// LowerCallResult - Lower the result values of a call into the
1667 /// appropriate copies out of appropriate physical registers.
1668 SDValue ARMTargetLowering::LowerCallResult(
1669     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1670     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1671     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1672     SDValue ThisVal) const {
1673   // Assign locations to each value returned by this call.
1674   SmallVector<CCValAssign, 16> RVLocs;
1675   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1676                  *DAG.getContext());
1677   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1678 
1679   // Copy all of the result registers out of their specified physreg.
1680   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1681     CCValAssign VA = RVLocs[i];
1682 
1683     // Pass 'this' value directly from the argument to return value, to avoid
1684     // reg unit interference
1685     if (i == 0 && isThisReturn) {
1686       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1687              "unexpected return calling convention register assignment");
1688       InVals.push_back(ThisVal);
1689       continue;
1690     }
1691 
1692     SDValue Val;
1693     if (VA.needsCustom()) {
1694       // Handle f64 or half of a v2f64.
1695       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1696                                       InFlag);
1697       Chain = Lo.getValue(1);
1698       InFlag = Lo.getValue(2);
1699       VA = RVLocs[++i]; // skip ahead to next loc
1700       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1701                                       InFlag);
1702       Chain = Hi.getValue(1);
1703       InFlag = Hi.getValue(2);
1704       if (!Subtarget->isLittle())
1705         std::swap (Lo, Hi);
1706       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1707 
1708       if (VA.getLocVT() == MVT::v2f64) {
1709         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1710         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1711                           DAG.getConstant(0, dl, MVT::i32));
1712 
1713         VA = RVLocs[++i]; // skip ahead to next loc
1714         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1715         Chain = Lo.getValue(1);
1716         InFlag = Lo.getValue(2);
1717         VA = RVLocs[++i]; // skip ahead to next loc
1718         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1719         Chain = Hi.getValue(1);
1720         InFlag = Hi.getValue(2);
1721         if (!Subtarget->isLittle())
1722           std::swap (Lo, Hi);
1723         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1724         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1725                           DAG.getConstant(1, dl, MVT::i32));
1726       }
1727     } else {
1728       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1729                                InFlag);
1730       Chain = Val.getValue(1);
1731       InFlag = Val.getValue(2);
1732     }
1733 
1734     switch (VA.getLocInfo()) {
1735     default: llvm_unreachable("Unknown loc info!");
1736     case CCValAssign::Full: break;
1737     case CCValAssign::BCvt:
1738       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1739       break;
1740     }
1741 
1742     InVals.push_back(Val);
1743   }
1744 
1745   return Chain;
1746 }
1747 
1748 /// LowerMemOpCallTo - Store the argument to the stack.
1749 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1750                                             SDValue Arg, const SDLoc &dl,
1751                                             SelectionDAG &DAG,
1752                                             const CCValAssign &VA,
1753                                             ISD::ArgFlagsTy Flags) const {
1754   unsigned LocMemOffset = VA.getLocMemOffset();
1755   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1756   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1757                        StackPtr, PtrOff);
1758   return DAG.getStore(
1759       Chain, dl, Arg, PtrOff,
1760       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1761 }
1762 
1763 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1764                                          SDValue Chain, SDValue &Arg,
1765                                          RegsToPassVector &RegsToPass,
1766                                          CCValAssign &VA, CCValAssign &NextVA,
1767                                          SDValue &StackPtr,
1768                                          SmallVectorImpl<SDValue> &MemOpChains,
1769                                          ISD::ArgFlagsTy Flags) const {
1770   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1771                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1772   unsigned id = Subtarget->isLittle() ? 0 : 1;
1773   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1774 
1775   if (NextVA.isRegLoc())
1776     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1777   else {
1778     assert(NextVA.isMemLoc());
1779     if (!StackPtr.getNode())
1780       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1781                                     getPointerTy(DAG.getDataLayout()));
1782 
1783     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1784                                            dl, DAG, NextVA,
1785                                            Flags));
1786   }
1787 }
1788 
1789 /// LowerCall - Lowering a call into a callseq_start <-
1790 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1791 /// nodes.
1792 SDValue
1793 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1794                              SmallVectorImpl<SDValue> &InVals) const {
1795   SelectionDAG &DAG                     = CLI.DAG;
1796   SDLoc &dl                             = CLI.DL;
1797   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1798   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1799   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1800   SDValue Chain                         = CLI.Chain;
1801   SDValue Callee                        = CLI.Callee;
1802   bool &isTailCall                      = CLI.IsTailCall;
1803   CallingConv::ID CallConv              = CLI.CallConv;
1804   bool doesNotRet                       = CLI.DoesNotReturn;
1805   bool isVarArg                         = CLI.IsVarArg;
1806 
1807   MachineFunction &MF = DAG.getMachineFunction();
1808   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1809   bool isThisReturn   = false;
1810   bool isSibCall      = false;
1811   auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
1812 
1813   // Disable tail calls if they're not supported.
1814   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1815     isTailCall = false;
1816 
1817   if (isTailCall) {
1818     // Check if it's really possible to do a tail call.
1819     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1820                     isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(),
1821                                                    Outs, OutVals, Ins, DAG);
1822     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1823       report_fatal_error("failed to perform tail call elimination on a call "
1824                          "site marked musttail");
1825     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1826     // detected sibcalls.
1827     if (isTailCall) {
1828       ++NumTailCalls;
1829       isSibCall = true;
1830     }
1831   }
1832 
1833   // Analyze operands of the call, assigning locations to each operand.
1834   SmallVector<CCValAssign, 16> ArgLocs;
1835   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1836                  *DAG.getContext());
1837   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1838 
1839   // Get a count of how many bytes are to be pushed on the stack.
1840   unsigned NumBytes = CCInfo.getNextStackOffset();
1841 
1842   // For tail calls, memory operands are available in our caller's stack.
1843   if (isSibCall)
1844     NumBytes = 0;
1845 
1846   // Adjust the stack pointer for the new arguments...
1847   // These operations are automatically eliminated by the prolog/epilog pass
1848   if (!isSibCall)
1849     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1850 
1851   SDValue StackPtr =
1852       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1853 
1854   RegsToPassVector RegsToPass;
1855   SmallVector<SDValue, 8> MemOpChains;
1856 
1857   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1858   // of tail call optimization, arguments are handled later.
1859   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1860        i != e;
1861        ++i, ++realArgIdx) {
1862     CCValAssign &VA = ArgLocs[i];
1863     SDValue Arg = OutVals[realArgIdx];
1864     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1865     bool isByVal = Flags.isByVal();
1866 
1867     // Promote the value if needed.
1868     switch (VA.getLocInfo()) {
1869     default: llvm_unreachable("Unknown loc info!");
1870     case CCValAssign::Full: break;
1871     case CCValAssign::SExt:
1872       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1873       break;
1874     case CCValAssign::ZExt:
1875       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1876       break;
1877     case CCValAssign::AExt:
1878       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1879       break;
1880     case CCValAssign::BCvt:
1881       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1882       break;
1883     }
1884 
1885     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1886     if (VA.needsCustom()) {
1887       if (VA.getLocVT() == MVT::v2f64) {
1888         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1889                                   DAG.getConstant(0, dl, MVT::i32));
1890         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1891                                   DAG.getConstant(1, dl, MVT::i32));
1892 
1893         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1894                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1895 
1896         VA = ArgLocs[++i]; // skip ahead to next loc
1897         if (VA.isRegLoc()) {
1898           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1899                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1900         } else {
1901           assert(VA.isMemLoc());
1902 
1903           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1904                                                  dl, DAG, VA, Flags));
1905         }
1906       } else {
1907         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1908                          StackPtr, MemOpChains, Flags);
1909       }
1910     } else if (VA.isRegLoc()) {
1911       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1912           Outs[0].VT == MVT::i32) {
1913         assert(VA.getLocVT() == MVT::i32 &&
1914                "unexpected calling convention register assignment");
1915         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1916                "unexpected use of 'returned'");
1917         isThisReturn = true;
1918       }
1919       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1920     } else if (isByVal) {
1921       assert(VA.isMemLoc());
1922       unsigned offset = 0;
1923 
1924       // True if this byval aggregate will be split between registers
1925       // and memory.
1926       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1927       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1928 
1929       if (CurByValIdx < ByValArgsCount) {
1930 
1931         unsigned RegBegin, RegEnd;
1932         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1933 
1934         EVT PtrVT =
1935             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1936         unsigned int i, j;
1937         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1938           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1939           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1940           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1941                                      MachinePointerInfo(),
1942                                      DAG.InferPtrAlignment(AddArg));
1943           MemOpChains.push_back(Load.getValue(1));
1944           RegsToPass.push_back(std::make_pair(j, Load));
1945         }
1946 
1947         // If parameter size outsides register area, "offset" value
1948         // helps us to calculate stack slot for remained part properly.
1949         offset = RegEnd - RegBegin;
1950 
1951         CCInfo.nextInRegsParam();
1952       }
1953 
1954       if (Flags.getByValSize() > 4*offset) {
1955         auto PtrVT = getPointerTy(DAG.getDataLayout());
1956         unsigned LocMemOffset = VA.getLocMemOffset();
1957         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1958         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1959         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1960         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1961         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1962                                            MVT::i32);
1963         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1964                                             MVT::i32);
1965 
1966         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1967         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1968         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1969                                           Ops));
1970       }
1971     } else if (!isSibCall) {
1972       assert(VA.isMemLoc());
1973 
1974       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1975                                              dl, DAG, VA, Flags));
1976     }
1977   }
1978 
1979   if (!MemOpChains.empty())
1980     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1981 
1982   // Build a sequence of copy-to-reg nodes chained together with token chain
1983   // and flag operands which copy the outgoing args into the appropriate regs.
1984   SDValue InFlag;
1985   // Tail call byval lowering might overwrite argument registers so in case of
1986   // tail call optimization the copies to registers are lowered later.
1987   if (!isTailCall)
1988     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1989       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1990                                RegsToPass[i].second, InFlag);
1991       InFlag = Chain.getValue(1);
1992     }
1993 
1994   // For tail calls lower the arguments to the 'real' stack slot.
1995   if (isTailCall) {
1996     // Force all the incoming stack arguments to be loaded from the stack
1997     // before any new outgoing arguments are stored to the stack, because the
1998     // outgoing stack slots may alias the incoming argument stack slots, and
1999     // the alias isn't otherwise explicit. This is slightly more conservative
2000     // than necessary, because it means that each store effectively depends
2001     // on every argument instead of just those arguments it would clobber.
2002 
2003     // Do not flag preceding copytoreg stuff together with the following stuff.
2004     InFlag = SDValue();
2005     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2006       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2007                                RegsToPass[i].second, InFlag);
2008       InFlag = Chain.getValue(1);
2009     }
2010     InFlag = SDValue();
2011   }
2012 
2013   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2014   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2015   // node so that legalize doesn't hack it.
2016   bool isDirect = false;
2017 
2018   const TargetMachine &TM = getTargetMachine();
2019   const Module *Mod = MF.getFunction().getParent();
2020   const GlobalValue *GV = nullptr;
2021   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2022     GV = G->getGlobal();
2023   bool isStub =
2024       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2025 
2026   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2027   bool isLocalARMFunc = false;
2028   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2029   auto PtrVt = getPointerTy(DAG.getDataLayout());
2030 
2031   if (Subtarget->genLongCalls()) {
2032     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2033            "long-calls codegen is not position independent!");
2034     // Handle a global address or an external symbol. If it's not one of
2035     // those, the target's already in a register, so we don't need to do
2036     // anything extra.
2037     if (isa<GlobalAddressSDNode>(Callee)) {
2038       // Create a constant pool entry for the callee address
2039       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2040       ARMConstantPoolValue *CPV =
2041         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2042 
2043       // Get the address of the callee into a register
2044       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2045       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2046       Callee = DAG.getLoad(
2047           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2048           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2049     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2050       const char *Sym = S->getSymbol();
2051 
2052       // Create a constant pool entry for the callee address
2053       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2054       ARMConstantPoolValue *CPV =
2055         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2056                                       ARMPCLabelIndex, 0);
2057       // Get the address of the callee into a register
2058       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2059       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2060       Callee = DAG.getLoad(
2061           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2062           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2063     }
2064   } else if (isa<GlobalAddressSDNode>(Callee)) {
2065     // If we're optimizing for minimum size and the function is called three or
2066     // more times in this block, we can improve codesize by calling indirectly
2067     // as BLXr has a 16-bit encoding.
2068     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2069     auto *BB = CLI.CS.getParent();
2070     bool PreferIndirect =
2071         Subtarget->isThumb() && MF.getFunction().optForMinSize() &&
2072         count_if(GV->users(), [&BB](const User *U) {
2073           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2074         }) > 2;
2075 
2076     if (!PreferIndirect) {
2077       isDirect = true;
2078       bool isDef = GV->isStrongDefinitionForLinker();
2079 
2080       // ARM call to a local ARM function is predicable.
2081       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2082       // tBX takes a register source operand.
2083       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2084         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2085         Callee = DAG.getNode(
2086             ARMISD::WrapperPIC, dl, PtrVt,
2087             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2088         Callee = DAG.getLoad(
2089             PtrVt, dl, DAG.getEntryNode(), Callee,
2090             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2091             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2092                                      MachineMemOperand::MOInvariant);
2093       } else if (Subtarget->isTargetCOFF()) {
2094         assert(Subtarget->isTargetWindows() &&
2095                "Windows is the only supported COFF target");
2096         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2097                                    ? ARMII::MO_DLLIMPORT
2098                                    : ARMII::MO_NO_FLAG;
2099         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2100                                             TargetFlags);
2101         if (GV->hasDLLImportStorageClass())
2102           Callee =
2103               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2104                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2105                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2106       } else {
2107         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2108       }
2109     }
2110   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2111     isDirect = true;
2112     // tBX takes a register source operand.
2113     const char *Sym = S->getSymbol();
2114     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2115       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2116       ARMConstantPoolValue *CPV =
2117         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2118                                       ARMPCLabelIndex, 4);
2119       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2120       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2121       Callee = DAG.getLoad(
2122           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2123           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2124       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2125       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2126     } else {
2127       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2128     }
2129   }
2130 
2131   // FIXME: handle tail calls differently.
2132   unsigned CallOpc;
2133   if (Subtarget->isThumb()) {
2134     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2135       CallOpc = ARMISD::CALL_NOLINK;
2136     else
2137       CallOpc = ARMISD::CALL;
2138   } else {
2139     if (!isDirect && !Subtarget->hasV5TOps())
2140       CallOpc = ARMISD::CALL_NOLINK;
2141     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2142              // Emit regular call when code size is the priority
2143              !MF.getFunction().optForMinSize())
2144       // "mov lr, pc; b _foo" to avoid confusing the RSP
2145       CallOpc = ARMISD::CALL_NOLINK;
2146     else
2147       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2148   }
2149 
2150   std::vector<SDValue> Ops;
2151   Ops.push_back(Chain);
2152   Ops.push_back(Callee);
2153 
2154   // Add argument registers to the end of the list so that they are known live
2155   // into the call.
2156   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2157     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2158                                   RegsToPass[i].second.getValueType()));
2159 
2160   // Add a register mask operand representing the call-preserved registers.
2161   if (!isTailCall) {
2162     const uint32_t *Mask;
2163     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2164     if (isThisReturn) {
2165       // For 'this' returns, use the R0-preserving mask if applicable
2166       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2167       if (!Mask) {
2168         // Set isThisReturn to false if the calling convention is not one that
2169         // allows 'returned' to be modeled in this way, so LowerCallResult does
2170         // not try to pass 'this' straight through
2171         isThisReturn = false;
2172         Mask = ARI->getCallPreservedMask(MF, CallConv);
2173       }
2174     } else
2175       Mask = ARI->getCallPreservedMask(MF, CallConv);
2176 
2177     assert(Mask && "Missing call preserved mask for calling convention");
2178     Ops.push_back(DAG.getRegisterMask(Mask));
2179   }
2180 
2181   if (InFlag.getNode())
2182     Ops.push_back(InFlag);
2183 
2184   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2185   if (isTailCall) {
2186     MF.getFrameInfo().setHasTailCall();
2187     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2188   }
2189 
2190   // Returns a chain and a flag for retval copy to use.
2191   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2192   InFlag = Chain.getValue(1);
2193 
2194   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2195                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2196   if (!Ins.empty())
2197     InFlag = Chain.getValue(1);
2198 
2199   // Handle result values, copying them out of physregs into vregs that we
2200   // return.
2201   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2202                          InVals, isThisReturn,
2203                          isThisReturn ? OutVals[0] : SDValue());
2204 }
2205 
2206 /// HandleByVal - Every parameter *after* a byval parameter is passed
2207 /// on the stack.  Remember the next parameter register to allocate,
2208 /// and then confiscate the rest of the parameter registers to insure
2209 /// this.
2210 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2211                                     unsigned Align) const {
2212   // Byval (as with any stack) slots are always at least 4 byte aligned.
2213   Align = std::max(Align, 4U);
2214 
2215   unsigned Reg = State->AllocateReg(GPRArgRegs);
2216   if (!Reg)
2217     return;
2218 
2219   unsigned AlignInRegs = Align / 4;
2220   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2221   for (unsigned i = 0; i < Waste; ++i)
2222     Reg = State->AllocateReg(GPRArgRegs);
2223 
2224   if (!Reg)
2225     return;
2226 
2227   unsigned Excess = 4 * (ARM::R4 - Reg);
2228 
2229   // Special case when NSAA != SP and parameter size greater than size of
2230   // all remained GPR regs. In that case we can't split parameter, we must
2231   // send it to stack. We also must set NCRN to R4, so waste all
2232   // remained registers.
2233   const unsigned NSAAOffset = State->getNextStackOffset();
2234   if (NSAAOffset != 0 && Size > Excess) {
2235     while (State->AllocateReg(GPRArgRegs))
2236       ;
2237     return;
2238   }
2239 
2240   // First register for byval parameter is the first register that wasn't
2241   // allocated before this method call, so it would be "reg".
2242   // If parameter is small enough to be saved in range [reg, r4), then
2243   // the end (first after last) register would be reg + param-size-in-regs,
2244   // else parameter would be splitted between registers and stack,
2245   // end register would be r4 in this case.
2246   unsigned ByValRegBegin = Reg;
2247   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2248   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2249   // Note, first register is allocated in the beginning of function already,
2250   // allocate remained amount of registers we need.
2251   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2252     State->AllocateReg(GPRArgRegs);
2253   // A byval parameter that is split between registers and memory needs its
2254   // size truncated here.
2255   // In the case where the entire structure fits in registers, we set the
2256   // size in memory to zero.
2257   Size = std::max<int>(Size - Excess, 0);
2258 }
2259 
2260 /// MatchingStackOffset - Return true if the given stack call argument is
2261 /// already available in the same position (relatively) of the caller's
2262 /// incoming argument stack.
2263 static
2264 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2265                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2266                          const TargetInstrInfo *TII) {
2267   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2268   int FI = std::numeric_limits<int>::max();
2269   if (Arg.getOpcode() == ISD::CopyFromReg) {
2270     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2271     if (!TargetRegisterInfo::isVirtualRegister(VR))
2272       return false;
2273     MachineInstr *Def = MRI->getVRegDef(VR);
2274     if (!Def)
2275       return false;
2276     if (!Flags.isByVal()) {
2277       if (!TII->isLoadFromStackSlot(*Def, FI))
2278         return false;
2279     } else {
2280       return false;
2281     }
2282   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2283     if (Flags.isByVal())
2284       // ByVal argument is passed in as a pointer but it's now being
2285       // dereferenced. e.g.
2286       // define @foo(%struct.X* %A) {
2287       //   tail call @bar(%struct.X* byval %A)
2288       // }
2289       return false;
2290     SDValue Ptr = Ld->getBasePtr();
2291     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2292     if (!FINode)
2293       return false;
2294     FI = FINode->getIndex();
2295   } else
2296     return false;
2297 
2298   assert(FI != std::numeric_limits<int>::max());
2299   if (!MFI.isFixedObjectIndex(FI))
2300     return false;
2301   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2302 }
2303 
2304 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2305 /// for tail call optimization. Targets which want to do tail call
2306 /// optimization should implement this function.
2307 bool
2308 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2309                                                      CallingConv::ID CalleeCC,
2310                                                      bool isVarArg,
2311                                                      bool isCalleeStructRet,
2312                                                      bool isCallerStructRet,
2313                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2314                                     const SmallVectorImpl<SDValue> &OutVals,
2315                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2316                                                      SelectionDAG& DAG) const {
2317   MachineFunction &MF = DAG.getMachineFunction();
2318   const Function &CallerF = MF.getFunction();
2319   CallingConv::ID CallerCC = CallerF.getCallingConv();
2320 
2321   assert(Subtarget->supportsTailCall());
2322 
2323   // Tail calls to function pointers cannot be optimized for Thumb1 if the args
2324   // to the call take up r0-r3. The reason is that there are no legal registers
2325   // left to hold the pointer to the function to be called.
2326   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2327       !isa<GlobalAddressSDNode>(Callee.getNode()))
2328       return false;
2329 
2330   // Look for obvious safe cases to perform tail call optimization that do not
2331   // require ABI changes. This is what gcc calls sibcall.
2332 
2333   // Exception-handling functions need a special set of instructions to indicate
2334   // a return to the hardware. Tail-calling another function would probably
2335   // break this.
2336   if (CallerF.hasFnAttribute("interrupt"))
2337     return false;
2338 
2339   // Also avoid sibcall optimization if either caller or callee uses struct
2340   // return semantics.
2341   if (isCalleeStructRet || isCallerStructRet)
2342     return false;
2343 
2344   // Externally-defined functions with weak linkage should not be
2345   // tail-called on ARM when the OS does not support dynamic
2346   // pre-emption of symbols, as the AAELF spec requires normal calls
2347   // to undefined weak functions to be replaced with a NOP or jump to the
2348   // next instruction. The behaviour of branch instructions in this
2349   // situation (as used for tail calls) is implementation-defined, so we
2350   // cannot rely on the linker replacing the tail call with a return.
2351   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2352     const GlobalValue *GV = G->getGlobal();
2353     const Triple &TT = getTargetMachine().getTargetTriple();
2354     if (GV->hasExternalWeakLinkage() &&
2355         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2356       return false;
2357   }
2358 
2359   // Check that the call results are passed in the same way.
2360   LLVMContext &C = *DAG.getContext();
2361   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2362                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2363                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2364     return false;
2365   // The callee has to preserve all registers the caller needs to preserve.
2366   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2367   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2368   if (CalleeCC != CallerCC) {
2369     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2370     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2371       return false;
2372   }
2373 
2374   // If Caller's vararg or byval argument has been split between registers and
2375   // stack, do not perform tail call, since part of the argument is in caller's
2376   // local frame.
2377   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2378   if (AFI_Caller->getArgRegsSaveSize())
2379     return false;
2380 
2381   // If the callee takes no arguments then go on to check the results of the
2382   // call.
2383   if (!Outs.empty()) {
2384     // Check if stack adjustment is needed. For now, do not do this if any
2385     // argument is passed on the stack.
2386     SmallVector<CCValAssign, 16> ArgLocs;
2387     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2388     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2389     if (CCInfo.getNextStackOffset()) {
2390       // Check if the arguments are already laid out in the right way as
2391       // the caller's fixed stack objects.
2392       MachineFrameInfo &MFI = MF.getFrameInfo();
2393       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2394       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2395       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2396            i != e;
2397            ++i, ++realArgIdx) {
2398         CCValAssign &VA = ArgLocs[i];
2399         EVT RegVT = VA.getLocVT();
2400         SDValue Arg = OutVals[realArgIdx];
2401         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2402         if (VA.getLocInfo() == CCValAssign::Indirect)
2403           return false;
2404         if (VA.needsCustom()) {
2405           // f64 and vector types are split into multiple registers or
2406           // register/stack-slot combinations.  The types will not match
2407           // the registers; give up on memory f64 refs until we figure
2408           // out what to do about this.
2409           if (!VA.isRegLoc())
2410             return false;
2411           if (!ArgLocs[++i].isRegLoc())
2412             return false;
2413           if (RegVT == MVT::v2f64) {
2414             if (!ArgLocs[++i].isRegLoc())
2415               return false;
2416             if (!ArgLocs[++i].isRegLoc())
2417               return false;
2418           }
2419         } else if (!VA.isRegLoc()) {
2420           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2421                                    MFI, MRI, TII))
2422             return false;
2423         }
2424       }
2425     }
2426 
2427     const MachineRegisterInfo &MRI = MF.getRegInfo();
2428     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2429       return false;
2430   }
2431 
2432   return true;
2433 }
2434 
2435 bool
2436 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2437                                   MachineFunction &MF, bool isVarArg,
2438                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2439                                   LLVMContext &Context) const {
2440   SmallVector<CCValAssign, 16> RVLocs;
2441   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2442   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2443 }
2444 
2445 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2446                                     const SDLoc &DL, SelectionDAG &DAG) {
2447   const MachineFunction &MF = DAG.getMachineFunction();
2448   const Function &F = MF.getFunction();
2449 
2450   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2451 
2452   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2453   // version of the "preferred return address". These offsets affect the return
2454   // instruction if this is a return from PL1 without hypervisor extensions.
2455   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2456   //    SWI:     0      "subs pc, lr, #0"
2457   //    ABORT:   +4     "subs pc, lr, #4"
2458   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2459   // UNDEF varies depending on where the exception came from ARM or Thumb
2460   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2461 
2462   int64_t LROffset;
2463   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2464       IntKind == "ABORT")
2465     LROffset = 4;
2466   else if (IntKind == "SWI" || IntKind == "UNDEF")
2467     LROffset = 0;
2468   else
2469     report_fatal_error("Unsupported interrupt attribute. If present, value "
2470                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2471 
2472   RetOps.insert(RetOps.begin() + 1,
2473                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2474 
2475   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2476 }
2477 
2478 SDValue
2479 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2480                                bool isVarArg,
2481                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2482                                const SmallVectorImpl<SDValue> &OutVals,
2483                                const SDLoc &dl, SelectionDAG &DAG) const {
2484   // CCValAssign - represent the assignment of the return value to a location.
2485   SmallVector<CCValAssign, 16> RVLocs;
2486 
2487   // CCState - Info about the registers and stack slots.
2488   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2489                  *DAG.getContext());
2490 
2491   // Analyze outgoing return values.
2492   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2493 
2494   SDValue Flag;
2495   SmallVector<SDValue, 4> RetOps;
2496   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2497   bool isLittleEndian = Subtarget->isLittle();
2498 
2499   MachineFunction &MF = DAG.getMachineFunction();
2500   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2501   AFI->setReturnRegsCount(RVLocs.size());
2502 
2503   // Copy the result values into the output registers.
2504   for (unsigned i = 0, realRVLocIdx = 0;
2505        i != RVLocs.size();
2506        ++i, ++realRVLocIdx) {
2507     CCValAssign &VA = RVLocs[i];
2508     assert(VA.isRegLoc() && "Can only return in registers!");
2509 
2510     SDValue Arg = OutVals[realRVLocIdx];
2511     bool ReturnF16 = false;
2512 
2513     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2514       // Half-precision return values can be returned like this:
2515       //
2516       // t11 f16 = fadd ...
2517       // t12: i16 = bitcast t11
2518       //   t13: i32 = zero_extend t12
2519       // t14: f32 = bitcast t13  <~~~~~~~ Arg
2520       //
2521       // to avoid code generation for bitcasts, we simply set Arg to the node
2522       // that produces the f16 value, t11 in this case.
2523       //
2524       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2525         SDValue ZE = Arg.getOperand(0);
2526         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2527           SDValue BC = ZE.getOperand(0);
2528           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2529             Arg = BC.getOperand(0);
2530             ReturnF16 = true;
2531           }
2532         }
2533       }
2534     }
2535 
2536     switch (VA.getLocInfo()) {
2537     default: llvm_unreachable("Unknown loc info!");
2538     case CCValAssign::Full: break;
2539     case CCValAssign::BCvt:
2540       if (!ReturnF16)
2541         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2542       break;
2543     }
2544 
2545     if (VA.needsCustom()) {
2546       if (VA.getLocVT() == MVT::v2f64) {
2547         // Extract the first half and return it in two registers.
2548         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2549                                    DAG.getConstant(0, dl, MVT::i32));
2550         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2551                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2552 
2553         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2554                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2555                                  Flag);
2556         Flag = Chain.getValue(1);
2557         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2558         VA = RVLocs[++i]; // skip ahead to next loc
2559         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2560                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2561                                  Flag);
2562         Flag = Chain.getValue(1);
2563         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2564         VA = RVLocs[++i]; // skip ahead to next loc
2565 
2566         // Extract the 2nd half and fall through to handle it as an f64 value.
2567         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2568                           DAG.getConstant(1, dl, MVT::i32));
2569       }
2570       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2571       // available.
2572       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2573                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2574       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2575                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2576                                Flag);
2577       Flag = Chain.getValue(1);
2578       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2579       VA = RVLocs[++i]; // skip ahead to next loc
2580       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2581                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2582                                Flag);
2583     } else
2584       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2585 
2586     // Guarantee that all emitted copies are
2587     // stuck together, avoiding something bad.
2588     Flag = Chain.getValue(1);
2589     RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2590                                      ReturnF16 ? MVT::f16 : VA.getLocVT()));
2591   }
2592   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2593   const MCPhysReg *I =
2594       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2595   if (I) {
2596     for (; *I; ++I) {
2597       if (ARM::GPRRegClass.contains(*I))
2598         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2599       else if (ARM::DPRRegClass.contains(*I))
2600         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2601       else
2602         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2603     }
2604   }
2605 
2606   // Update chain and glue.
2607   RetOps[0] = Chain;
2608   if (Flag.getNode())
2609     RetOps.push_back(Flag);
2610 
2611   // CPUs which aren't M-class use a special sequence to return from
2612   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2613   // though we use "subs pc, lr, #N").
2614   //
2615   // M-class CPUs actually use a normal return sequence with a special
2616   // (hardware-provided) value in LR, so the normal code path works.
2617   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2618       !Subtarget->isMClass()) {
2619     if (Subtarget->isThumb1Only())
2620       report_fatal_error("interrupt attribute is not supported in Thumb1");
2621     return LowerInterruptReturn(RetOps, dl, DAG);
2622   }
2623 
2624   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2625 }
2626 
2627 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2628   if (N->getNumValues() != 1)
2629     return false;
2630   if (!N->hasNUsesOfValue(1, 0))
2631     return false;
2632 
2633   SDValue TCChain = Chain;
2634   SDNode *Copy = *N->use_begin();
2635   if (Copy->getOpcode() == ISD::CopyToReg) {
2636     // If the copy has a glue operand, we conservatively assume it isn't safe to
2637     // perform a tail call.
2638     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2639       return false;
2640     TCChain = Copy->getOperand(0);
2641   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2642     SDNode *VMov = Copy;
2643     // f64 returned in a pair of GPRs.
2644     SmallPtrSet<SDNode*, 2> Copies;
2645     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2646          UI != UE; ++UI) {
2647       if (UI->getOpcode() != ISD::CopyToReg)
2648         return false;
2649       Copies.insert(*UI);
2650     }
2651     if (Copies.size() > 2)
2652       return false;
2653 
2654     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2655          UI != UE; ++UI) {
2656       SDValue UseChain = UI->getOperand(0);
2657       if (Copies.count(UseChain.getNode()))
2658         // Second CopyToReg
2659         Copy = *UI;
2660       else {
2661         // We are at the top of this chain.
2662         // If the copy has a glue operand, we conservatively assume it
2663         // isn't safe to perform a tail call.
2664         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2665           return false;
2666         // First CopyToReg
2667         TCChain = UseChain;
2668       }
2669     }
2670   } else if (Copy->getOpcode() == ISD::BITCAST) {
2671     // f32 returned in a single GPR.
2672     if (!Copy->hasOneUse())
2673       return false;
2674     Copy = *Copy->use_begin();
2675     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2676       return false;
2677     // If the copy has a glue operand, we conservatively assume it isn't safe to
2678     // perform a tail call.
2679     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2680       return false;
2681     TCChain = Copy->getOperand(0);
2682   } else {
2683     return false;
2684   }
2685 
2686   bool HasRet = false;
2687   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2688        UI != UE; ++UI) {
2689     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2690         UI->getOpcode() != ARMISD::INTRET_FLAG)
2691       return false;
2692     HasRet = true;
2693   }
2694 
2695   if (!HasRet)
2696     return false;
2697 
2698   Chain = TCChain;
2699   return true;
2700 }
2701 
2702 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2703   if (!Subtarget->supportsTailCall())
2704     return false;
2705 
2706   auto Attr =
2707       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2708   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2709     return false;
2710 
2711   return true;
2712 }
2713 
2714 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2715 // and pass the lower and high parts through.
2716 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2717   SDLoc DL(Op);
2718   SDValue WriteValue = Op->getOperand(2);
2719 
2720   // This function is only supposed to be called for i64 type argument.
2721   assert(WriteValue.getValueType() == MVT::i64
2722           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2723 
2724   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2725                            DAG.getConstant(0, DL, MVT::i32));
2726   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2727                            DAG.getConstant(1, DL, MVT::i32));
2728   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2729   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2730 }
2731 
2732 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2733 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2734 // one of the above mentioned nodes. It has to be wrapped because otherwise
2735 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2736 // be used to form addressing mode. These wrapped nodes will be selected
2737 // into MOVi.
2738 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2739                                              SelectionDAG &DAG) const {
2740   EVT PtrVT = Op.getValueType();
2741   // FIXME there is no actual debug info here
2742   SDLoc dl(Op);
2743   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2744   SDValue Res;
2745 
2746   // When generating execute-only code Constant Pools must be promoted to the
2747   // global data section. It's a bit ugly that we can't share them across basic
2748   // blocks, but this way we guarantee that execute-only behaves correct with
2749   // position-independent addressing modes.
2750   if (Subtarget->genExecuteOnly()) {
2751     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2752     auto T = const_cast<Type*>(CP->getType());
2753     auto C = const_cast<Constant*>(CP->getConstVal());
2754     auto M = const_cast<Module*>(DAG.getMachineFunction().
2755                                  getFunction().getParent());
2756     auto GV = new GlobalVariable(
2757                     *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2758                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2759                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2760                     Twine(AFI->createPICLabelUId())
2761                   );
2762     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2763                                             dl, PtrVT);
2764     return LowerGlobalAddress(GA, DAG);
2765   }
2766 
2767   if (CP->isMachineConstantPoolEntry())
2768     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2769                                     CP->getAlignment());
2770   else
2771     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2772                                     CP->getAlignment());
2773   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2774 }
2775 
2776 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2777   return MachineJumpTableInfo::EK_Inline;
2778 }
2779 
2780 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2781                                              SelectionDAG &DAG) const {
2782   MachineFunction &MF = DAG.getMachineFunction();
2783   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2784   unsigned ARMPCLabelIndex = 0;
2785   SDLoc DL(Op);
2786   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2787   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2788   SDValue CPAddr;
2789   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2790   if (!IsPositionIndependent) {
2791     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2792   } else {
2793     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2794     ARMPCLabelIndex = AFI->createPICLabelUId();
2795     ARMConstantPoolValue *CPV =
2796       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2797                                       ARMCP::CPBlockAddress, PCAdj);
2798     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2799   }
2800   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2801   SDValue Result = DAG.getLoad(
2802       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2803       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2804   if (!IsPositionIndependent)
2805     return Result;
2806   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2807   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2808 }
2809 
2810 /// Convert a TLS address reference into the correct sequence of loads
2811 /// and calls to compute the variable's address for Darwin, and return an
2812 /// SDValue containing the final node.
2813 
2814 /// Darwin only has one TLS scheme which must be capable of dealing with the
2815 /// fully general situation, in the worst case. This means:
2816 ///     + "extern __thread" declaration.
2817 ///     + Defined in a possibly unknown dynamic library.
2818 ///
2819 /// The general system is that each __thread variable has a [3 x i32] descriptor
2820 /// which contains information used by the runtime to calculate the address. The
2821 /// only part of this the compiler needs to know about is the first word, which
2822 /// contains a function pointer that must be called with the address of the
2823 /// entire descriptor in "r0".
2824 ///
2825 /// Since this descriptor may be in a different unit, in general access must
2826 /// proceed along the usual ARM rules. A common sequence to produce is:
2827 ///
2828 ///     movw rT1, :lower16:_var$non_lazy_ptr
2829 ///     movt rT1, :upper16:_var$non_lazy_ptr
2830 ///     ldr r0, [rT1]
2831 ///     ldr rT2, [r0]
2832 ///     blx rT2
2833 ///     [...address now in r0...]
2834 SDValue
2835 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2836                                                SelectionDAG &DAG) const {
2837   assert(Subtarget->isTargetDarwin() &&
2838          "This function expects a Darwin target");
2839   SDLoc DL(Op);
2840 
2841   // First step is to get the address of the actua global symbol. This is where
2842   // the TLS descriptor lives.
2843   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2844 
2845   // The first entry in the descriptor is a function pointer that we must call
2846   // to obtain the address of the variable.
2847   SDValue Chain = DAG.getEntryNode();
2848   SDValue FuncTLVGet = DAG.getLoad(
2849       MVT::i32, DL, Chain, DescAddr,
2850       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2851       /* Alignment = */ 4,
2852       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2853           MachineMemOperand::MOInvariant);
2854   Chain = FuncTLVGet.getValue(1);
2855 
2856   MachineFunction &F = DAG.getMachineFunction();
2857   MachineFrameInfo &MFI = F.getFrameInfo();
2858   MFI.setAdjustsStack(true);
2859 
2860   // TLS calls preserve all registers except those that absolutely must be
2861   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2862   // silly).
2863   auto TRI =
2864       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
2865   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2866   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2867 
2868   // Finally, we can make the call. This is just a degenerate version of a
2869   // normal AArch64 call node: r0 takes the address of the descriptor, and
2870   // returns the address of the variable in this thread.
2871   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2872   Chain =
2873       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2874                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2875                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2876   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2877 }
2878 
2879 SDValue
2880 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2881                                                 SelectionDAG &DAG) const {
2882   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2883 
2884   SDValue Chain = DAG.getEntryNode();
2885   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2886   SDLoc DL(Op);
2887 
2888   // Load the current TEB (thread environment block)
2889   SDValue Ops[] = {Chain,
2890                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2891                    DAG.getConstant(15, DL, MVT::i32),
2892                    DAG.getConstant(0, DL, MVT::i32),
2893                    DAG.getConstant(13, DL, MVT::i32),
2894                    DAG.getConstant(0, DL, MVT::i32),
2895                    DAG.getConstant(2, DL, MVT::i32)};
2896   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2897                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2898 
2899   SDValue TEB = CurrentTEB.getValue(0);
2900   Chain = CurrentTEB.getValue(1);
2901 
2902   // Load the ThreadLocalStoragePointer from the TEB
2903   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2904   SDValue TLSArray =
2905       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2906   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2907 
2908   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2909   // offset into the TLSArray.
2910 
2911   // Load the TLS index from the C runtime
2912   SDValue TLSIndex =
2913       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2914   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2915   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2916 
2917   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2918                               DAG.getConstant(2, DL, MVT::i32));
2919   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2920                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2921                             MachinePointerInfo());
2922 
2923   // Get the offset of the start of the .tls section (section base)
2924   const auto *GA = cast<GlobalAddressSDNode>(Op);
2925   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2926   SDValue Offset = DAG.getLoad(
2927       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2928                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2929       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2930 
2931   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2932 }
2933 
2934 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2935 SDValue
2936 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2937                                                  SelectionDAG &DAG) const {
2938   SDLoc dl(GA);
2939   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2940   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2941   MachineFunction &MF = DAG.getMachineFunction();
2942   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2943   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2944   ARMConstantPoolValue *CPV =
2945     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2946                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2947   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2948   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2949   Argument = DAG.getLoad(
2950       PtrVT, dl, DAG.getEntryNode(), Argument,
2951       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2952   SDValue Chain = Argument.getValue(1);
2953 
2954   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2955   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2956 
2957   // call __tls_get_addr.
2958   ArgListTy Args;
2959   ArgListEntry Entry;
2960   Entry.Node = Argument;
2961   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2962   Args.push_back(Entry);
2963 
2964   // FIXME: is there useful debug info available here?
2965   TargetLowering::CallLoweringInfo CLI(DAG);
2966   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2967       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2968       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2969 
2970   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2971   return CallResult.first;
2972 }
2973 
2974 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2975 // "local exec" model.
2976 SDValue
2977 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2978                                         SelectionDAG &DAG,
2979                                         TLSModel::Model model) const {
2980   const GlobalValue *GV = GA->getGlobal();
2981   SDLoc dl(GA);
2982   SDValue Offset;
2983   SDValue Chain = DAG.getEntryNode();
2984   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2985   // Get the Thread Pointer
2986   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2987 
2988   if (model == TLSModel::InitialExec) {
2989     MachineFunction &MF = DAG.getMachineFunction();
2990     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2991     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2992     // Initial exec model.
2993     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2994     ARMConstantPoolValue *CPV =
2995       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2996                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2997                                       true);
2998     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2999     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3000     Offset = DAG.getLoad(
3001         PtrVT, dl, Chain, Offset,
3002         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3003     Chain = Offset.getValue(1);
3004 
3005     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3006     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3007 
3008     Offset = DAG.getLoad(
3009         PtrVT, dl, Chain, Offset,
3010         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3011   } else {
3012     // local exec model
3013     assert(model == TLSModel::LocalExec);
3014     ARMConstantPoolValue *CPV =
3015       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3016     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3017     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3018     Offset = DAG.getLoad(
3019         PtrVT, dl, Chain, Offset,
3020         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3021   }
3022 
3023   // The address of the thread local variable is the add of the thread
3024   // pointer with the offset of the variable.
3025   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3026 }
3027 
3028 SDValue
3029 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3030   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3031   if (DAG.getTarget().useEmulatedTLS())
3032     return LowerToTLSEmulatedModel(GA, DAG);
3033 
3034   if (Subtarget->isTargetDarwin())
3035     return LowerGlobalTLSAddressDarwin(Op, DAG);
3036 
3037   if (Subtarget->isTargetWindows())
3038     return LowerGlobalTLSAddressWindows(Op, DAG);
3039 
3040   // TODO: implement the "local dynamic" model
3041   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3042   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3043 
3044   switch (model) {
3045     case TLSModel::GeneralDynamic:
3046     case TLSModel::LocalDynamic:
3047       return LowerToTLSGeneralDynamicModel(GA, DAG);
3048     case TLSModel::InitialExec:
3049     case TLSModel::LocalExec:
3050       return LowerToTLSExecModels(GA, DAG, model);
3051   }
3052   llvm_unreachable("bogus TLS model");
3053 }
3054 
3055 /// Return true if all users of V are within function F, looking through
3056 /// ConstantExprs.
3057 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3058   SmallVector<const User*,4> Worklist;
3059   for (auto *U : V->users())
3060     Worklist.push_back(U);
3061   while (!Worklist.empty()) {
3062     auto *U = Worklist.pop_back_val();
3063     if (isa<ConstantExpr>(U)) {
3064       for (auto *UU : U->users())
3065         Worklist.push_back(UU);
3066       continue;
3067     }
3068 
3069     auto *I = dyn_cast<Instruction>(U);
3070     if (!I || I->getParent()->getParent() != F)
3071       return false;
3072   }
3073   return true;
3074 }
3075 
3076 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3077                                      const GlobalValue *GV, SelectionDAG &DAG,
3078                                      EVT PtrVT, const SDLoc &dl) {
3079   // If we're creating a pool entry for a constant global with unnamed address,
3080   // and the global is small enough, we can emit it inline into the constant pool
3081   // to save ourselves an indirection.
3082   //
3083   // This is a win if the constant is only used in one function (so it doesn't
3084   // need to be duplicated) or duplicating the constant wouldn't increase code
3085   // size (implying the constant is no larger than 4 bytes).
3086   const Function &F = DAG.getMachineFunction().getFunction();
3087 
3088   // We rely on this decision to inline being idemopotent and unrelated to the
3089   // use-site. We know that if we inline a variable at one use site, we'll
3090   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3091   // doesn't know about this optimization, so bail out if it's enabled else
3092   // we could decide to inline here (and thus never emit the GV) but require
3093   // the GV from fast-isel generated code.
3094   if (!EnableConstpoolPromotion ||
3095       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3096       return SDValue();
3097 
3098   auto *GVar = dyn_cast<GlobalVariable>(GV);
3099   if (!GVar || !GVar->hasInitializer() ||
3100       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3101       !GVar->hasLocalLinkage())
3102     return SDValue();
3103 
3104   // If we inline a value that contains relocations, we move the relocations
3105   // from .data to .text. This is not allowed in position-independent code.
3106   auto *Init = GVar->getInitializer();
3107   if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3108       Init->needsRelocation())
3109     return SDValue();
3110 
3111   // The constant islands pass can only really deal with alignment requests
3112   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3113   // any type wanting greater alignment requirements than 4 bytes. We also
3114   // can only promote constants that are multiples of 4 bytes in size or
3115   // are paddable to a multiple of 4. Currently we only try and pad constants
3116   // that are strings for simplicity.
3117   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3118   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3119   unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3120   unsigned RequiredPadding = 4 - (Size % 4);
3121   bool PaddingPossible =
3122     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3123   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3124       Size == 0)
3125     return SDValue();
3126 
3127   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3128   MachineFunction &MF = DAG.getMachineFunction();
3129   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3130 
3131   // We can't bloat the constant pool too much, else the ConstantIslands pass
3132   // may fail to converge. If we haven't promoted this global yet (it may have
3133   // multiple uses), and promoting it would increase the constant pool size (Sz
3134   // > 4), ensure we have space to do so up to MaxTotal.
3135   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3136     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3137         ConstpoolPromotionMaxTotal)
3138       return SDValue();
3139 
3140   // This is only valid if all users are in a single function; we can't clone
3141   // the constant in general. The LLVM IR unnamed_addr allows merging
3142   // constants, but not cloning them.
3143   //
3144   // We could potentially allow cloning if we could prove all uses of the
3145   // constant in the current function don't care about the address, like
3146   // printf format strings. But that isn't implemented for now.
3147   if (!allUsersAreInFunction(GVar, &F))
3148     return SDValue();
3149 
3150   // We're going to inline this global. Pad it out if needed.
3151   if (RequiredPadding != 4) {
3152     StringRef S = CDAInit->getAsString();
3153 
3154     SmallVector<uint8_t,16> V(S.size());
3155     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3156     while (RequiredPadding--)
3157       V.push_back(0);
3158     Init = ConstantDataArray::get(*DAG.getContext(), V);
3159   }
3160 
3161   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3162   SDValue CPAddr =
3163     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3164   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3165     AFI->markGlobalAsPromotedToConstantPool(GVar);
3166     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3167                                       PaddedSize - 4);
3168   }
3169   ++NumConstpoolPromoted;
3170   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3171 }
3172 
3173 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3174   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3175     if (!(GV = GA->getBaseObject()))
3176       return false;
3177   if (const auto *V = dyn_cast<GlobalVariable>(GV))
3178     return V->isConstant();
3179   return isa<Function>(GV);
3180 }
3181 
3182 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3183                                               SelectionDAG &DAG) const {
3184   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3185   default: llvm_unreachable("unknown object format");
3186   case Triple::COFF:
3187     return LowerGlobalAddressWindows(Op, DAG);
3188   case Triple::ELF:
3189     return LowerGlobalAddressELF(Op, DAG);
3190   case Triple::MachO:
3191     return LowerGlobalAddressDarwin(Op, DAG);
3192   }
3193 }
3194 
3195 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3196                                                  SelectionDAG &DAG) const {
3197   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3198   SDLoc dl(Op);
3199   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3200   const TargetMachine &TM = getTargetMachine();
3201   bool IsRO = isReadOnly(GV);
3202 
3203   // promoteToConstantPool only if not generating XO text section
3204   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3205     if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3206       return V;
3207 
3208   if (isPositionIndependent()) {
3209     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3210     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3211                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3212     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3213     if (UseGOT_PREL)
3214       Result =
3215           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3216                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3217     return Result;
3218   } else if (Subtarget->isROPI() && IsRO) {
3219     // PC-relative.
3220     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3221     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3222     return Result;
3223   } else if (Subtarget->isRWPI() && !IsRO) {
3224     // SB-relative.
3225     SDValue RelAddr;
3226     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3227       ++NumMovwMovt;
3228       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3229       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3230     } else { // use literal pool for address constant
3231       ARMConstantPoolValue *CPV =
3232         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3233       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3234       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3235       RelAddr = DAG.getLoad(
3236           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3237           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3238     }
3239     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3240     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3241     return Result;
3242   }
3243 
3244   // If we have T2 ops, we can materialize the address directly via movt/movw
3245   // pair. This is always cheaper.
3246   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3247     ++NumMovwMovt;
3248     // FIXME: Once remat is capable of dealing with instructions with register
3249     // operands, expand this into two nodes.
3250     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3251                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3252   } else {
3253     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3254     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3255     return DAG.getLoad(
3256         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3257         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3258   }
3259 }
3260 
3261 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3262                                                     SelectionDAG &DAG) const {
3263   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3264          "ROPI/RWPI not currently supported for Darwin");
3265   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3266   SDLoc dl(Op);
3267   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3268 
3269   if (Subtarget->useMovt(DAG.getMachineFunction()))
3270     ++NumMovwMovt;
3271 
3272   // FIXME: Once remat is capable of dealing with instructions with register
3273   // operands, expand this into multiple nodes
3274   unsigned Wrapper =
3275       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3276 
3277   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3278   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3279 
3280   if (Subtarget->isGVIndirectSymbol(GV))
3281     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3282                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3283   return Result;
3284 }
3285 
3286 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3287                                                      SelectionDAG &DAG) const {
3288   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3289   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3290          "Windows on ARM expects to use movw/movt");
3291   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3292          "ROPI/RWPI not currently supported for Windows");
3293 
3294   const TargetMachine &TM = getTargetMachine();
3295   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3296   ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3297   if (GV->hasDLLImportStorageClass())
3298     TargetFlags = ARMII::MO_DLLIMPORT;
3299   else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3300     TargetFlags = ARMII::MO_COFFSTUB;
3301   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3302   SDValue Result;
3303   SDLoc DL(Op);
3304 
3305   ++NumMovwMovt;
3306 
3307   // FIXME: Once remat is capable of dealing with instructions with register
3308   // operands, expand this into two nodes.
3309   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3310                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3311                                                   TargetFlags));
3312   if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3313     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3314                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3315   return Result;
3316 }
3317 
3318 SDValue
3319 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3320   SDLoc dl(Op);
3321   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3322   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3323                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3324                      Op.getOperand(1), Val);
3325 }
3326 
3327 SDValue
3328 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3329   SDLoc dl(Op);
3330   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3331                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3332 }
3333 
3334 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3335                                                       SelectionDAG &DAG) const {
3336   SDLoc dl(Op);
3337   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3338                      Op.getOperand(0));
3339 }
3340 
3341 SDValue
3342 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3343                                           const ARMSubtarget *Subtarget) const {
3344   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3345   SDLoc dl(Op);
3346   switch (IntNo) {
3347   default: return SDValue();    // Don't custom lower most intrinsics.
3348   case Intrinsic::thread_pointer: {
3349     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3350     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3351   }
3352   case Intrinsic::eh_sjlj_lsda: {
3353     MachineFunction &MF = DAG.getMachineFunction();
3354     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3355     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3356     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3357     SDValue CPAddr;
3358     bool IsPositionIndependent = isPositionIndependent();
3359     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3360     ARMConstantPoolValue *CPV =
3361       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3362                                       ARMCP::CPLSDA, PCAdj);
3363     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3364     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3365     SDValue Result = DAG.getLoad(
3366         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3367         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3368 
3369     if (IsPositionIndependent) {
3370       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3371       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3372     }
3373     return Result;
3374   }
3375   case Intrinsic::arm_neon_vabs:
3376     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3377                         Op.getOperand(1));
3378   case Intrinsic::arm_neon_vmulls:
3379   case Intrinsic::arm_neon_vmullu: {
3380     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3381       ? ARMISD::VMULLs : ARMISD::VMULLu;
3382     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3383                        Op.getOperand(1), Op.getOperand(2));
3384   }
3385   case Intrinsic::arm_neon_vminnm:
3386   case Intrinsic::arm_neon_vmaxnm: {
3387     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3388       ? ISD::FMINNUM : ISD::FMAXNUM;
3389     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3390                        Op.getOperand(1), Op.getOperand(2));
3391   }
3392   case Intrinsic::arm_neon_vminu:
3393   case Intrinsic::arm_neon_vmaxu: {
3394     if (Op.getValueType().isFloatingPoint())
3395       return SDValue();
3396     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3397       ? ISD::UMIN : ISD::UMAX;
3398     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3399                          Op.getOperand(1), Op.getOperand(2));
3400   }
3401   case Intrinsic::arm_neon_vmins:
3402   case Intrinsic::arm_neon_vmaxs: {
3403     // v{min,max}s is overloaded between signed integers and floats.
3404     if (!Op.getValueType().isFloatingPoint()) {
3405       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3406         ? ISD::SMIN : ISD::SMAX;
3407       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3408                          Op.getOperand(1), Op.getOperand(2));
3409     }
3410     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3411       ? ISD::FMINIMUM : ISD::FMAXIMUM;
3412     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3413                        Op.getOperand(1), Op.getOperand(2));
3414   }
3415   case Intrinsic::arm_neon_vtbl1:
3416     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3417                        Op.getOperand(1), Op.getOperand(2));
3418   case Intrinsic::arm_neon_vtbl2:
3419     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3420                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3421   }
3422 }
3423 
3424 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3425                                  const ARMSubtarget *Subtarget) {
3426   SDLoc dl(Op);
3427   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3428   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3429   if (SSID == SyncScope::SingleThread)
3430     return Op;
3431 
3432   if (!Subtarget->hasDataBarrier()) {
3433     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3434     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3435     // here.
3436     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3437            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3438     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3439                        DAG.getConstant(0, dl, MVT::i32));
3440   }
3441 
3442   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3443   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3444   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3445   if (Subtarget->isMClass()) {
3446     // Only a full system barrier exists in the M-class architectures.
3447     Domain = ARM_MB::SY;
3448   } else if (Subtarget->preferISHSTBarriers() &&
3449              Ord == AtomicOrdering::Release) {
3450     // Swift happens to implement ISHST barriers in a way that's compatible with
3451     // Release semantics but weaker than ISH so we'd be fools not to use
3452     // it. Beware: other processors probably don't!
3453     Domain = ARM_MB::ISHST;
3454   }
3455 
3456   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3457                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3458                      DAG.getConstant(Domain, dl, MVT::i32));
3459 }
3460 
3461 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3462                              const ARMSubtarget *Subtarget) {
3463   // ARM pre v5TE and Thumb1 does not have preload instructions.
3464   if (!(Subtarget->isThumb2() ||
3465         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3466     // Just preserve the chain.
3467     return Op.getOperand(0);
3468 
3469   SDLoc dl(Op);
3470   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3471   if (!isRead &&
3472       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3473     // ARMv7 with MP extension has PLDW.
3474     return Op.getOperand(0);
3475 
3476   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3477   if (Subtarget->isThumb()) {
3478     // Invert the bits.
3479     isRead = ~isRead & 1;
3480     isData = ~isData & 1;
3481   }
3482 
3483   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3484                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3485                      DAG.getConstant(isData, dl, MVT::i32));
3486 }
3487 
3488 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3489   MachineFunction &MF = DAG.getMachineFunction();
3490   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3491 
3492   // vastart just stores the address of the VarArgsFrameIndex slot into the
3493   // memory location argument.
3494   SDLoc dl(Op);
3495   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3496   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3497   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3498   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3499                       MachinePointerInfo(SV));
3500 }
3501 
3502 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3503                                                 CCValAssign &NextVA,
3504                                                 SDValue &Root,
3505                                                 SelectionDAG &DAG,
3506                                                 const SDLoc &dl) const {
3507   MachineFunction &MF = DAG.getMachineFunction();
3508   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3509 
3510   const TargetRegisterClass *RC;
3511   if (AFI->isThumb1OnlyFunction())
3512     RC = &ARM::tGPRRegClass;
3513   else
3514     RC = &ARM::GPRRegClass;
3515 
3516   // Transform the arguments stored in physical registers into virtual ones.
3517   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3518   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3519 
3520   SDValue ArgValue2;
3521   if (NextVA.isMemLoc()) {
3522     MachineFrameInfo &MFI = MF.getFrameInfo();
3523     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3524 
3525     // Create load node to retrieve arguments from the stack.
3526     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3527     ArgValue2 = DAG.getLoad(
3528         MVT::i32, dl, Root, FIN,
3529         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3530   } else {
3531     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3532     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3533   }
3534   if (!Subtarget->isLittle())
3535     std::swap (ArgValue, ArgValue2);
3536   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3537 }
3538 
3539 // The remaining GPRs hold either the beginning of variable-argument
3540 // data, or the beginning of an aggregate passed by value (usually
3541 // byval).  Either way, we allocate stack slots adjacent to the data
3542 // provided by our caller, and store the unallocated registers there.
3543 // If this is a variadic function, the va_list pointer will begin with
3544 // these values; otherwise, this reassembles a (byval) structure that
3545 // was split between registers and memory.
3546 // Return: The frame index registers were stored into.
3547 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3548                                       const SDLoc &dl, SDValue &Chain,
3549                                       const Value *OrigArg,
3550                                       unsigned InRegsParamRecordIdx,
3551                                       int ArgOffset, unsigned ArgSize) const {
3552   // Currently, two use-cases possible:
3553   // Case #1. Non-var-args function, and we meet first byval parameter.
3554   //          Setup first unallocated register as first byval register;
3555   //          eat all remained registers
3556   //          (these two actions are performed by HandleByVal method).
3557   //          Then, here, we initialize stack frame with
3558   //          "store-reg" instructions.
3559   // Case #2. Var-args function, that doesn't contain byval parameters.
3560   //          The same: eat all remained unallocated registers,
3561   //          initialize stack frame.
3562 
3563   MachineFunction &MF = DAG.getMachineFunction();
3564   MachineFrameInfo &MFI = MF.getFrameInfo();
3565   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3566   unsigned RBegin, REnd;
3567   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3568     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3569   } else {
3570     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3571     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3572     REnd = ARM::R4;
3573   }
3574 
3575   if (REnd != RBegin)
3576     ArgOffset = -4 * (ARM::R4 - RBegin);
3577 
3578   auto PtrVT = getPointerTy(DAG.getDataLayout());
3579   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3580   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3581 
3582   SmallVector<SDValue, 4> MemOps;
3583   const TargetRegisterClass *RC =
3584       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3585 
3586   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3587     unsigned VReg = MF.addLiveIn(Reg, RC);
3588     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3589     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3590                                  MachinePointerInfo(OrigArg, 4 * i));
3591     MemOps.push_back(Store);
3592     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3593   }
3594 
3595   if (!MemOps.empty())
3596     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3597   return FrameIndex;
3598 }
3599 
3600 // Setup stack frame, the va_list pointer will start from.
3601 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3602                                              const SDLoc &dl, SDValue &Chain,
3603                                              unsigned ArgOffset,
3604                                              unsigned TotalArgRegsSaveSize,
3605                                              bool ForceMutable) const {
3606   MachineFunction &MF = DAG.getMachineFunction();
3607   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3608 
3609   // Try to store any remaining integer argument regs
3610   // to their spots on the stack so that they may be loaded by dereferencing
3611   // the result of va_next.
3612   // If there is no regs to be stored, just point address after last
3613   // argument passed via stack.
3614   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3615                                   CCInfo.getInRegsParamsCount(),
3616                                   CCInfo.getNextStackOffset(), 4);
3617   AFI->setVarArgsFrameIndex(FrameIndex);
3618 }
3619 
3620 SDValue ARMTargetLowering::LowerFormalArguments(
3621     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3622     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3623     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3624   MachineFunction &MF = DAG.getMachineFunction();
3625   MachineFrameInfo &MFI = MF.getFrameInfo();
3626 
3627   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3628 
3629   // Assign locations to all of the incoming arguments.
3630   SmallVector<CCValAssign, 16> ArgLocs;
3631   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3632                  *DAG.getContext());
3633   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3634 
3635   SmallVector<SDValue, 16> ArgValues;
3636   SDValue ArgValue;
3637   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3638   unsigned CurArgIdx = 0;
3639 
3640   // Initially ArgRegsSaveSize is zero.
3641   // Then we increase this value each time we meet byval parameter.
3642   // We also increase this value in case of varargs function.
3643   AFI->setArgRegsSaveSize(0);
3644 
3645   // Calculate the amount of stack space that we need to allocate to store
3646   // byval and variadic arguments that are passed in registers.
3647   // We need to know this before we allocate the first byval or variadic
3648   // argument, as they will be allocated a stack slot below the CFA (Canonical
3649   // Frame Address, the stack pointer at entry to the function).
3650   unsigned ArgRegBegin = ARM::R4;
3651   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3652     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3653       break;
3654 
3655     CCValAssign &VA = ArgLocs[i];
3656     unsigned Index = VA.getValNo();
3657     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3658     if (!Flags.isByVal())
3659       continue;
3660 
3661     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3662     unsigned RBegin, REnd;
3663     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3664     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3665 
3666     CCInfo.nextInRegsParam();
3667   }
3668   CCInfo.rewindByValRegsInfo();
3669 
3670   int lastInsIndex = -1;
3671   if (isVarArg && MFI.hasVAStart()) {
3672     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3673     if (RegIdx != array_lengthof(GPRArgRegs))
3674       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3675   }
3676 
3677   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3678   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3679   auto PtrVT = getPointerTy(DAG.getDataLayout());
3680 
3681   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3682     CCValAssign &VA = ArgLocs[i];
3683     if (Ins[VA.getValNo()].isOrigArg()) {
3684       std::advance(CurOrigArg,
3685                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3686       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3687     }
3688     // Arguments stored in registers.
3689     if (VA.isRegLoc()) {
3690       EVT RegVT = VA.getLocVT();
3691 
3692       if (VA.needsCustom()) {
3693         // f64 and vector types are split up into multiple registers or
3694         // combinations of registers and stack slots.
3695         if (VA.getLocVT() == MVT::v2f64) {
3696           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3697                                                    Chain, DAG, dl);
3698           VA = ArgLocs[++i]; // skip ahead to next loc
3699           SDValue ArgValue2;
3700           if (VA.isMemLoc()) {
3701             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3702             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3703             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3704                                     MachinePointerInfo::getFixedStack(
3705                                         DAG.getMachineFunction(), FI));
3706           } else {
3707             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3708                                              Chain, DAG, dl);
3709           }
3710           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3711           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3712                                  ArgValue, ArgValue1,
3713                                  DAG.getIntPtrConstant(0, dl));
3714           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3715                                  ArgValue, ArgValue2,
3716                                  DAG.getIntPtrConstant(1, dl));
3717         } else
3718           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3719       } else {
3720         const TargetRegisterClass *RC;
3721 
3722 
3723         if (RegVT == MVT::f16)
3724           RC = &ARM::HPRRegClass;
3725         else if (RegVT == MVT::f32)
3726           RC = &ARM::SPRRegClass;
3727         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3728           RC = &ARM::DPRRegClass;
3729         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3730           RC = &ARM::QPRRegClass;
3731         else if (RegVT == MVT::i32)
3732           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3733                                            : &ARM::GPRRegClass;
3734         else
3735           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3736 
3737         // Transform the arguments in physical registers into virtual ones.
3738         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3739         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3740       }
3741 
3742       // If this is an 8 or 16-bit value, it is really passed promoted
3743       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3744       // truncate to the right size.
3745       switch (VA.getLocInfo()) {
3746       default: llvm_unreachable("Unknown loc info!");
3747       case CCValAssign::Full: break;
3748       case CCValAssign::BCvt:
3749         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3750         break;
3751       case CCValAssign::SExt:
3752         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3753                                DAG.getValueType(VA.getValVT()));
3754         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3755         break;
3756       case CCValAssign::ZExt:
3757         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3758                                DAG.getValueType(VA.getValVT()));
3759         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3760         break;
3761       }
3762 
3763       InVals.push_back(ArgValue);
3764     } else { // VA.isRegLoc()
3765       // sanity check
3766       assert(VA.isMemLoc());
3767       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3768 
3769       int index = VA.getValNo();
3770 
3771       // Some Ins[] entries become multiple ArgLoc[] entries.
3772       // Process them only once.
3773       if (index != lastInsIndex)
3774         {
3775           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3776           // FIXME: For now, all byval parameter objects are marked mutable.
3777           // This can be changed with more analysis.
3778           // In case of tail call optimization mark all arguments mutable.
3779           // Since they could be overwritten by lowering of arguments in case of
3780           // a tail call.
3781           if (Flags.isByVal()) {
3782             assert(Ins[index].isOrigArg() &&
3783                    "Byval arguments cannot be implicit");
3784             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3785 
3786             int FrameIndex = StoreByValRegs(
3787                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3788                 VA.getLocMemOffset(), Flags.getByValSize());
3789             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3790             CCInfo.nextInRegsParam();
3791           } else {
3792             unsigned FIOffset = VA.getLocMemOffset();
3793             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3794                                            FIOffset, true);
3795 
3796             // Create load nodes to retrieve arguments from the stack.
3797             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3798             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3799                                          MachinePointerInfo::getFixedStack(
3800                                              DAG.getMachineFunction(), FI)));
3801           }
3802           lastInsIndex = index;
3803         }
3804     }
3805   }
3806 
3807   // varargs
3808   if (isVarArg && MFI.hasVAStart())
3809     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3810                          CCInfo.getNextStackOffset(),
3811                          TotalArgRegsSaveSize);
3812 
3813   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3814 
3815   return Chain;
3816 }
3817 
3818 /// isFloatingPointZero - Return true if this is +0.0.
3819 static bool isFloatingPointZero(SDValue Op) {
3820   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3821     return CFP->getValueAPF().isPosZero();
3822   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3823     // Maybe this has already been legalized into the constant pool?
3824     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3825       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3826       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3827         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3828           return CFP->getValueAPF().isPosZero();
3829     }
3830   } else if (Op->getOpcode() == ISD::BITCAST &&
3831              Op->getValueType(0) == MVT::f64) {
3832     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3833     // created by LowerConstantFP().
3834     SDValue BitcastOp = Op->getOperand(0);
3835     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3836         isNullConstant(BitcastOp->getOperand(0)))
3837       return true;
3838   }
3839   return false;
3840 }
3841 
3842 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3843 /// the given operands.
3844 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3845                                      SDValue &ARMcc, SelectionDAG &DAG,
3846                                      const SDLoc &dl) const {
3847   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3848     unsigned C = RHSC->getZExtValue();
3849     if (!isLegalICmpImmediate((int32_t)C)) {
3850       // Constant does not fit, try adjusting it by one.
3851       switch (CC) {
3852       default: break;
3853       case ISD::SETLT:
3854       case ISD::SETGE:
3855         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3856           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3857           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3858         }
3859         break;
3860       case ISD::SETULT:
3861       case ISD::SETUGE:
3862         if (C != 0 && isLegalICmpImmediate(C-1)) {
3863           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3864           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3865         }
3866         break;
3867       case ISD::SETLE:
3868       case ISD::SETGT:
3869         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3870           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3871           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3872         }
3873         break;
3874       case ISD::SETULE:
3875       case ISD::SETUGT:
3876         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3877           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3878           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3879         }
3880         break;
3881       }
3882     }
3883   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
3884              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
3885     // In ARM and Thumb-2, the compare instructions can shift their second
3886     // operand.
3887     CC = ISD::getSetCCSwappedOperands(CC);
3888     std::swap(LHS, RHS);
3889   }
3890 
3891   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3892   ARMISD::NodeType CompareType;
3893   switch (CondCode) {
3894   default:
3895     CompareType = ARMISD::CMP;
3896     break;
3897   case ARMCC::EQ:
3898   case ARMCC::NE:
3899     // Uses only Z Flag
3900     CompareType = ARMISD::CMPZ;
3901     break;
3902   }
3903   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3904   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3905 }
3906 
3907 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3908 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3909                                      SelectionDAG &DAG, const SDLoc &dl,
3910                                      bool InvalidOnQNaN) const {
3911   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3912   SDValue Cmp;
3913   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3914   if (!isFloatingPointZero(RHS))
3915     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3916   else
3917     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3918   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3919 }
3920 
3921 /// duplicateCmp - Glue values can have only one use, so this function
3922 /// duplicates a comparison node.
3923 SDValue
3924 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3925   unsigned Opc = Cmp.getOpcode();
3926   SDLoc DL(Cmp);
3927   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3928     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3929 
3930   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3931   Cmp = Cmp.getOperand(0);
3932   Opc = Cmp.getOpcode();
3933   if (Opc == ARMISD::CMPFP)
3934     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3935                       Cmp.getOperand(1), Cmp.getOperand(2));
3936   else {
3937     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3938     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3939                       Cmp.getOperand(1));
3940   }
3941   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3942 }
3943 
3944 // This function returns three things: the arithmetic computation itself
3945 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
3946 // comparison and the condition code define the case in which the arithmetic
3947 // computation *does not* overflow.
3948 std::pair<SDValue, SDValue>
3949 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3950                                  SDValue &ARMcc) const {
3951   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3952 
3953   SDValue Value, OverflowCmp;
3954   SDValue LHS = Op.getOperand(0);
3955   SDValue RHS = Op.getOperand(1);
3956   SDLoc dl(Op);
3957 
3958   // FIXME: We are currently always generating CMPs because we don't support
3959   // generating CMN through the backend. This is not as good as the natural
3960   // CMP case because it causes a register dependency and cannot be folded
3961   // later.
3962 
3963   switch (Op.getOpcode()) {
3964   default:
3965     llvm_unreachable("Unknown overflow instruction!");
3966   case ISD::SADDO:
3967     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3968     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3969     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3970     break;
3971   case ISD::UADDO:
3972     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3973     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
3974     // We do not use it in the USUBO case as Value may not be used.
3975     Value = DAG.getNode(ARMISD::ADDC, dl,
3976                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
3977                 .getValue(0);
3978     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3979     break;
3980   case ISD::SSUBO:
3981     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3982     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3983     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3984     break;
3985   case ISD::USUBO:
3986     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3987     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3988     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3989     break;
3990   case ISD::UMULO:
3991     // We generate a UMUL_LOHI and then check if the high word is 0.
3992     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
3993     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
3994                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
3995                         LHS, RHS);
3996     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
3997                               DAG.getConstant(0, dl, MVT::i32));
3998     Value = Value.getValue(0); // We only want the low 32 bits for the result.
3999     break;
4000   case ISD::SMULO:
4001     // We generate a SMUL_LOHI and then check if all the bits of the high word
4002     // are the same as the sign bit of the low word.
4003     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4004     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4005                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4006                         LHS, RHS);
4007     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4008                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4009                                           Value.getValue(0),
4010                                           DAG.getConstant(31, dl, MVT::i32)));
4011     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4012     break;
4013   } // switch (...)
4014 
4015   return std::make_pair(Value, OverflowCmp);
4016 }
4017 
4018 SDValue
4019 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4020   // Let legalize expand this if it isn't a legal type yet.
4021   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4022     return SDValue();
4023 
4024   SDValue Value, OverflowCmp;
4025   SDValue ARMcc;
4026   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4027   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4028   SDLoc dl(Op);
4029   // We use 0 and 1 as false and true values.
4030   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4031   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4032   EVT VT = Op.getValueType();
4033 
4034   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4035                                  ARMcc, CCR, OverflowCmp);
4036 
4037   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4038   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4039 }
4040 
4041 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4042                                               SelectionDAG &DAG) {
4043   SDLoc DL(BoolCarry);
4044   EVT CarryVT = BoolCarry.getValueType();
4045 
4046   // This converts the boolean value carry into the carry flag by doing
4047   // ARMISD::SUBC Carry, 1
4048   SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4049                               DAG.getVTList(CarryVT, MVT::i32),
4050                               BoolCarry, DAG.getConstant(1, DL, CarryVT));
4051   return Carry.getValue(1);
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 // Check if a condition of the type x < k ? k : x can be converted into a
4388 // bit operation instead of conditional moves.
4389 // Currently this is allowed given:
4390 // - The conditions and values match up
4391 // - k is 0 or -1 (all ones)
4392 // This function will not check the last condition, thats up to the caller
4393 // It returns true if the transformation can be made, and in such case
4394 // returns x in V, and k in SatK.
4395 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4396                                          SDValue &SatK)
4397 {
4398   SDValue LHS = Op.getOperand(0);
4399   SDValue RHS = Op.getOperand(1);
4400   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4401   SDValue TrueVal = Op.getOperand(2);
4402   SDValue FalseVal = Op.getOperand(3);
4403 
4404   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4405                                                ? &RHS
4406                                                : nullptr;
4407 
4408   // No constant operation in comparison, early out
4409   if (!K)
4410     return false;
4411 
4412   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4413   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4414   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4415 
4416   // If the constant on left and right side, or variable on left and right,
4417   // does not match, early out
4418   if (*K != KTmp || V != VTmp)
4419     return false;
4420 
4421   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4422     SatK = *K;
4423     return true;
4424   }
4425 
4426   return false;
4427 }
4428 
4429 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4430   EVT VT = Op.getValueType();
4431   SDLoc dl(Op);
4432 
4433   // Try to convert two saturating conditional selects into a single SSAT
4434   SDValue SatValue;
4435   uint64_t SatConstant;
4436   bool SatUSat;
4437   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4438       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4439     if (SatUSat)
4440       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4441                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4442     else
4443       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4444                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4445   }
4446 
4447   // Try to convert expressions of the form x < k ? k : x (and similar forms)
4448   // into more efficient bit operations, which is possible when k is 0 or -1
4449   // On ARM and Thumb-2 which have flexible operand 2 this will result in
4450   // single instructions. On Thumb the shift and the bit operation will be two
4451   // instructions.
4452   // Only allow this transformation on full-width (32-bit) operations
4453   SDValue LowerSatConstant;
4454   if (VT == MVT::i32 &&
4455       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4456     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4457                                  DAG.getConstant(31, dl, VT));
4458     if (isNullConstant(LowerSatConstant)) {
4459       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4460                                       DAG.getAllOnesConstant(dl, VT));
4461       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4462     } else if (isAllOnesConstant(LowerSatConstant))
4463       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4464   }
4465 
4466   SDValue LHS = Op.getOperand(0);
4467   SDValue RHS = Op.getOperand(1);
4468   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4469   SDValue TrueVal = Op.getOperand(2);
4470   SDValue FalseVal = Op.getOperand(3);
4471 
4472   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4473     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4474                                                     dl);
4475 
4476     // If softenSetCCOperands only returned one value, we should compare it to
4477     // zero.
4478     if (!RHS.getNode()) {
4479       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4480       CC = ISD::SETNE;
4481     }
4482   }
4483 
4484   if (LHS.getValueType() == MVT::i32) {
4485     // Try to generate VSEL on ARMv8.
4486     // The VSEL instruction can't use all the usual ARM condition
4487     // codes: it only has two bits to select the condition code, so it's
4488     // constrained to use only GE, GT, VS and EQ.
4489     //
4490     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4491     // swap the operands of the previous compare instruction (effectively
4492     // inverting the compare condition, swapping 'less' and 'greater') and
4493     // sometimes need to swap the operands to the VSEL (which inverts the
4494     // condition in the sense of firing whenever the previous condition didn't)
4495     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4496                                     TrueVal.getValueType() == MVT::f64)) {
4497       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4498       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4499           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4500         CC = ISD::getSetCCInverse(CC, true);
4501         std::swap(TrueVal, FalseVal);
4502       }
4503     }
4504 
4505     SDValue ARMcc;
4506     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4507     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4508     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4509   }
4510 
4511   ARMCC::CondCodes CondCode, CondCode2;
4512   bool InvalidOnQNaN;
4513   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4514 
4515   // Normalize the fp compare. If RHS is zero we keep it there so we match
4516   // CMPFPw0 instead of CMPFP.
4517   if (Subtarget->hasFPARMv8() && !isFloatingPointZero(RHS) &&
4518      (TrueVal.getValueType() == MVT::f16 ||
4519       TrueVal.getValueType() == MVT::f32 ||
4520       TrueVal.getValueType() == MVT::f64)) {
4521     bool swpCmpOps = false;
4522     bool swpVselOps = false;
4523     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4524 
4525     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4526         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4527       if (swpCmpOps)
4528         std::swap(LHS, RHS);
4529       if (swpVselOps)
4530         std::swap(TrueVal, FalseVal);
4531     }
4532   }
4533 
4534   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4535   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4536   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4537   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4538   if (CondCode2 != ARMCC::AL) {
4539     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4540     // FIXME: Needs another CMP because flag can have but one use.
4541     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4542     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4543   }
4544   return Result;
4545 }
4546 
4547 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4548 /// to morph to an integer compare sequence.
4549 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4550                            const ARMSubtarget *Subtarget) {
4551   SDNode *N = Op.getNode();
4552   if (!N->hasOneUse())
4553     // Otherwise it requires moving the value from fp to integer registers.
4554     return false;
4555   if (!N->getNumValues())
4556     return false;
4557   EVT VT = Op.getValueType();
4558   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4559     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4560     // vmrs are very slow, e.g. cortex-a8.
4561     return false;
4562 
4563   if (isFloatingPointZero(Op)) {
4564     SeenZero = true;
4565     return true;
4566   }
4567   return ISD::isNormalLoad(N);
4568 }
4569 
4570 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4571   if (isFloatingPointZero(Op))
4572     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4573 
4574   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4575     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4576                        Ld->getPointerInfo(), Ld->getAlignment(),
4577                        Ld->getMemOperand()->getFlags());
4578 
4579   llvm_unreachable("Unknown VFP cmp argument!");
4580 }
4581 
4582 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4583                            SDValue &RetVal1, SDValue &RetVal2) {
4584   SDLoc dl(Op);
4585 
4586   if (isFloatingPointZero(Op)) {
4587     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4588     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4589     return;
4590   }
4591 
4592   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4593     SDValue Ptr = Ld->getBasePtr();
4594     RetVal1 =
4595         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4596                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4597 
4598     EVT PtrType = Ptr.getValueType();
4599     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4600     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4601                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4602     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4603                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4604                           Ld->getMemOperand()->getFlags());
4605     return;
4606   }
4607 
4608   llvm_unreachable("Unknown VFP cmp argument!");
4609 }
4610 
4611 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4612 /// f32 and even f64 comparisons to integer ones.
4613 SDValue
4614 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4615   SDValue Chain = Op.getOperand(0);
4616   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4617   SDValue LHS = Op.getOperand(2);
4618   SDValue RHS = Op.getOperand(3);
4619   SDValue Dest = Op.getOperand(4);
4620   SDLoc dl(Op);
4621 
4622   bool LHSSeenZero = false;
4623   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4624   bool RHSSeenZero = false;
4625   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4626   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4627     // If unsafe fp math optimization is enabled and there are no other uses of
4628     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4629     // to an integer comparison.
4630     if (CC == ISD::SETOEQ)
4631       CC = ISD::SETEQ;
4632     else if (CC == ISD::SETUNE)
4633       CC = ISD::SETNE;
4634 
4635     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4636     SDValue ARMcc;
4637     if (LHS.getValueType() == MVT::f32) {
4638       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4639                         bitcastf32Toi32(LHS, DAG), Mask);
4640       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4641                         bitcastf32Toi32(RHS, DAG), Mask);
4642       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4643       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4644       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4645                          Chain, Dest, ARMcc, CCR, Cmp);
4646     }
4647 
4648     SDValue LHS1, LHS2;
4649     SDValue RHS1, RHS2;
4650     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4651     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4652     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4653     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4654     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4655     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4656     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4657     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4658     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4659   }
4660 
4661   return SDValue();
4662 }
4663 
4664 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4665   SDValue Chain = Op.getOperand(0);
4666   SDValue Cond = Op.getOperand(1);
4667   SDValue Dest = Op.getOperand(2);
4668   SDLoc dl(Op);
4669 
4670   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4671   // instruction.
4672   unsigned Opc = Cond.getOpcode();
4673   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4674                       !Subtarget->isThumb1Only();
4675   if (Cond.getResNo() == 1 &&
4676       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4677        Opc == ISD::USUBO || OptimizeMul)) {
4678     // Only lower legal XALUO ops.
4679     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4680       return SDValue();
4681 
4682     // The actual operation with overflow check.
4683     SDValue Value, OverflowCmp;
4684     SDValue ARMcc;
4685     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4686 
4687     // Reverse the condition code.
4688     ARMCC::CondCodes CondCode =
4689         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4690     CondCode = ARMCC::getOppositeCondition(CondCode);
4691     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4692     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4693 
4694     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4695                        OverflowCmp);
4696   }
4697 
4698   return SDValue();
4699 }
4700 
4701 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4702   SDValue Chain = Op.getOperand(0);
4703   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4704   SDValue LHS = Op.getOperand(2);
4705   SDValue RHS = Op.getOperand(3);
4706   SDValue Dest = Op.getOperand(4);
4707   SDLoc dl(Op);
4708 
4709   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4710     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4711                                                     dl);
4712 
4713     // If softenSetCCOperands only returned one value, we should compare it to
4714     // zero.
4715     if (!RHS.getNode()) {
4716       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4717       CC = ISD::SETNE;
4718     }
4719   }
4720 
4721   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4722   // instruction.
4723   unsigned Opc = LHS.getOpcode();
4724   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4725                       !Subtarget->isThumb1Only();
4726   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
4727       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4728        Opc == ISD::USUBO || OptimizeMul) &&
4729       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4730     // Only lower legal XALUO ops.
4731     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4732       return SDValue();
4733 
4734     // The actual operation with overflow check.
4735     SDValue Value, OverflowCmp;
4736     SDValue ARMcc;
4737     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
4738 
4739     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
4740       // Reverse the condition code.
4741       ARMCC::CondCodes CondCode =
4742           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4743       CondCode = ARMCC::getOppositeCondition(CondCode);
4744       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4745     }
4746     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4747 
4748     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4749                        OverflowCmp);
4750   }
4751 
4752   if (LHS.getValueType() == MVT::i32) {
4753     SDValue ARMcc;
4754     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4755     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4756     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4757                        Chain, Dest, ARMcc, CCR, Cmp);
4758   }
4759 
4760   if (getTargetMachine().Options.UnsafeFPMath &&
4761       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4762        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4763     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4764       return Result;
4765   }
4766 
4767   ARMCC::CondCodes CondCode, CondCode2;
4768   bool InvalidOnQNaN;
4769   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4770 
4771   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4772   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4773   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4774   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4775   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4776   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4777   if (CondCode2 != ARMCC::AL) {
4778     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4779     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4780     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4781   }
4782   return Res;
4783 }
4784 
4785 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4786   SDValue Chain = Op.getOperand(0);
4787   SDValue Table = Op.getOperand(1);
4788   SDValue Index = Op.getOperand(2);
4789   SDLoc dl(Op);
4790 
4791   EVT PTy = getPointerTy(DAG.getDataLayout());
4792   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4793   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4794   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4795   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4796   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
4797   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4798     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4799     // which does another jump to the destination. This also makes it easier
4800     // to translate it to TBB / TBH later (Thumb2 only).
4801     // FIXME: This might not work if the function is extremely large.
4802     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4803                        Addr, Op.getOperand(2), JTI);
4804   }
4805   if (isPositionIndependent() || Subtarget->isROPI()) {
4806     Addr =
4807         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4808                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4809     Chain = Addr.getValue(1);
4810     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
4811     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4812   } else {
4813     Addr =
4814         DAG.getLoad(PTy, dl, Chain, Addr,
4815                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4816     Chain = Addr.getValue(1);
4817     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4818   }
4819 }
4820 
4821 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4822   EVT VT = Op.getValueType();
4823   SDLoc dl(Op);
4824 
4825   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4826     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4827       return Op;
4828     return DAG.UnrollVectorOp(Op.getNode());
4829   }
4830 
4831   const bool HasFullFP16 =
4832     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
4833 
4834   EVT NewTy;
4835   const EVT OpTy = Op.getOperand(0).getValueType();
4836   if (OpTy == MVT::v4f32)
4837     NewTy = MVT::v4i32;
4838   else if (OpTy == MVT::v4f16 && HasFullFP16)
4839     NewTy = MVT::v4i16;
4840   else if (OpTy == MVT::v8f16 && HasFullFP16)
4841     NewTy = MVT::v8i16;
4842   else
4843     llvm_unreachable("Invalid type for custom lowering!");
4844 
4845   if (VT != MVT::v4i16 && VT != MVT::v8i16)
4846     return DAG.UnrollVectorOp(Op.getNode());
4847 
4848   Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
4849   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4850 }
4851 
4852 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4853   EVT VT = Op.getValueType();
4854   if (VT.isVector())
4855     return LowerVectorFP_TO_INT(Op, DAG);
4856   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4857     RTLIB::Libcall LC;
4858     if (Op.getOpcode() == ISD::FP_TO_SINT)
4859       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4860                               Op.getValueType());
4861     else
4862       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4863                               Op.getValueType());
4864     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4865                        /*isSigned*/ false, SDLoc(Op)).first;
4866   }
4867 
4868   return Op;
4869 }
4870 
4871 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4872   EVT VT = Op.getValueType();
4873   SDLoc dl(Op);
4874 
4875   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4876     if (VT.getVectorElementType() == MVT::f32)
4877       return Op;
4878     return DAG.UnrollVectorOp(Op.getNode());
4879   }
4880 
4881   assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
4882           Op.getOperand(0).getValueType() == MVT::v8i16) &&
4883          "Invalid type for custom lowering!");
4884 
4885   const bool HasFullFP16 =
4886     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
4887 
4888   EVT DestVecType;
4889   if (VT == MVT::v4f32)
4890     DestVecType = MVT::v4i32;
4891   else if (VT == MVT::v4f16 && HasFullFP16)
4892     DestVecType = MVT::v4i16;
4893   else if (VT == MVT::v8f16 && HasFullFP16)
4894     DestVecType = MVT::v8i16;
4895   else
4896     return DAG.UnrollVectorOp(Op.getNode());
4897 
4898   unsigned CastOpc;
4899   unsigned Opc;
4900   switch (Op.getOpcode()) {
4901   default: llvm_unreachable("Invalid opcode!");
4902   case ISD::SINT_TO_FP:
4903     CastOpc = ISD::SIGN_EXTEND;
4904     Opc = ISD::SINT_TO_FP;
4905     break;
4906   case ISD::UINT_TO_FP:
4907     CastOpc = ISD::ZERO_EXTEND;
4908     Opc = ISD::UINT_TO_FP;
4909     break;
4910   }
4911 
4912   Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
4913   return DAG.getNode(Opc, dl, VT, Op);
4914 }
4915 
4916 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4917   EVT VT = Op.getValueType();
4918   if (VT.isVector())
4919     return LowerVectorINT_TO_FP(Op, DAG);
4920   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4921     RTLIB::Libcall LC;
4922     if (Op.getOpcode() == ISD::SINT_TO_FP)
4923       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4924                               Op.getValueType());
4925     else
4926       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4927                               Op.getValueType());
4928     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4929                        /*isSigned*/ false, SDLoc(Op)).first;
4930   }
4931 
4932   return Op;
4933 }
4934 
4935 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4936   // Implement fcopysign with a fabs and a conditional fneg.
4937   SDValue Tmp0 = Op.getOperand(0);
4938   SDValue Tmp1 = Op.getOperand(1);
4939   SDLoc dl(Op);
4940   EVT VT = Op.getValueType();
4941   EVT SrcVT = Tmp1.getValueType();
4942   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4943     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4944   bool UseNEON = !InGPR && Subtarget->hasNEON();
4945 
4946   if (UseNEON) {
4947     // Use VBSL to copy the sign bit.
4948     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4949     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4950                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4951     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4952     if (VT == MVT::f64)
4953       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4954                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4955                          DAG.getConstant(32, dl, MVT::i32));
4956     else /*if (VT == MVT::f32)*/
4957       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4958     if (SrcVT == MVT::f32) {
4959       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4960       if (VT == MVT::f64)
4961         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4962                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4963                            DAG.getConstant(32, dl, MVT::i32));
4964     } else if (VT == MVT::f32)
4965       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4966                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4967                          DAG.getConstant(32, dl, MVT::i32));
4968     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4969     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4970 
4971     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4972                                             dl, MVT::i32);
4973     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4974     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4975                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4976 
4977     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4978                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4979                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4980     if (VT == MVT::f32) {
4981       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4982       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4983                         DAG.getConstant(0, dl, MVT::i32));
4984     } else {
4985       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4986     }
4987 
4988     return Res;
4989   }
4990 
4991   // Bitcast operand 1 to i32.
4992   if (SrcVT == MVT::f64)
4993     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4994                        Tmp1).getValue(1);
4995   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4996 
4997   // Or in the signbit with integer operations.
4998   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4999   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5000   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5001   if (VT == MVT::f32) {
5002     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5003                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5004     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5005                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5006   }
5007 
5008   // f64: Or the high part with signbit and then combine two parts.
5009   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5010                      Tmp0);
5011   SDValue Lo = Tmp0.getValue(0);
5012   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5013   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5014   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5015 }
5016 
5017 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5018   MachineFunction &MF = DAG.getMachineFunction();
5019   MachineFrameInfo &MFI = MF.getFrameInfo();
5020   MFI.setReturnAddressIsTaken(true);
5021 
5022   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5023     return SDValue();
5024 
5025   EVT VT = Op.getValueType();
5026   SDLoc dl(Op);
5027   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5028   if (Depth) {
5029     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5030     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5031     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5032                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5033                        MachinePointerInfo());
5034   }
5035 
5036   // Return LR, which contains the return address. Mark it an implicit live-in.
5037   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5038   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5039 }
5040 
5041 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5042   const ARMBaseRegisterInfo &ARI =
5043     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5044   MachineFunction &MF = DAG.getMachineFunction();
5045   MachineFrameInfo &MFI = MF.getFrameInfo();
5046   MFI.setFrameAddressIsTaken(true);
5047 
5048   EVT VT = Op.getValueType();
5049   SDLoc dl(Op);  // FIXME probably not meaningful
5050   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5051   unsigned FrameReg = ARI.getFrameRegister(MF);
5052   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5053   while (Depth--)
5054     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5055                             MachinePointerInfo());
5056   return FrameAddr;
5057 }
5058 
5059 // FIXME? Maybe this could be a TableGen attribute on some registers and
5060 // this table could be generated automatically from RegInfo.
5061 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5062                                               SelectionDAG &DAG) const {
5063   unsigned Reg = StringSwitch<unsigned>(RegName)
5064                        .Case("sp", ARM::SP)
5065                        .Default(0);
5066   if (Reg)
5067     return Reg;
5068   report_fatal_error(Twine("Invalid register name \""
5069                               + StringRef(RegName)  + "\"."));
5070 }
5071 
5072 // Result is 64 bit value so split into two 32 bit values and return as a
5073 // pair of values.
5074 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5075                                 SelectionDAG &DAG) {
5076   SDLoc DL(N);
5077 
5078   // This function is only supposed to be called for i64 type destination.
5079   assert(N->getValueType(0) == MVT::i64
5080           && "ExpandREAD_REGISTER called for non-i64 type result.");
5081 
5082   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5083                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5084                              N->getOperand(0),
5085                              N->getOperand(1));
5086 
5087   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5088                     Read.getValue(1)));
5089   Results.push_back(Read.getOperand(0));
5090 }
5091 
5092 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5093 /// When \p DstVT, the destination type of \p BC, is on the vector
5094 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5095 /// it might be possible to combine them, such that everything stays on the
5096 /// vector register bank.
5097 /// \p return The node that would replace \p BT, if the combine
5098 /// is possible.
5099 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5100                                                 SelectionDAG &DAG) {
5101   SDValue Op = BC->getOperand(0);
5102   EVT DstVT = BC->getValueType(0);
5103 
5104   // The only vector instruction that can produce a scalar (remember,
5105   // since the bitcast was about to be turned into VMOVDRR, the source
5106   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5107   // Moreover, we can do this combine only if there is one use.
5108   // Finally, if the destination type is not a vector, there is not
5109   // much point on forcing everything on the vector bank.
5110   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5111       !Op.hasOneUse())
5112     return SDValue();
5113 
5114   // If the index is not constant, we will introduce an additional
5115   // multiply that will stick.
5116   // Give up in that case.
5117   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5118   if (!Index)
5119     return SDValue();
5120   unsigned DstNumElt = DstVT.getVectorNumElements();
5121 
5122   // Compute the new index.
5123   const APInt &APIntIndex = Index->getAPIntValue();
5124   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5125   NewIndex *= APIntIndex;
5126   // Check if the new constant index fits into i32.
5127   if (NewIndex.getBitWidth() > 32)
5128     return SDValue();
5129 
5130   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5131   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5132   SDLoc dl(Op);
5133   SDValue ExtractSrc = Op.getOperand(0);
5134   EVT VecVT = EVT::getVectorVT(
5135       *DAG.getContext(), DstVT.getScalarType(),
5136       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5137   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5138   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5139                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5140 }
5141 
5142 /// ExpandBITCAST - If the target supports VFP, this function is called to
5143 /// expand a bit convert where either the source or destination type is i64 to
5144 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5145 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5146 /// vectors), since the legalizer won't know what to do with that.
5147 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5148                              const ARMSubtarget *Subtarget) {
5149   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5150   SDLoc dl(N);
5151   SDValue Op = N->getOperand(0);
5152 
5153   // This function is only supposed to be called for i64 types, either as the
5154   // source or destination of the bit convert.
5155   EVT SrcVT = Op.getValueType();
5156   EVT DstVT = N->getValueType(0);
5157   const bool HasFullFP16 = Subtarget->hasFullFP16();
5158 
5159   if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5160      // FullFP16: half values are passed in S-registers, and we don't
5161      // need any of the bitcast and moves:
5162      //
5163      // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5164      //   t5: i32 = bitcast t2
5165      // t18: f16 = ARMISD::VMOVhr t5
5166      if (Op.getOpcode() != ISD::CopyFromReg ||
5167          Op.getValueType() != MVT::f32)
5168        return SDValue();
5169 
5170      auto Move = N->use_begin();
5171      if (Move->getOpcode() != ARMISD::VMOVhr)
5172        return SDValue();
5173 
5174      SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5175      SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5176      DAG.ReplaceAllUsesWith(*Move, &Copy);
5177      return Copy;
5178   }
5179 
5180   if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5181     if (!HasFullFP16)
5182       return SDValue();
5183     // SoftFP: read half-precision arguments:
5184     //
5185     // t2: i32,ch = ...
5186     //        t7: i16 = truncate t2 <~~~~ Op
5187     //      t8: f16 = bitcast t7    <~~~~ N
5188     //
5189     if (Op.getOperand(0).getValueType() == MVT::i32)
5190       return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5191                          MVT::f16, Op.getOperand(0));
5192 
5193     return SDValue();
5194   }
5195 
5196   // Half-precision return values
5197   if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5198     if (!HasFullFP16)
5199       return SDValue();
5200     //
5201     //          t11: f16 = fadd t8, t10
5202     //        t12: i16 = bitcast t11       <~~~ SDNode N
5203     //      t13: i32 = zero_extend t12
5204     //    t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5205     //  t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5206     //
5207     // transform this into:
5208     //
5209     //    t20: i32 = ARMISD::VMOVrh t11
5210     //  t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5211     //
5212     auto ZeroExtend = N->use_begin();
5213     if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5214         ZeroExtend->getValueType(0) != MVT::i32)
5215       return SDValue();
5216 
5217     auto Copy = ZeroExtend->use_begin();
5218     if (Copy->getOpcode() == ISD::CopyToReg &&
5219         Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5220       SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5221       DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5222       return Cvt;
5223     }
5224     return SDValue();
5225   }
5226 
5227   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5228     return SDValue();
5229 
5230   // Turn i64->f64 into VMOVDRR.
5231   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5232     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5233     // if we can combine the bitcast with its source.
5234     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5235       return Val;
5236 
5237     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5238                              DAG.getConstant(0, dl, MVT::i32));
5239     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5240                              DAG.getConstant(1, dl, MVT::i32));
5241     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5242                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5243   }
5244 
5245   // Turn f64->i64 into VMOVRRD.
5246   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5247     SDValue Cvt;
5248     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5249         SrcVT.getVectorNumElements() > 1)
5250       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5251                         DAG.getVTList(MVT::i32, MVT::i32),
5252                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5253     else
5254       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5255                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5256     // Merge the pieces into a single i64 value.
5257     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5258   }
5259 
5260   return SDValue();
5261 }
5262 
5263 /// getZeroVector - Returns a vector of specified type with all zero elements.
5264 /// Zero vectors are used to represent vector negation and in those cases
5265 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
5266 /// not support i64 elements, so sometimes the zero vectors will need to be
5267 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
5268 /// zero vector.
5269 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5270   assert(VT.isVector() && "Expected a vector type");
5271   // The canonical modified immediate encoding of a zero vector is....0!
5272   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5273   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5274   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5275   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5276 }
5277 
5278 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5279 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5280 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5281                                                 SelectionDAG &DAG) const {
5282   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5283   EVT VT = Op.getValueType();
5284   unsigned VTBits = VT.getSizeInBits();
5285   SDLoc dl(Op);
5286   SDValue ShOpLo = Op.getOperand(0);
5287   SDValue ShOpHi = Op.getOperand(1);
5288   SDValue ShAmt  = Op.getOperand(2);
5289   SDValue ARMcc;
5290   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5291   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5292 
5293   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5294 
5295   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5296                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5297   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5298   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5299                                    DAG.getConstant(VTBits, dl, MVT::i32));
5300   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5301   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5302   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5303   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5304                             ISD::SETGE, ARMcc, DAG, dl);
5305   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5306                            ARMcc, CCR, CmpLo);
5307 
5308   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5309   SDValue HiBigShift = Opc == ISD::SRA
5310                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5311                                          DAG.getConstant(VTBits - 1, dl, VT))
5312                            : DAG.getConstant(0, dl, VT);
5313   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5314                             ISD::SETGE, ARMcc, DAG, dl);
5315   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5316                            ARMcc, CCR, CmpHi);
5317 
5318   SDValue Ops[2] = { Lo, Hi };
5319   return DAG.getMergeValues(Ops, dl);
5320 }
5321 
5322 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5323 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5324 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5325                                                SelectionDAG &DAG) const {
5326   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5327   EVT VT = Op.getValueType();
5328   unsigned VTBits = VT.getSizeInBits();
5329   SDLoc dl(Op);
5330   SDValue ShOpLo = Op.getOperand(0);
5331   SDValue ShOpHi = Op.getOperand(1);
5332   SDValue ShAmt  = Op.getOperand(2);
5333   SDValue ARMcc;
5334   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5335 
5336   assert(Op.getOpcode() == ISD::SHL_PARTS);
5337   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5338                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5339   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5340   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5341   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5342 
5343   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5344                                    DAG.getConstant(VTBits, dl, MVT::i32));
5345   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5346   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5347                             ISD::SETGE, ARMcc, DAG, dl);
5348   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5349                            ARMcc, CCR, CmpHi);
5350 
5351   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5352                           ISD::SETGE, ARMcc, DAG, dl);
5353   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5354   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5355                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5356 
5357   SDValue Ops[2] = { Lo, Hi };
5358   return DAG.getMergeValues(Ops, dl);
5359 }
5360 
5361 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5362                                             SelectionDAG &DAG) const {
5363   // The rounding mode is in bits 23:22 of the FPSCR.
5364   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5365   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5366   // so that the shift + and get folded into a bitfield extract.
5367   SDLoc dl(Op);
5368   SDValue Ops[] = { DAG.getEntryNode(),
5369                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5370 
5371   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5372   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5373                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5374   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5375                               DAG.getConstant(22, dl, MVT::i32));
5376   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5377                      DAG.getConstant(3, dl, MVT::i32));
5378 }
5379 
5380 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5381                          const ARMSubtarget *ST) {
5382   SDLoc dl(N);
5383   EVT VT = N->getValueType(0);
5384   if (VT.isVector()) {
5385     assert(ST->hasNEON());
5386 
5387     // Compute the least significant set bit: LSB = X & -X
5388     SDValue X = N->getOperand(0);
5389     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5390     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5391 
5392     EVT ElemTy = VT.getVectorElementType();
5393 
5394     if (ElemTy == MVT::i8) {
5395       // Compute with: cttz(x) = ctpop(lsb - 1)
5396       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5397                                 DAG.getTargetConstant(1, dl, ElemTy));
5398       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5399       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5400     }
5401 
5402     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5403         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5404       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5405       unsigned NumBits = ElemTy.getSizeInBits();
5406       SDValue WidthMinus1 =
5407           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5408                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5409       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5410       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5411     }
5412 
5413     // Compute with: cttz(x) = ctpop(lsb - 1)
5414 
5415     // Compute LSB - 1.
5416     SDValue Bits;
5417     if (ElemTy == MVT::i64) {
5418       // Load constant 0xffff'ffff'ffff'ffff to register.
5419       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5420                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5421       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5422     } else {
5423       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5424                                 DAG.getTargetConstant(1, dl, ElemTy));
5425       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5426     }
5427     return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5428   }
5429 
5430   if (!ST->hasV6T2Ops())
5431     return SDValue();
5432 
5433   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5434   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5435 }
5436 
5437 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5438                           const ARMSubtarget *ST) {
5439   EVT VT = N->getValueType(0);
5440   SDLoc DL(N);
5441 
5442   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5443   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5444           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5445          "Unexpected type for custom ctpop lowering");
5446 
5447   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5448   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5449   SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5450   Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5451 
5452   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5453   unsigned EltSize = 8;
5454   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5455   while (EltSize != VT.getScalarSizeInBits()) {
5456     SmallVector<SDValue, 8> Ops;
5457     Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5458                                   TLI.getPointerTy(DAG.getDataLayout())));
5459     Ops.push_back(Res);
5460 
5461     EltSize *= 2;
5462     NumElts /= 2;
5463     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5464     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5465   }
5466 
5467   return Res;
5468 }
5469 
5470 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5471                           const ARMSubtarget *ST) {
5472   EVT VT = N->getValueType(0);
5473   SDLoc dl(N);
5474 
5475   if (!VT.isVector())
5476     return SDValue();
5477 
5478   // Lower vector shifts on NEON to use VSHL.
5479   assert(ST->hasNEON() && "unexpected vector shift");
5480 
5481   // Left shifts translate directly to the vshiftu intrinsic.
5482   if (N->getOpcode() == ISD::SHL)
5483     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5484                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5485                                        MVT::i32),
5486                        N->getOperand(0), N->getOperand(1));
5487 
5488   assert((N->getOpcode() == ISD::SRA ||
5489           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5490 
5491   // NEON uses the same intrinsics for both left and right shifts.  For
5492   // right shifts, the shift amounts are negative, so negate the vector of
5493   // shift amounts.
5494   EVT ShiftVT = N->getOperand(1).getValueType();
5495   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5496                                      getZeroVector(ShiftVT, DAG, dl),
5497                                      N->getOperand(1));
5498   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5499                              Intrinsic::arm_neon_vshifts :
5500                              Intrinsic::arm_neon_vshiftu);
5501   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5502                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5503                      N->getOperand(0), NegatedCount);
5504 }
5505 
5506 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5507                                 const ARMSubtarget *ST) {
5508   EVT VT = N->getValueType(0);
5509   SDLoc dl(N);
5510 
5511   // We can get here for a node like i32 = ISD::SHL i32, i64
5512   if (VT != MVT::i64)
5513     return SDValue();
5514 
5515   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5516          "Unknown shift to lower!");
5517 
5518   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5519   if (!isOneConstant(N->getOperand(1)))
5520     return SDValue();
5521 
5522   // If we are in thumb mode, we don't have RRX.
5523   if (ST->isThumb1Only()) return SDValue();
5524 
5525   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5526   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5527                            DAG.getConstant(0, dl, MVT::i32));
5528   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5529                            DAG.getConstant(1, dl, MVT::i32));
5530 
5531   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5532   // captures the result into a carry flag.
5533   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5534   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5535 
5536   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5537   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5538 
5539   // Merge the pieces into a single i64 value.
5540  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5541 }
5542 
5543 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5544   SDValue TmpOp0, TmpOp1;
5545   bool Invert = false;
5546   bool Swap = false;
5547   unsigned Opc = 0;
5548 
5549   SDValue Op0 = Op.getOperand(0);
5550   SDValue Op1 = Op.getOperand(1);
5551   SDValue CC = Op.getOperand(2);
5552   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5553   EVT VT = Op.getValueType();
5554   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5555   SDLoc dl(Op);
5556 
5557   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5558       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5559     // Special-case integer 64-bit equality comparisons. They aren't legal,
5560     // but they can be lowered with a few vector instructions.
5561     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5562     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5563     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5564     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5565     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5566                               DAG.getCondCode(ISD::SETEQ));
5567     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5568     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5569     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5570     if (SetCCOpcode == ISD::SETNE)
5571       Merged = DAG.getNOT(dl, Merged, CmpVT);
5572     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5573     return Merged;
5574   }
5575 
5576   if (CmpVT.getVectorElementType() == MVT::i64)
5577     // 64-bit comparisons are not legal in general.
5578     return SDValue();
5579 
5580   if (Op1.getValueType().isFloatingPoint()) {
5581     switch (SetCCOpcode) {
5582     default: llvm_unreachable("Illegal FP comparison");
5583     case ISD::SETUNE:
5584     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5585     case ISD::SETOEQ:
5586     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5587     case ISD::SETOLT:
5588     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5589     case ISD::SETOGT:
5590     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5591     case ISD::SETOLE:
5592     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5593     case ISD::SETOGE:
5594     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5595     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5596     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5597     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5598     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5599     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5600     case ISD::SETONE:
5601       // Expand this to (OLT | OGT).
5602       TmpOp0 = Op0;
5603       TmpOp1 = Op1;
5604       Opc = ISD::OR;
5605       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5606       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5607       break;
5608     case ISD::SETUO:
5609       Invert = true;
5610       LLVM_FALLTHROUGH;
5611     case ISD::SETO:
5612       // Expand this to (OLT | OGE).
5613       TmpOp0 = Op0;
5614       TmpOp1 = Op1;
5615       Opc = ISD::OR;
5616       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5617       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5618       break;
5619     }
5620   } else {
5621     // Integer comparisons.
5622     switch (SetCCOpcode) {
5623     default: llvm_unreachable("Illegal integer comparison");
5624     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5625     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5626     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
5627     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5628     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5629     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5630     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5631     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5632     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5633     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5634     }
5635 
5636     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5637     if (Opc == ARMISD::VCEQ) {
5638       SDValue AndOp;
5639       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5640         AndOp = Op0;
5641       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5642         AndOp = Op1;
5643 
5644       // Ignore bitconvert.
5645       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5646         AndOp = AndOp.getOperand(0);
5647 
5648       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5649         Opc = ARMISD::VTST;
5650         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5651         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5652         Invert = !Invert;
5653       }
5654     }
5655   }
5656 
5657   if (Swap)
5658     std::swap(Op0, Op1);
5659 
5660   // If one of the operands is a constant vector zero, attempt to fold the
5661   // comparison to a specialized compare-against-zero form.
5662   SDValue SingleOp;
5663   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5664     SingleOp = Op0;
5665   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5666     if (Opc == ARMISD::VCGE)
5667       Opc = ARMISD::VCLEZ;
5668     else if (Opc == ARMISD::VCGT)
5669       Opc = ARMISD::VCLTZ;
5670     SingleOp = Op1;
5671   }
5672 
5673   SDValue Result;
5674   if (SingleOp.getNode()) {
5675     switch (Opc) {
5676     case ARMISD::VCEQ:
5677       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5678     case ARMISD::VCGE:
5679       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5680     case ARMISD::VCLEZ:
5681       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5682     case ARMISD::VCGT:
5683       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5684     case ARMISD::VCLTZ:
5685       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5686     default:
5687       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5688     }
5689   } else {
5690      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5691   }
5692 
5693   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5694 
5695   if (Invert)
5696     Result = DAG.getNOT(dl, Result, VT);
5697 
5698   return Result;
5699 }
5700 
5701 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
5702   SDValue LHS = Op.getOperand(0);
5703   SDValue RHS = Op.getOperand(1);
5704   SDValue Carry = Op.getOperand(2);
5705   SDValue Cond = Op.getOperand(3);
5706   SDLoc DL(Op);
5707 
5708   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
5709 
5710   // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
5711   // have to invert the carry first.
5712   Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
5713                       DAG.getConstant(1, DL, MVT::i32), Carry);
5714   // This converts the boolean value carry into the carry flag.
5715   Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
5716 
5717   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5718   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5719 
5720   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5721   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5722   SDValue ARMcc = DAG.getConstant(
5723       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5724   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5725   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5726                                    Cmp.getValue(1), SDValue());
5727   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5728                      CCR, Chain.getValue(1));
5729 }
5730 
5731 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5732 /// valid vector constant for a NEON instruction with a "modified immediate"
5733 /// operand (e.g., VMOV).  If so, return the encoded value.
5734 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5735                                  unsigned SplatBitSize, SelectionDAG &DAG,
5736                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5737                                  NEONModImmType type) {
5738   unsigned OpCmode, Imm;
5739 
5740   // SplatBitSize is set to the smallest size that splats the vector, so a
5741   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5742   // immediate instructions others than VMOV do not support the 8-bit encoding
5743   // of a zero vector, and the default encoding of zero is supposed to be the
5744   // 32-bit version.
5745   if (SplatBits == 0)
5746     SplatBitSize = 32;
5747 
5748   switch (SplatBitSize) {
5749   case 8:
5750     if (type != VMOVModImm)
5751       return SDValue();
5752     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5753     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5754     OpCmode = 0xe;
5755     Imm = SplatBits;
5756     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5757     break;
5758 
5759   case 16:
5760     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5761     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5762     if ((SplatBits & ~0xff) == 0) {
5763       // Value = 0x00nn: Op=x, Cmode=100x.
5764       OpCmode = 0x8;
5765       Imm = SplatBits;
5766       break;
5767     }
5768     if ((SplatBits & ~0xff00) == 0) {
5769       // Value = 0xnn00: Op=x, Cmode=101x.
5770       OpCmode = 0xa;
5771       Imm = SplatBits >> 8;
5772       break;
5773     }
5774     return SDValue();
5775 
5776   case 32:
5777     // NEON's 32-bit VMOV supports splat values where:
5778     // * only one byte is nonzero, or
5779     // * the least significant byte is 0xff and the second byte is nonzero, or
5780     // * the least significant 2 bytes are 0xff and the third is nonzero.
5781     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5782     if ((SplatBits & ~0xff) == 0) {
5783       // Value = 0x000000nn: Op=x, Cmode=000x.
5784       OpCmode = 0;
5785       Imm = SplatBits;
5786       break;
5787     }
5788     if ((SplatBits & ~0xff00) == 0) {
5789       // Value = 0x0000nn00: Op=x, Cmode=001x.
5790       OpCmode = 0x2;
5791       Imm = SplatBits >> 8;
5792       break;
5793     }
5794     if ((SplatBits & ~0xff0000) == 0) {
5795       // Value = 0x00nn0000: Op=x, Cmode=010x.
5796       OpCmode = 0x4;
5797       Imm = SplatBits >> 16;
5798       break;
5799     }
5800     if ((SplatBits & ~0xff000000) == 0) {
5801       // Value = 0xnn000000: Op=x, Cmode=011x.
5802       OpCmode = 0x6;
5803       Imm = SplatBits >> 24;
5804       break;
5805     }
5806 
5807     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5808     if (type == OtherModImm) return SDValue();
5809 
5810     if ((SplatBits & ~0xffff) == 0 &&
5811         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5812       // Value = 0x0000nnff: Op=x, Cmode=1100.
5813       OpCmode = 0xc;
5814       Imm = SplatBits >> 8;
5815       break;
5816     }
5817 
5818     if ((SplatBits & ~0xffffff) == 0 &&
5819         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5820       // Value = 0x00nnffff: Op=x, Cmode=1101.
5821       OpCmode = 0xd;
5822       Imm = SplatBits >> 16;
5823       break;
5824     }
5825 
5826     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5827     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5828     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5829     // and fall through here to test for a valid 64-bit splat.  But, then the
5830     // caller would also need to check and handle the change in size.
5831     return SDValue();
5832 
5833   case 64: {
5834     if (type != VMOVModImm)
5835       return SDValue();
5836     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5837     uint64_t BitMask = 0xff;
5838     uint64_t Val = 0;
5839     unsigned ImmMask = 1;
5840     Imm = 0;
5841     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5842       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5843         Val |= BitMask;
5844         Imm |= ImmMask;
5845       } else if ((SplatBits & BitMask) != 0) {
5846         return SDValue();
5847       }
5848       BitMask <<= 8;
5849       ImmMask <<= 1;
5850     }
5851 
5852     if (DAG.getDataLayout().isBigEndian())
5853       // swap higher and lower 32 bit word
5854       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5855 
5856     // Op=1, Cmode=1110.
5857     OpCmode = 0x1e;
5858     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5859     break;
5860   }
5861 
5862   default:
5863     llvm_unreachable("unexpected size for isNEONModifiedImm");
5864   }
5865 
5866   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5867   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5868 }
5869 
5870 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5871                                            const ARMSubtarget *ST) const {
5872   EVT VT = Op.getValueType();
5873   bool IsDouble = (VT == MVT::f64);
5874   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5875   const APFloat &FPVal = CFP->getValueAPF();
5876 
5877   // Prevent floating-point constants from using literal loads
5878   // when execute-only is enabled.
5879   if (ST->genExecuteOnly()) {
5880     // If we can represent the constant as an immediate, don't lower it
5881     if (isFPImmLegal(FPVal, VT))
5882       return Op;
5883     // Otherwise, construct as integer, and move to float register
5884     APInt INTVal = FPVal.bitcastToAPInt();
5885     SDLoc DL(CFP);
5886     switch (VT.getSimpleVT().SimpleTy) {
5887       default:
5888         llvm_unreachable("Unknown floating point type!");
5889         break;
5890       case MVT::f64: {
5891         SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5892         SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5893         if (!ST->isLittle())
5894           std::swap(Lo, Hi);
5895         return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5896       }
5897       case MVT::f32:
5898           return DAG.getNode(ARMISD::VMOVSR, DL, VT,
5899               DAG.getConstant(INTVal, DL, MVT::i32));
5900     }
5901   }
5902 
5903   if (!ST->hasVFP3())
5904     return SDValue();
5905 
5906   // Use the default (constant pool) lowering for double constants when we have
5907   // an SP-only FPU
5908   if (IsDouble && Subtarget->isFPOnlySP())
5909     return SDValue();
5910 
5911   // Try splatting with a VMOV.f32...
5912   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5913 
5914   if (ImmVal != -1) {
5915     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5916       // We have code in place to select a valid ConstantFP already, no need to
5917       // do any mangling.
5918       return Op;
5919     }
5920 
5921     // It's a float and we are trying to use NEON operations where
5922     // possible. Lower it to a splat followed by an extract.
5923     SDLoc DL(Op);
5924     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5925     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5926                                       NewVal);
5927     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5928                        DAG.getConstant(0, DL, MVT::i32));
5929   }
5930 
5931   // The rest of our options are NEON only, make sure that's allowed before
5932   // proceeding..
5933   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5934     return SDValue();
5935 
5936   EVT VMovVT;
5937   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5938 
5939   // It wouldn't really be worth bothering for doubles except for one very
5940   // important value, which does happen to match: 0.0. So make sure we don't do
5941   // anything stupid.
5942   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5943     return SDValue();
5944 
5945   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5946   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5947                                      VMovVT, false, VMOVModImm);
5948   if (NewVal != SDValue()) {
5949     SDLoc DL(Op);
5950     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5951                                       NewVal);
5952     if (IsDouble)
5953       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5954 
5955     // It's a float: cast and extract a vector element.
5956     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5957                                        VecConstant);
5958     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5959                        DAG.getConstant(0, DL, MVT::i32));
5960   }
5961 
5962   // Finally, try a VMVN.i32
5963   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5964                              false, VMVNModImm);
5965   if (NewVal != SDValue()) {
5966     SDLoc DL(Op);
5967     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5968 
5969     if (IsDouble)
5970       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5971 
5972     // It's a float: cast and extract a vector element.
5973     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5974                                        VecConstant);
5975     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5976                        DAG.getConstant(0, DL, MVT::i32));
5977   }
5978 
5979   return SDValue();
5980 }
5981 
5982 // check if an VEXT instruction can handle the shuffle mask when the
5983 // vector sources of the shuffle are the same.
5984 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5985   unsigned NumElts = VT.getVectorNumElements();
5986 
5987   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5988   if (M[0] < 0)
5989     return false;
5990 
5991   Imm = M[0];
5992 
5993   // If this is a VEXT shuffle, the immediate value is the index of the first
5994   // element.  The other shuffle indices must be the successive elements after
5995   // the first one.
5996   unsigned ExpectedElt = Imm;
5997   for (unsigned i = 1; i < NumElts; ++i) {
5998     // Increment the expected index.  If it wraps around, just follow it
5999     // back to index zero and keep going.
6000     ++ExpectedElt;
6001     if (ExpectedElt == NumElts)
6002       ExpectedElt = 0;
6003 
6004     if (M[i] < 0) continue; // ignore UNDEF indices
6005     if (ExpectedElt != static_cast<unsigned>(M[i]))
6006       return false;
6007   }
6008 
6009   return true;
6010 }
6011 
6012 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6013                        bool &ReverseVEXT, unsigned &Imm) {
6014   unsigned NumElts = VT.getVectorNumElements();
6015   ReverseVEXT = false;
6016 
6017   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6018   if (M[0] < 0)
6019     return false;
6020 
6021   Imm = M[0];
6022 
6023   // If this is a VEXT shuffle, the immediate value is the index of the first
6024   // element.  The other shuffle indices must be the successive elements after
6025   // the first one.
6026   unsigned ExpectedElt = Imm;
6027   for (unsigned i = 1; i < NumElts; ++i) {
6028     // Increment the expected index.  If it wraps around, it may still be
6029     // a VEXT but the source vectors must be swapped.
6030     ExpectedElt += 1;
6031     if (ExpectedElt == NumElts * 2) {
6032       ExpectedElt = 0;
6033       ReverseVEXT = true;
6034     }
6035 
6036     if (M[i] < 0) continue; // ignore UNDEF indices
6037     if (ExpectedElt != static_cast<unsigned>(M[i]))
6038       return false;
6039   }
6040 
6041   // Adjust the index value if the source operands will be swapped.
6042   if (ReverseVEXT)
6043     Imm -= NumElts;
6044 
6045   return true;
6046 }
6047 
6048 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6049 /// instruction with the specified blocksize.  (The order of the elements
6050 /// within each block of the vector is reversed.)
6051 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6052   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6053          "Only possible block sizes for VREV are: 16, 32, 64");
6054 
6055   unsigned EltSz = VT.getScalarSizeInBits();
6056   if (EltSz == 64)
6057     return false;
6058 
6059   unsigned NumElts = VT.getVectorNumElements();
6060   unsigned BlockElts = M[0] + 1;
6061   // If the first shuffle index is UNDEF, be optimistic.
6062   if (M[0] < 0)
6063     BlockElts = BlockSize / EltSz;
6064 
6065   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6066     return false;
6067 
6068   for (unsigned i = 0; i < NumElts; ++i) {
6069     if (M[i] < 0) continue; // ignore UNDEF indices
6070     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6071       return false;
6072   }
6073 
6074   return true;
6075 }
6076 
6077 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6078   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6079   // range, then 0 is placed into the resulting vector. So pretty much any mask
6080   // of 8 elements can work here.
6081   return VT == MVT::v8i8 && M.size() == 8;
6082 }
6083 
6084 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6085                                unsigned Index) {
6086   if (Mask.size() == Elements * 2)
6087     return Index / Elements;
6088   return Mask[Index] == 0 ? 0 : 1;
6089 }
6090 
6091 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6092 // checking that pairs of elements in the shuffle mask represent the same index
6093 // in each vector, incrementing the expected index by 2 at each step.
6094 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6095 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6096 //  v2={e,f,g,h}
6097 // WhichResult gives the offset for each element in the mask based on which
6098 // of the two results it belongs to.
6099 //
6100 // The transpose can be represented either as:
6101 // result1 = shufflevector v1, v2, result1_shuffle_mask
6102 // result2 = shufflevector v1, v2, result2_shuffle_mask
6103 // where v1/v2 and the shuffle masks have the same number of elements
6104 // (here WhichResult (see below) indicates which result is being checked)
6105 //
6106 // or as:
6107 // results = shufflevector v1, v2, shuffle_mask
6108 // where both results are returned in one vector and the shuffle mask has twice
6109 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6110 // want to check the low half and high half of the shuffle mask as if it were
6111 // the other case
6112 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6113   unsigned EltSz = VT.getScalarSizeInBits();
6114   if (EltSz == 64)
6115     return false;
6116 
6117   unsigned NumElts = VT.getVectorNumElements();
6118   if (M.size() != NumElts && M.size() != NumElts*2)
6119     return false;
6120 
6121   // If the mask is twice as long as the input vector then we need to check the
6122   // upper and lower parts of the mask with a matching value for WhichResult
6123   // FIXME: A mask with only even values will be rejected in case the first
6124   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6125   // M[0] is used to determine WhichResult
6126   for (unsigned i = 0; i < M.size(); i += NumElts) {
6127     WhichResult = SelectPairHalf(NumElts, M, i);
6128     for (unsigned j = 0; j < NumElts; j += 2) {
6129       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6130           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6131         return false;
6132     }
6133   }
6134 
6135   if (M.size() == NumElts*2)
6136     WhichResult = 0;
6137 
6138   return true;
6139 }
6140 
6141 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6142 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6143 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6144 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6145   unsigned EltSz = VT.getScalarSizeInBits();
6146   if (EltSz == 64)
6147     return false;
6148 
6149   unsigned NumElts = VT.getVectorNumElements();
6150   if (M.size() != NumElts && M.size() != NumElts*2)
6151     return false;
6152 
6153   for (unsigned i = 0; i < M.size(); i += NumElts) {
6154     WhichResult = SelectPairHalf(NumElts, M, i);
6155     for (unsigned j = 0; j < NumElts; j += 2) {
6156       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6157           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6158         return false;
6159     }
6160   }
6161 
6162   if (M.size() == NumElts*2)
6163     WhichResult = 0;
6164 
6165   return true;
6166 }
6167 
6168 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6169 // that the mask elements are either all even and in steps of size 2 or all odd
6170 // and in steps of size 2.
6171 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6172 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6173 //  v2={e,f,g,h}
6174 // Requires similar checks to that of isVTRNMask with
6175 // respect the how results are returned.
6176 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6177   unsigned EltSz = VT.getScalarSizeInBits();
6178   if (EltSz == 64)
6179     return false;
6180 
6181   unsigned NumElts = VT.getVectorNumElements();
6182   if (M.size() != NumElts && M.size() != NumElts*2)
6183     return false;
6184 
6185   for (unsigned i = 0; i < M.size(); i += NumElts) {
6186     WhichResult = SelectPairHalf(NumElts, M, i);
6187     for (unsigned j = 0; j < NumElts; ++j) {
6188       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6189         return false;
6190     }
6191   }
6192 
6193   if (M.size() == NumElts*2)
6194     WhichResult = 0;
6195 
6196   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6197   if (VT.is64BitVector() && EltSz == 32)
6198     return false;
6199 
6200   return true;
6201 }
6202 
6203 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6204 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6205 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6206 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6207   unsigned EltSz = VT.getScalarSizeInBits();
6208   if (EltSz == 64)
6209     return false;
6210 
6211   unsigned NumElts = VT.getVectorNumElements();
6212   if (M.size() != NumElts && M.size() != NumElts*2)
6213     return false;
6214 
6215   unsigned Half = NumElts / 2;
6216   for (unsigned i = 0; i < M.size(); i += NumElts) {
6217     WhichResult = SelectPairHalf(NumElts, M, i);
6218     for (unsigned j = 0; j < NumElts; j += Half) {
6219       unsigned Idx = WhichResult;
6220       for (unsigned k = 0; k < Half; ++k) {
6221         int MIdx = M[i + j + k];
6222         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6223           return false;
6224         Idx += 2;
6225       }
6226     }
6227   }
6228 
6229   if (M.size() == NumElts*2)
6230     WhichResult = 0;
6231 
6232   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6233   if (VT.is64BitVector() && EltSz == 32)
6234     return false;
6235 
6236   return true;
6237 }
6238 
6239 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6240 // that pairs of elements of the shufflemask represent the same index in each
6241 // vector incrementing sequentially through the vectors.
6242 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6243 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6244 //  v2={e,f,g,h}
6245 // Requires similar checks to that of isVTRNMask with respect the how results
6246 // are returned.
6247 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6248   unsigned EltSz = VT.getScalarSizeInBits();
6249   if (EltSz == 64)
6250     return false;
6251 
6252   unsigned NumElts = VT.getVectorNumElements();
6253   if (M.size() != NumElts && M.size() != NumElts*2)
6254     return false;
6255 
6256   for (unsigned i = 0; i < M.size(); i += NumElts) {
6257     WhichResult = SelectPairHalf(NumElts, M, i);
6258     unsigned Idx = WhichResult * NumElts / 2;
6259     for (unsigned j = 0; j < NumElts; j += 2) {
6260       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6261           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6262         return false;
6263       Idx += 1;
6264     }
6265   }
6266 
6267   if (M.size() == NumElts*2)
6268     WhichResult = 0;
6269 
6270   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6271   if (VT.is64BitVector() && EltSz == 32)
6272     return false;
6273 
6274   return true;
6275 }
6276 
6277 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6278 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6279 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6280 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6281   unsigned EltSz = VT.getScalarSizeInBits();
6282   if (EltSz == 64)
6283     return false;
6284 
6285   unsigned NumElts = VT.getVectorNumElements();
6286   if (M.size() != NumElts && M.size() != NumElts*2)
6287     return false;
6288 
6289   for (unsigned i = 0; i < M.size(); i += NumElts) {
6290     WhichResult = SelectPairHalf(NumElts, M, i);
6291     unsigned Idx = WhichResult * NumElts / 2;
6292     for (unsigned j = 0; j < NumElts; j += 2) {
6293       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6294           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6295         return false;
6296       Idx += 1;
6297     }
6298   }
6299 
6300   if (M.size() == NumElts*2)
6301     WhichResult = 0;
6302 
6303   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6304   if (VT.is64BitVector() && EltSz == 32)
6305     return false;
6306 
6307   return true;
6308 }
6309 
6310 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6311 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6312 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6313                                            unsigned &WhichResult,
6314                                            bool &isV_UNDEF) {
6315   isV_UNDEF = false;
6316   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6317     return ARMISD::VTRN;
6318   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6319     return ARMISD::VUZP;
6320   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6321     return ARMISD::VZIP;
6322 
6323   isV_UNDEF = true;
6324   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6325     return ARMISD::VTRN;
6326   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6327     return ARMISD::VUZP;
6328   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6329     return ARMISD::VZIP;
6330 
6331   return 0;
6332 }
6333 
6334 /// \return true if this is a reverse operation on an vector.
6335 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6336   unsigned NumElts = VT.getVectorNumElements();
6337   // Make sure the mask has the right size.
6338   if (NumElts != M.size())
6339       return false;
6340 
6341   // Look for <15, ..., 3, -1, 1, 0>.
6342   for (unsigned i = 0; i != NumElts; ++i)
6343     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6344       return false;
6345 
6346   return true;
6347 }
6348 
6349 // If N is an integer constant that can be moved into a register in one
6350 // instruction, return an SDValue of such a constant (will become a MOV
6351 // instruction).  Otherwise return null.
6352 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6353                                      const ARMSubtarget *ST, const SDLoc &dl) {
6354   uint64_t Val;
6355   if (!isa<ConstantSDNode>(N))
6356     return SDValue();
6357   Val = cast<ConstantSDNode>(N)->getZExtValue();
6358 
6359   if (ST->isThumb1Only()) {
6360     if (Val <= 255 || ~Val <= 255)
6361       return DAG.getConstant(Val, dl, MVT::i32);
6362   } else {
6363     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6364       return DAG.getConstant(Val, dl, MVT::i32);
6365   }
6366   return SDValue();
6367 }
6368 
6369 // If this is a case we can't handle, return null and let the default
6370 // expansion code take care of it.
6371 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6372                                              const ARMSubtarget *ST) const {
6373   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6374   SDLoc dl(Op);
6375   EVT VT = Op.getValueType();
6376 
6377   APInt SplatBits, SplatUndef;
6378   unsigned SplatBitSize;
6379   bool HasAnyUndefs;
6380   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6381     if (SplatUndef.isAllOnesValue())
6382       return DAG.getUNDEF(VT);
6383 
6384     if (SplatBitSize <= 64) {
6385       // Check if an immediate VMOV works.
6386       EVT VmovVT;
6387       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6388                                       SplatUndef.getZExtValue(), SplatBitSize,
6389                                       DAG, dl, VmovVT, VT.is128BitVector(),
6390                                       VMOVModImm);
6391       if (Val.getNode()) {
6392         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6393         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6394       }
6395 
6396       // Try an immediate VMVN.
6397       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6398       Val = isNEONModifiedImm(NegatedImm,
6399                                       SplatUndef.getZExtValue(), SplatBitSize,
6400                                       DAG, dl, VmovVT, VT.is128BitVector(),
6401                                       VMVNModImm);
6402       if (Val.getNode()) {
6403         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6404         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6405       }
6406 
6407       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6408       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6409         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6410         if (ImmVal != -1) {
6411           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6412           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6413         }
6414       }
6415     }
6416   }
6417 
6418   // Scan through the operands to see if only one value is used.
6419   //
6420   // As an optimisation, even if more than one value is used it may be more
6421   // profitable to splat with one value then change some lanes.
6422   //
6423   // Heuristically we decide to do this if the vector has a "dominant" value,
6424   // defined as splatted to more than half of the lanes.
6425   unsigned NumElts = VT.getVectorNumElements();
6426   bool isOnlyLowElement = true;
6427   bool usesOnlyOneValue = true;
6428   bool hasDominantValue = false;
6429   bool isConstant = true;
6430 
6431   // Map of the number of times a particular SDValue appears in the
6432   // element list.
6433   DenseMap<SDValue, unsigned> ValueCounts;
6434   SDValue Value;
6435   for (unsigned i = 0; i < NumElts; ++i) {
6436     SDValue V = Op.getOperand(i);
6437     if (V.isUndef())
6438       continue;
6439     if (i > 0)
6440       isOnlyLowElement = false;
6441     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6442       isConstant = false;
6443 
6444     ValueCounts.insert(std::make_pair(V, 0));
6445     unsigned &Count = ValueCounts[V];
6446 
6447     // Is this value dominant? (takes up more than half of the lanes)
6448     if (++Count > (NumElts / 2)) {
6449       hasDominantValue = true;
6450       Value = V;
6451     }
6452   }
6453   if (ValueCounts.size() != 1)
6454     usesOnlyOneValue = false;
6455   if (!Value.getNode() && !ValueCounts.empty())
6456     Value = ValueCounts.begin()->first;
6457 
6458   if (ValueCounts.empty())
6459     return DAG.getUNDEF(VT);
6460 
6461   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6462   // Keep going if we are hitting this case.
6463   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6464     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6465 
6466   unsigned EltSize = VT.getScalarSizeInBits();
6467 
6468   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6469   // i32 and try again.
6470   if (hasDominantValue && EltSize <= 32) {
6471     if (!isConstant) {
6472       SDValue N;
6473 
6474       // If we are VDUPing a value that comes directly from a vector, that will
6475       // cause an unnecessary move to and from a GPR, where instead we could
6476       // just use VDUPLANE. We can only do this if the lane being extracted
6477       // is at a constant index, as the VDUP from lane instructions only have
6478       // constant-index forms.
6479       ConstantSDNode *constIndex;
6480       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6481           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6482         // We need to create a new undef vector to use for the VDUPLANE if the
6483         // size of the vector from which we get the value is different than the
6484         // size of the vector that we need to create. We will insert the element
6485         // such that the register coalescer will remove unnecessary copies.
6486         if (VT != Value->getOperand(0).getValueType()) {
6487           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6488                              VT.getVectorNumElements();
6489           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6490                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6491                         Value, DAG.getConstant(index, dl, MVT::i32)),
6492                            DAG.getConstant(index, dl, MVT::i32));
6493         } else
6494           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6495                         Value->getOperand(0), Value->getOperand(1));
6496       } else
6497         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6498 
6499       if (!usesOnlyOneValue) {
6500         // The dominant value was splatted as 'N', but we now have to insert
6501         // all differing elements.
6502         for (unsigned I = 0; I < NumElts; ++I) {
6503           if (Op.getOperand(I) == Value)
6504             continue;
6505           SmallVector<SDValue, 3> Ops;
6506           Ops.push_back(N);
6507           Ops.push_back(Op.getOperand(I));
6508           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6509           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6510         }
6511       }
6512       return N;
6513     }
6514     if (VT.getVectorElementType().isFloatingPoint()) {
6515       SmallVector<SDValue, 8> Ops;
6516       for (unsigned i = 0; i < NumElts; ++i)
6517         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6518                                   Op.getOperand(i)));
6519       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6520       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6521       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6522       if (Val.getNode())
6523         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6524     }
6525     if (usesOnlyOneValue) {
6526       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6527       if (isConstant && Val.getNode())
6528         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6529     }
6530   }
6531 
6532   // If all elements are constants and the case above didn't get hit, fall back
6533   // to the default expansion, which will generate a load from the constant
6534   // pool.
6535   if (isConstant)
6536     return SDValue();
6537 
6538   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6539   if (NumElts >= 4) {
6540     SDValue shuffle = ReconstructShuffle(Op, DAG);
6541     if (shuffle != SDValue())
6542       return shuffle;
6543   }
6544 
6545   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6546     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6547     // into two 64-bit vectors; we might discover a better way to lower it.
6548     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6549     EVT ExtVT = VT.getVectorElementType();
6550     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6551     SDValue Lower =
6552         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6553     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6554       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6555     SDValue Upper = DAG.getBuildVector(
6556         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6557     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6558       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6559     if (Lower && Upper)
6560       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6561   }
6562 
6563   // Vectors with 32- or 64-bit elements can be built by directly assigning
6564   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6565   // will be legalized.
6566   if (EltSize >= 32) {
6567     // Do the expansion with floating-point types, since that is what the VFP
6568     // registers are defined to use, and since i64 is not legal.
6569     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6570     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6571     SmallVector<SDValue, 8> Ops;
6572     for (unsigned i = 0; i < NumElts; ++i)
6573       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6574     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6575     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6576   }
6577 
6578   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6579   // know the default expansion would otherwise fall back on something even
6580   // worse. For a vector with one or two non-undef values, that's
6581   // scalar_to_vector for the elements followed by a shuffle (provided the
6582   // shuffle is valid for the target) and materialization element by element
6583   // on the stack followed by a load for everything else.
6584   if (!isConstant && !usesOnlyOneValue) {
6585     SDValue Vec = DAG.getUNDEF(VT);
6586     for (unsigned i = 0 ; i < NumElts; ++i) {
6587       SDValue V = Op.getOperand(i);
6588       if (V.isUndef())
6589         continue;
6590       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6591       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6592     }
6593     return Vec;
6594   }
6595 
6596   return SDValue();
6597 }
6598 
6599 // Gather data to see if the operation can be modelled as a
6600 // shuffle in combination with VEXTs.
6601 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6602                                               SelectionDAG &DAG) const {
6603   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6604   SDLoc dl(Op);
6605   EVT VT = Op.getValueType();
6606   unsigned NumElts = VT.getVectorNumElements();
6607 
6608   struct ShuffleSourceInfo {
6609     SDValue Vec;
6610     unsigned MinElt = std::numeric_limits<unsigned>::max();
6611     unsigned MaxElt = 0;
6612 
6613     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6614     // be compatible with the shuffle we intend to construct. As a result
6615     // ShuffleVec will be some sliding window into the original Vec.
6616     SDValue ShuffleVec;
6617 
6618     // Code should guarantee that element i in Vec starts at element "WindowBase
6619     // + i * WindowScale in ShuffleVec".
6620     int WindowBase = 0;
6621     int WindowScale = 1;
6622 
6623     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6624 
6625     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6626   };
6627 
6628   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6629   // node.
6630   SmallVector<ShuffleSourceInfo, 2> Sources;
6631   for (unsigned i = 0; i < NumElts; ++i) {
6632     SDValue V = Op.getOperand(i);
6633     if (V.isUndef())
6634       continue;
6635     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6636       // A shuffle can only come from building a vector from various
6637       // elements of other vectors.
6638       return SDValue();
6639     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6640       // Furthermore, shuffles require a constant mask, whereas extractelts
6641       // accept variable indices.
6642       return SDValue();
6643     }
6644 
6645     // Add this element source to the list if it's not already there.
6646     SDValue SourceVec = V.getOperand(0);
6647     auto Source = llvm::find(Sources, SourceVec);
6648     if (Source == Sources.end())
6649       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6650 
6651     // Update the minimum and maximum lane number seen.
6652     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6653     Source->MinElt = std::min(Source->MinElt, EltNo);
6654     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6655   }
6656 
6657   // Currently only do something sane when at most two source vectors
6658   // are involved.
6659   if (Sources.size() > 2)
6660     return SDValue();
6661 
6662   // Find out the smallest element size among result and two sources, and use
6663   // it as element size to build the shuffle_vector.
6664   EVT SmallestEltTy = VT.getVectorElementType();
6665   for (auto &Source : Sources) {
6666     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6667     if (SrcEltTy.bitsLT(SmallestEltTy))
6668       SmallestEltTy = SrcEltTy;
6669   }
6670   unsigned ResMultiplier =
6671       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6672   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6673   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6674 
6675   // If the source vector is too wide or too narrow, we may nevertheless be able
6676   // to construct a compatible shuffle either by concatenating it with UNDEF or
6677   // extracting a suitable range of elements.
6678   for (auto &Src : Sources) {
6679     EVT SrcVT = Src.ShuffleVec.getValueType();
6680 
6681     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6682       continue;
6683 
6684     // This stage of the search produces a source with the same element type as
6685     // the original, but with a total width matching the BUILD_VECTOR output.
6686     EVT EltVT = SrcVT.getVectorElementType();
6687     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6688     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6689 
6690     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6691       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6692         return SDValue();
6693       // We can pad out the smaller vector for free, so if it's part of a
6694       // shuffle...
6695       Src.ShuffleVec =
6696           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6697                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6698       continue;
6699     }
6700 
6701     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6702       return SDValue();
6703 
6704     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6705       // Span too large for a VEXT to cope
6706       return SDValue();
6707     }
6708 
6709     if (Src.MinElt >= NumSrcElts) {
6710       // The extraction can just take the second half
6711       Src.ShuffleVec =
6712           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6713                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6714       Src.WindowBase = -NumSrcElts;
6715     } else if (Src.MaxElt < NumSrcElts) {
6716       // The extraction can just take the first half
6717       Src.ShuffleVec =
6718           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6719                       DAG.getConstant(0, dl, MVT::i32));
6720     } else {
6721       // An actual VEXT is needed
6722       SDValue VEXTSrc1 =
6723           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6724                       DAG.getConstant(0, dl, MVT::i32));
6725       SDValue VEXTSrc2 =
6726           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6727                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6728 
6729       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6730                                    VEXTSrc2,
6731                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6732       Src.WindowBase = -Src.MinElt;
6733     }
6734   }
6735 
6736   // Another possible incompatibility occurs from the vector element types. We
6737   // can fix this by bitcasting the source vectors to the same type we intend
6738   // for the shuffle.
6739   for (auto &Src : Sources) {
6740     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6741     if (SrcEltTy == SmallestEltTy)
6742       continue;
6743     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6744     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6745     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6746     Src.WindowBase *= Src.WindowScale;
6747   }
6748 
6749   // Final sanity check before we try to actually produce a shuffle.
6750   LLVM_DEBUG(for (auto Src
6751                   : Sources)
6752                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6753 
6754   // The stars all align, our next step is to produce the mask for the shuffle.
6755   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6756   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6757   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6758     SDValue Entry = Op.getOperand(i);
6759     if (Entry.isUndef())
6760       continue;
6761 
6762     auto Src = llvm::find(Sources, Entry.getOperand(0));
6763     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6764 
6765     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6766     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6767     // segment.
6768     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6769     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6770                                VT.getScalarSizeInBits());
6771     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6772 
6773     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6774     // starting at the appropriate offset.
6775     int *LaneMask = &Mask[i * ResMultiplier];
6776 
6777     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6778     ExtractBase += NumElts * (Src - Sources.begin());
6779     for (int j = 0; j < LanesDefined; ++j)
6780       LaneMask[j] = ExtractBase + j;
6781   }
6782 
6783   // Final check before we try to produce nonsense...
6784   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6785     return SDValue();
6786 
6787   // We can't handle more than two sources. This should have already
6788   // been checked before this point.
6789   assert(Sources.size() <= 2 && "Too many sources!");
6790 
6791   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6792   for (unsigned i = 0; i < Sources.size(); ++i)
6793     ShuffleOps[i] = Sources[i].ShuffleVec;
6794 
6795   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6796                                          ShuffleOps[1], Mask);
6797   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6798 }
6799 
6800 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6801 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6802 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6803 /// are assumed to be legal.
6804 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
6805   if (VT.getVectorNumElements() == 4 &&
6806       (VT.is128BitVector() || VT.is64BitVector())) {
6807     unsigned PFIndexes[4];
6808     for (unsigned i = 0; i != 4; ++i) {
6809       if (M[i] < 0)
6810         PFIndexes[i] = 8;
6811       else
6812         PFIndexes[i] = M[i];
6813     }
6814 
6815     // Compute the index in the perfect shuffle table.
6816     unsigned PFTableIndex =
6817       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6818     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6819     unsigned Cost = (PFEntry >> 30);
6820 
6821     if (Cost <= 4)
6822       return true;
6823   }
6824 
6825   bool ReverseVEXT, isV_UNDEF;
6826   unsigned Imm, WhichResult;
6827 
6828   unsigned EltSize = VT.getScalarSizeInBits();
6829   return (EltSize >= 32 ||
6830           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6831           isVREVMask(M, VT, 64) ||
6832           isVREVMask(M, VT, 32) ||
6833           isVREVMask(M, VT, 16) ||
6834           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6835           isVTBLMask(M, VT) ||
6836           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6837           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6838 }
6839 
6840 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6841 /// the specified operations to build the shuffle.
6842 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6843                                       SDValue RHS, SelectionDAG &DAG,
6844                                       const SDLoc &dl) {
6845   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6846   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6847   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6848 
6849   enum {
6850     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6851     OP_VREV,
6852     OP_VDUP0,
6853     OP_VDUP1,
6854     OP_VDUP2,
6855     OP_VDUP3,
6856     OP_VEXT1,
6857     OP_VEXT2,
6858     OP_VEXT3,
6859     OP_VUZPL, // VUZP, left result
6860     OP_VUZPR, // VUZP, right result
6861     OP_VZIPL, // VZIP, left result
6862     OP_VZIPR, // VZIP, right result
6863     OP_VTRNL, // VTRN, left result
6864     OP_VTRNR  // VTRN, right result
6865   };
6866 
6867   if (OpNum == OP_COPY) {
6868     if (LHSID == (1*9+2)*9+3) return LHS;
6869     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6870     return RHS;
6871   }
6872 
6873   SDValue OpLHS, OpRHS;
6874   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6875   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6876   EVT VT = OpLHS.getValueType();
6877 
6878   switch (OpNum) {
6879   default: llvm_unreachable("Unknown shuffle opcode!");
6880   case OP_VREV:
6881     // VREV divides the vector in half and swaps within the half.
6882     if (VT.getVectorElementType() == MVT::i32 ||
6883         VT.getVectorElementType() == MVT::f32)
6884       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6885     // vrev <4 x i16> -> VREV32
6886     if (VT.getVectorElementType() == MVT::i16)
6887       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6888     // vrev <4 x i8> -> VREV16
6889     assert(VT.getVectorElementType() == MVT::i8);
6890     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6891   case OP_VDUP0:
6892   case OP_VDUP1:
6893   case OP_VDUP2:
6894   case OP_VDUP3:
6895     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6896                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6897   case OP_VEXT1:
6898   case OP_VEXT2:
6899   case OP_VEXT3:
6900     return DAG.getNode(ARMISD::VEXT, dl, VT,
6901                        OpLHS, OpRHS,
6902                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6903   case OP_VUZPL:
6904   case OP_VUZPR:
6905     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6906                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6907   case OP_VZIPL:
6908   case OP_VZIPR:
6909     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6910                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6911   case OP_VTRNL:
6912   case OP_VTRNR:
6913     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6914                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6915   }
6916 }
6917 
6918 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6919                                        ArrayRef<int> ShuffleMask,
6920                                        SelectionDAG &DAG) {
6921   // Check to see if we can use the VTBL instruction.
6922   SDValue V1 = Op.getOperand(0);
6923   SDValue V2 = Op.getOperand(1);
6924   SDLoc DL(Op);
6925 
6926   SmallVector<SDValue, 8> VTBLMask;
6927   for (ArrayRef<int>::iterator
6928          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6929     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6930 
6931   if (V2.getNode()->isUndef())
6932     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6933                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6934 
6935   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6936                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6937 }
6938 
6939 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6940                                                       SelectionDAG &DAG) {
6941   SDLoc DL(Op);
6942   SDValue OpLHS = Op.getOperand(0);
6943   EVT VT = OpLHS.getValueType();
6944 
6945   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6946          "Expect an v8i16/v16i8 type");
6947   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6948   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6949   // extract the first 8 bytes into the top double word and the last 8 bytes
6950   // into the bottom double word. The v8i16 case is similar.
6951   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6952   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6953                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6954 }
6955 
6956 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6957   SDValue V1 = Op.getOperand(0);
6958   SDValue V2 = Op.getOperand(1);
6959   SDLoc dl(Op);
6960   EVT VT = Op.getValueType();
6961   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6962 
6963   // Convert shuffles that are directly supported on NEON to target-specific
6964   // DAG nodes, instead of keeping them as shuffles and matching them again
6965   // during code selection.  This is more efficient and avoids the possibility
6966   // of inconsistencies between legalization and selection.
6967   // FIXME: floating-point vectors should be canonicalized to integer vectors
6968   // of the same time so that they get CSEd properly.
6969   ArrayRef<int> ShuffleMask = SVN->getMask();
6970 
6971   unsigned EltSize = VT.getScalarSizeInBits();
6972   if (EltSize <= 32) {
6973     if (SVN->isSplat()) {
6974       int Lane = SVN->getSplatIndex();
6975       // If this is undef splat, generate it via "just" vdup, if possible.
6976       if (Lane == -1) Lane = 0;
6977 
6978       // Test if V1 is a SCALAR_TO_VECTOR.
6979       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6980         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6981       }
6982       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6983       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6984       // reaches it).
6985       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6986           !isa<ConstantSDNode>(V1.getOperand(0))) {
6987         bool IsScalarToVector = true;
6988         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6989           if (!V1.getOperand(i).isUndef()) {
6990             IsScalarToVector = false;
6991             break;
6992           }
6993         if (IsScalarToVector)
6994           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6995       }
6996       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6997                          DAG.getConstant(Lane, dl, MVT::i32));
6998     }
6999 
7000     bool ReverseVEXT;
7001     unsigned Imm;
7002     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7003       if (ReverseVEXT)
7004         std::swap(V1, V2);
7005       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7006                          DAG.getConstant(Imm, dl, MVT::i32));
7007     }
7008 
7009     if (isVREVMask(ShuffleMask, VT, 64))
7010       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7011     if (isVREVMask(ShuffleMask, VT, 32))
7012       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7013     if (isVREVMask(ShuffleMask, VT, 16))
7014       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7015 
7016     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7017       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7018                          DAG.getConstant(Imm, dl, MVT::i32));
7019     }
7020 
7021     // Check for Neon shuffles that modify both input vectors in place.
7022     // If both results are used, i.e., if there are two shuffles with the same
7023     // source operands and with masks corresponding to both results of one of
7024     // these operations, DAG memoization will ensure that a single node is
7025     // used for both shuffles.
7026     unsigned WhichResult;
7027     bool isV_UNDEF;
7028     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7029             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7030       if (isV_UNDEF)
7031         V2 = V1;
7032       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7033           .getValue(WhichResult);
7034     }
7035 
7036     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7037     // shuffles that produce a result larger than their operands with:
7038     //   shuffle(concat(v1, undef), concat(v2, undef))
7039     // ->
7040     //   shuffle(concat(v1, v2), undef)
7041     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7042     //
7043     // This is useful in the general case, but there are special cases where
7044     // native shuffles produce larger results: the two-result ops.
7045     //
7046     // Look through the concat when lowering them:
7047     //   shuffle(concat(v1, v2), undef)
7048     // ->
7049     //   concat(VZIP(v1, v2):0, :1)
7050     //
7051     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7052       SDValue SubV1 = V1->getOperand(0);
7053       SDValue SubV2 = V1->getOperand(1);
7054       EVT SubVT = SubV1.getValueType();
7055 
7056       // We expect these to have been canonicalized to -1.
7057       assert(llvm::all_of(ShuffleMask, [&](int i) {
7058         return i < (int)VT.getVectorNumElements();
7059       }) && "Unexpected shuffle index into UNDEF operand!");
7060 
7061       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7062               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7063         if (isV_UNDEF)
7064           SubV2 = SubV1;
7065         assert((WhichResult == 0) &&
7066                "In-place shuffle of concat can only have one result!");
7067         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7068                                   SubV1, SubV2);
7069         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7070                            Res.getValue(1));
7071       }
7072     }
7073   }
7074 
7075   // If the shuffle is not directly supported and it has 4 elements, use
7076   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7077   unsigned NumElts = VT.getVectorNumElements();
7078   if (NumElts == 4) {
7079     unsigned PFIndexes[4];
7080     for (unsigned i = 0; i != 4; ++i) {
7081       if (ShuffleMask[i] < 0)
7082         PFIndexes[i] = 8;
7083       else
7084         PFIndexes[i] = ShuffleMask[i];
7085     }
7086 
7087     // Compute the index in the perfect shuffle table.
7088     unsigned PFTableIndex =
7089       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7090     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7091     unsigned Cost = (PFEntry >> 30);
7092 
7093     if (Cost <= 4)
7094       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7095   }
7096 
7097   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7098   if (EltSize >= 32) {
7099     // Do the expansion with floating-point types, since that is what the VFP
7100     // registers are defined to use, and since i64 is not legal.
7101     EVT EltVT = EVT::getFloatingPointVT(EltSize);
7102     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7103     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7104     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7105     SmallVector<SDValue, 8> Ops;
7106     for (unsigned i = 0; i < NumElts; ++i) {
7107       if (ShuffleMask[i] < 0)
7108         Ops.push_back(DAG.getUNDEF(EltVT));
7109       else
7110         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7111                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
7112                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7113                                                   dl, MVT::i32)));
7114     }
7115     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7116     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7117   }
7118 
7119   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7120     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7121 
7122   if (VT == MVT::v8i8)
7123     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7124       return NewOp;
7125 
7126   return SDValue();
7127 }
7128 
7129 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7130   // INSERT_VECTOR_ELT is legal only for immediate indexes.
7131   SDValue Lane = Op.getOperand(2);
7132   if (!isa<ConstantSDNode>(Lane))
7133     return SDValue();
7134 
7135   return Op;
7136 }
7137 
7138 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7139   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7140   SDValue Lane = Op.getOperand(1);
7141   if (!isa<ConstantSDNode>(Lane))
7142     return SDValue();
7143 
7144   SDValue Vec = Op.getOperand(0);
7145   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7146     SDLoc dl(Op);
7147     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7148   }
7149 
7150   return Op;
7151 }
7152 
7153 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7154   // The only time a CONCAT_VECTORS operation can have legal types is when
7155   // two 64-bit vectors are concatenated to a 128-bit vector.
7156   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
7157          "unexpected CONCAT_VECTORS");
7158   SDLoc dl(Op);
7159   SDValue Val = DAG.getUNDEF(MVT::v2f64);
7160   SDValue Op0 = Op.getOperand(0);
7161   SDValue Op1 = Op.getOperand(1);
7162   if (!Op0.isUndef())
7163     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7164                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
7165                       DAG.getIntPtrConstant(0, dl));
7166   if (!Op1.isUndef())
7167     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7168                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
7169                       DAG.getIntPtrConstant(1, dl));
7170   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
7171 }
7172 
7173 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
7174 /// element has been zero/sign-extended, depending on the isSigned parameter,
7175 /// from an integer type half its size.
7176 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
7177                                    bool isSigned) {
7178   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
7179   EVT VT = N->getValueType(0);
7180   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
7181     SDNode *BVN = N->getOperand(0).getNode();
7182     if (BVN->getValueType(0) != MVT::v4i32 ||
7183         BVN->getOpcode() != ISD::BUILD_VECTOR)
7184       return false;
7185     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7186     unsigned HiElt = 1 - LoElt;
7187     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
7188     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
7189     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
7190     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
7191     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
7192       return false;
7193     if (isSigned) {
7194       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
7195           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
7196         return true;
7197     } else {
7198       if (Hi0->isNullValue() && Hi1->isNullValue())
7199         return true;
7200     }
7201     return false;
7202   }
7203 
7204   if (N->getOpcode() != ISD::BUILD_VECTOR)
7205     return false;
7206 
7207   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
7208     SDNode *Elt = N->getOperand(i).getNode();
7209     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
7210       unsigned EltSize = VT.getScalarSizeInBits();
7211       unsigned HalfSize = EltSize / 2;
7212       if (isSigned) {
7213         if (!isIntN(HalfSize, C->getSExtValue()))
7214           return false;
7215       } else {
7216         if (!isUIntN(HalfSize, C->getZExtValue()))
7217           return false;
7218       }
7219       continue;
7220     }
7221     return false;
7222   }
7223 
7224   return true;
7225 }
7226 
7227 /// isSignExtended - Check if a node is a vector value that is sign-extended
7228 /// or a constant BUILD_VECTOR with sign-extended elements.
7229 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7230   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7231     return true;
7232   if (isExtendedBUILD_VECTOR(N, DAG, true))
7233     return true;
7234   return false;
7235 }
7236 
7237 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7238 /// or a constant BUILD_VECTOR with zero-extended elements.
7239 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7240   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7241     return true;
7242   if (isExtendedBUILD_VECTOR(N, DAG, false))
7243     return true;
7244   return false;
7245 }
7246 
7247 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7248   if (OrigVT.getSizeInBits() >= 64)
7249     return OrigVT;
7250 
7251   assert(OrigVT.isSimple() && "Expecting a simple value type");
7252 
7253   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7254   switch (OrigSimpleTy) {
7255   default: llvm_unreachable("Unexpected Vector Type");
7256   case MVT::v2i8:
7257   case MVT::v2i16:
7258      return MVT::v2i32;
7259   case MVT::v4i8:
7260     return  MVT::v4i16;
7261   }
7262 }
7263 
7264 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7265 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7266 /// We insert the required extension here to get the vector to fill a D register.
7267 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7268                                             const EVT &OrigTy,
7269                                             const EVT &ExtTy,
7270                                             unsigned ExtOpcode) {
7271   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7272   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7273   // 64-bits we need to insert a new extension so that it will be 64-bits.
7274   assert(ExtTy.is128BitVector() && "Unexpected extension size");
7275   if (OrigTy.getSizeInBits() >= 64)
7276     return N;
7277 
7278   // Must extend size to at least 64 bits to be used as an operand for VMULL.
7279   EVT NewVT = getExtensionTo64Bits(OrigTy);
7280 
7281   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7282 }
7283 
7284 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7285 /// does not do any sign/zero extension. If the original vector is less
7286 /// than 64 bits, an appropriate extension will be added after the load to
7287 /// reach a total size of 64 bits. We have to add the extension separately
7288 /// because ARM does not have a sign/zero extending load for vectors.
7289 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7290   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7291 
7292   // The load already has the right type.
7293   if (ExtendedTy == LD->getMemoryVT())
7294     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7295                        LD->getBasePtr(), LD->getPointerInfo(),
7296                        LD->getAlignment(), LD->getMemOperand()->getFlags());
7297 
7298   // We need to create a zextload/sextload. We cannot just create a load
7299   // followed by a zext/zext node because LowerMUL is also run during normal
7300   // operation legalization where we can't create illegal types.
7301   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7302                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7303                         LD->getMemoryVT(), LD->getAlignment(),
7304                         LD->getMemOperand()->getFlags());
7305 }
7306 
7307 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7308 /// extending load, or BUILD_VECTOR with extended elements, return the
7309 /// unextended value. The unextended vector should be 64 bits so that it can
7310 /// be used as an operand to a VMULL instruction. If the original vector size
7311 /// before extension is less than 64 bits we add a an extension to resize
7312 /// the vector to 64 bits.
7313 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7314   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7315     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7316                                         N->getOperand(0)->getValueType(0),
7317                                         N->getValueType(0),
7318                                         N->getOpcode());
7319 
7320   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7321     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7322            "Expected extending load");
7323 
7324     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7325     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7326     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7327     SDValue extLoad =
7328         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7329     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7330 
7331     return newLoad;
7332   }
7333 
7334   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7335   // have been legalized as a BITCAST from v4i32.
7336   if (N->getOpcode() == ISD::BITCAST) {
7337     SDNode *BVN = N->getOperand(0).getNode();
7338     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7339            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7340     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7341     return DAG.getBuildVector(
7342         MVT::v2i32, SDLoc(N),
7343         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7344   }
7345   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7346   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7347   EVT VT = N->getValueType(0);
7348   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7349   unsigned NumElts = VT.getVectorNumElements();
7350   MVT TruncVT = MVT::getIntegerVT(EltSize);
7351   SmallVector<SDValue, 8> Ops;
7352   SDLoc dl(N);
7353   for (unsigned i = 0; i != NumElts; ++i) {
7354     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7355     const APInt &CInt = C->getAPIntValue();
7356     // Element types smaller than 32 bits are not legal, so use i32 elements.
7357     // The values are implicitly truncated so sext vs. zext doesn't matter.
7358     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7359   }
7360   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7361 }
7362 
7363 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7364   unsigned Opcode = N->getOpcode();
7365   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7366     SDNode *N0 = N->getOperand(0).getNode();
7367     SDNode *N1 = N->getOperand(1).getNode();
7368     return N0->hasOneUse() && N1->hasOneUse() &&
7369       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7370   }
7371   return false;
7372 }
7373 
7374 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7375   unsigned Opcode = N->getOpcode();
7376   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7377     SDNode *N0 = N->getOperand(0).getNode();
7378     SDNode *N1 = N->getOperand(1).getNode();
7379     return N0->hasOneUse() && N1->hasOneUse() &&
7380       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7381   }
7382   return false;
7383 }
7384 
7385 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7386   // Multiplications are only custom-lowered for 128-bit vectors so that
7387   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7388   EVT VT = Op.getValueType();
7389   assert(VT.is128BitVector() && VT.isInteger() &&
7390          "unexpected type for custom-lowering ISD::MUL");
7391   SDNode *N0 = Op.getOperand(0).getNode();
7392   SDNode *N1 = Op.getOperand(1).getNode();
7393   unsigned NewOpc = 0;
7394   bool isMLA = false;
7395   bool isN0SExt = isSignExtended(N0, DAG);
7396   bool isN1SExt = isSignExtended(N1, DAG);
7397   if (isN0SExt && isN1SExt)
7398     NewOpc = ARMISD::VMULLs;
7399   else {
7400     bool isN0ZExt = isZeroExtended(N0, DAG);
7401     bool isN1ZExt = isZeroExtended(N1, DAG);
7402     if (isN0ZExt && isN1ZExt)
7403       NewOpc = ARMISD::VMULLu;
7404     else if (isN1SExt || isN1ZExt) {
7405       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7406       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7407       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7408         NewOpc = ARMISD::VMULLs;
7409         isMLA = true;
7410       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7411         NewOpc = ARMISD::VMULLu;
7412         isMLA = true;
7413       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7414         std::swap(N0, N1);
7415         NewOpc = ARMISD::VMULLu;
7416         isMLA = true;
7417       }
7418     }
7419 
7420     if (!NewOpc) {
7421       if (VT == MVT::v2i64)
7422         // Fall through to expand this.  It is not legal.
7423         return SDValue();
7424       else
7425         // Other vector multiplications are legal.
7426         return Op;
7427     }
7428   }
7429 
7430   // Legalize to a VMULL instruction.
7431   SDLoc DL(Op);
7432   SDValue Op0;
7433   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7434   if (!isMLA) {
7435     Op0 = SkipExtensionForVMULL(N0, DAG);
7436     assert(Op0.getValueType().is64BitVector() &&
7437            Op1.getValueType().is64BitVector() &&
7438            "unexpected types for extended operands to VMULL");
7439     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7440   }
7441 
7442   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7443   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7444   //   vmull q0, d4, d6
7445   //   vmlal q0, d5, d6
7446   // is faster than
7447   //   vaddl q0, d4, d5
7448   //   vmovl q1, d6
7449   //   vmul  q0, q0, q1
7450   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7451   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7452   EVT Op1VT = Op1.getValueType();
7453   return DAG.getNode(N0->getOpcode(), DL, VT,
7454                      DAG.getNode(NewOpc, DL, VT,
7455                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7456                      DAG.getNode(NewOpc, DL, VT,
7457                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7458 }
7459 
7460 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7461                               SelectionDAG &DAG) {
7462   // TODO: Should this propagate fast-math-flags?
7463 
7464   // Convert to float
7465   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7466   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7467   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7468   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7469   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7470   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7471   // Get reciprocal estimate.
7472   // float4 recip = vrecpeq_f32(yf);
7473   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7474                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7475                    Y);
7476   // Because char has a smaller range than uchar, we can actually get away
7477   // without any newton steps.  This requires that we use a weird bias
7478   // of 0xb000, however (again, this has been exhaustively tested).
7479   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7480   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7481   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7482   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7483   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7484   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7485   // Convert back to short.
7486   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7487   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7488   return X;
7489 }
7490 
7491 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7492                                SelectionDAG &DAG) {
7493   // TODO: Should this propagate fast-math-flags?
7494 
7495   SDValue N2;
7496   // Convert to float.
7497   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7498   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7499   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7500   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7501   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7502   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7503 
7504   // Use reciprocal estimate and one refinement step.
7505   // float4 recip = vrecpeq_f32(yf);
7506   // recip *= vrecpsq_f32(yf, recip);
7507   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7508                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7509                    N1);
7510   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7511                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7512                    N1, N2);
7513   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7514   // Because short has a smaller range than ushort, we can actually get away
7515   // with only a single newton step.  This requires that we use a weird bias
7516   // of 89, however (again, this has been exhaustively tested).
7517   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7518   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7519   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7520   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7521   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7522   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7523   // Convert back to integer and return.
7524   // return vmovn_s32(vcvt_s32_f32(result));
7525   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7526   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7527   return N0;
7528 }
7529 
7530 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7531   EVT VT = Op.getValueType();
7532   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7533          "unexpected type for custom-lowering ISD::SDIV");
7534 
7535   SDLoc dl(Op);
7536   SDValue N0 = Op.getOperand(0);
7537   SDValue N1 = Op.getOperand(1);
7538   SDValue N2, N3;
7539 
7540   if (VT == MVT::v8i8) {
7541     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7542     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7543 
7544     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7545                      DAG.getIntPtrConstant(4, dl));
7546     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7547                      DAG.getIntPtrConstant(4, dl));
7548     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7549                      DAG.getIntPtrConstant(0, dl));
7550     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7551                      DAG.getIntPtrConstant(0, dl));
7552 
7553     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7554     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7555 
7556     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7557     N0 = LowerCONCAT_VECTORS(N0, DAG);
7558 
7559     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7560     return N0;
7561   }
7562   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7563 }
7564 
7565 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7566   // TODO: Should this propagate fast-math-flags?
7567   EVT VT = Op.getValueType();
7568   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7569          "unexpected type for custom-lowering ISD::UDIV");
7570 
7571   SDLoc dl(Op);
7572   SDValue N0 = Op.getOperand(0);
7573   SDValue N1 = Op.getOperand(1);
7574   SDValue N2, N3;
7575 
7576   if (VT == MVT::v8i8) {
7577     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7578     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7579 
7580     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7581                      DAG.getIntPtrConstant(4, dl));
7582     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7583                      DAG.getIntPtrConstant(4, dl));
7584     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7585                      DAG.getIntPtrConstant(0, dl));
7586     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7587                      DAG.getIntPtrConstant(0, dl));
7588 
7589     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7590     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7591 
7592     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7593     N0 = LowerCONCAT_VECTORS(N0, DAG);
7594 
7595     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7596                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7597                                      MVT::i32),
7598                      N0);
7599     return N0;
7600   }
7601 
7602   // v4i16 sdiv ... Convert to float.
7603   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7604   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7605   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7606   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7607   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7608   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7609 
7610   // Use reciprocal estimate and two refinement steps.
7611   // float4 recip = vrecpeq_f32(yf);
7612   // recip *= vrecpsq_f32(yf, recip);
7613   // recip *= vrecpsq_f32(yf, recip);
7614   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7615                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7616                    BN1);
7617   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7618                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7619                    BN1, N2);
7620   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7621   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7622                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7623                    BN1, N2);
7624   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7625   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7626   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7627   // and that it will never cause us to return an answer too large).
7628   // float4 result = as_float4(as_int4(xf*recip) + 2);
7629   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7630   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7631   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7632   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7633   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7634   // Convert back to integer and return.
7635   // return vmovn_u32(vcvt_s32_f32(result));
7636   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7637   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7638   return N0;
7639 }
7640 
7641 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
7642   SDNode *N = Op.getNode();
7643   EVT VT = N->getValueType(0);
7644   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7645 
7646   SDValue Carry = Op.getOperand(2);
7647 
7648   SDLoc DL(Op);
7649 
7650   SDValue Result;
7651   if (Op.getOpcode() == ISD::ADDCARRY) {
7652     // This converts the boolean value carry into the carry flag.
7653     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7654 
7655     // Do the addition proper using the carry flag we wanted.
7656     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
7657                          Op.getOperand(1), Carry);
7658 
7659     // Now convert the carry flag into a boolean value.
7660     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7661   } else {
7662     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
7663     // have to invert the carry first.
7664     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7665                         DAG.getConstant(1, DL, MVT::i32), Carry);
7666     // This converts the boolean value carry into the carry flag.
7667     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7668 
7669     // Do the subtraction proper using the carry flag we wanted.
7670     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
7671                          Op.getOperand(1), Carry);
7672 
7673     // Now convert the carry flag into a boolean value.
7674     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7675     // But the carry returned by ARMISD::SUBE is not a borrow as expected
7676     // by ISD::SUBCARRY, so compute 1 - C.
7677     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7678                         DAG.getConstant(1, DL, MVT::i32), Carry);
7679   }
7680 
7681   // Return both values.
7682   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
7683 }
7684 
7685 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7686   assert(Subtarget->isTargetDarwin());
7687 
7688   // For iOS, we want to call an alternative entry point: __sincos_stret,
7689   // return values are passed via sret.
7690   SDLoc dl(Op);
7691   SDValue Arg = Op.getOperand(0);
7692   EVT ArgVT = Arg.getValueType();
7693   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7694   auto PtrVT = getPointerTy(DAG.getDataLayout());
7695 
7696   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7697   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7698 
7699   // Pair of floats / doubles used to pass the result.
7700   Type *RetTy = StructType::get(ArgTy, ArgTy);
7701   auto &DL = DAG.getDataLayout();
7702 
7703   ArgListTy Args;
7704   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7705   SDValue SRet;
7706   if (ShouldUseSRet) {
7707     // Create stack object for sret.
7708     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7709     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7710     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7711     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7712 
7713     ArgListEntry Entry;
7714     Entry.Node = SRet;
7715     Entry.Ty = RetTy->getPointerTo();
7716     Entry.IsSExt = false;
7717     Entry.IsZExt = false;
7718     Entry.IsSRet = true;
7719     Args.push_back(Entry);
7720     RetTy = Type::getVoidTy(*DAG.getContext());
7721   }
7722 
7723   ArgListEntry Entry;
7724   Entry.Node = Arg;
7725   Entry.Ty = ArgTy;
7726   Entry.IsSExt = false;
7727   Entry.IsZExt = false;
7728   Args.push_back(Entry);
7729 
7730   RTLIB::Libcall LC =
7731       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
7732   const char *LibcallName = getLibcallName(LC);
7733   CallingConv::ID CC = getLibcallCallingConv(LC);
7734   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7735 
7736   TargetLowering::CallLoweringInfo CLI(DAG);
7737   CLI.setDebugLoc(dl)
7738       .setChain(DAG.getEntryNode())
7739       .setCallee(CC, RetTy, Callee, std::move(Args))
7740       .setDiscardResult(ShouldUseSRet);
7741   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7742 
7743   if (!ShouldUseSRet)
7744     return CallResult.first;
7745 
7746   SDValue LoadSin =
7747       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7748 
7749   // Address of cos field.
7750   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7751                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7752   SDValue LoadCos =
7753       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7754 
7755   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7756   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7757                      LoadSin.getValue(0), LoadCos.getValue(0));
7758 }
7759 
7760 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7761                                                   bool Signed,
7762                                                   SDValue &Chain) const {
7763   EVT VT = Op.getValueType();
7764   assert((VT == MVT::i32 || VT == MVT::i64) &&
7765          "unexpected type for custom lowering DIV");
7766   SDLoc dl(Op);
7767 
7768   const auto &DL = DAG.getDataLayout();
7769   const auto &TLI = DAG.getTargetLoweringInfo();
7770 
7771   const char *Name = nullptr;
7772   if (Signed)
7773     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7774   else
7775     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7776 
7777   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7778 
7779   ARMTargetLowering::ArgListTy Args;
7780 
7781   for (auto AI : {1, 0}) {
7782     ArgListEntry Arg;
7783     Arg.Node = Op.getOperand(AI);
7784     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7785     Args.push_back(Arg);
7786   }
7787 
7788   CallLoweringInfo CLI(DAG);
7789   CLI.setDebugLoc(dl)
7790     .setChain(Chain)
7791     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7792                ES, std::move(Args));
7793 
7794   return LowerCallTo(CLI).first;
7795 }
7796 
7797 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7798                                             bool Signed) const {
7799   assert(Op.getValueType() == MVT::i32 &&
7800          "unexpected type for custom lowering DIV");
7801   SDLoc dl(Op);
7802 
7803   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7804                                DAG.getEntryNode(), Op.getOperand(1));
7805 
7806   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7807 }
7808 
7809 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7810   SDLoc DL(N);
7811   SDValue Op = N->getOperand(1);
7812   if (N->getValueType(0) == MVT::i32)
7813     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7814   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7815                            DAG.getConstant(0, DL, MVT::i32));
7816   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7817                            DAG.getConstant(1, DL, MVT::i32));
7818   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7819                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7820 }
7821 
7822 void ARMTargetLowering::ExpandDIV_Windows(
7823     SDValue Op, SelectionDAG &DAG, bool Signed,
7824     SmallVectorImpl<SDValue> &Results) const {
7825   const auto &DL = DAG.getDataLayout();
7826   const auto &TLI = DAG.getTargetLoweringInfo();
7827 
7828   assert(Op.getValueType() == MVT::i64 &&
7829          "unexpected type for custom lowering DIV");
7830   SDLoc dl(Op);
7831 
7832   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7833 
7834   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7835 
7836   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7837   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7838                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7839   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7840 
7841   Results.push_back(Lower);
7842   Results.push_back(Upper);
7843 }
7844 
7845 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7846   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7847     // Acquire/Release load/store is not legal for targets without a dmb or
7848     // equivalent available.
7849     return SDValue();
7850 
7851   // Monotonic load/store is legal for all targets.
7852   return Op;
7853 }
7854 
7855 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7856                                     SmallVectorImpl<SDValue> &Results,
7857                                     SelectionDAG &DAG,
7858                                     const ARMSubtarget *Subtarget) {
7859   SDLoc DL(N);
7860   // Under Power Management extensions, the cycle-count is:
7861   //    mrc p15, #0, <Rt>, c9, c13, #0
7862   SDValue Ops[] = { N->getOperand(0), // Chain
7863                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7864                     DAG.getConstant(15, DL, MVT::i32),
7865                     DAG.getConstant(0, DL, MVT::i32),
7866                     DAG.getConstant(9, DL, MVT::i32),
7867                     DAG.getConstant(13, DL, MVT::i32),
7868                     DAG.getConstant(0, DL, MVT::i32)
7869   };
7870 
7871   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7872                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7873   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7874                                 DAG.getConstant(0, DL, MVT::i32)));
7875   Results.push_back(Cycles32.getValue(1));
7876 }
7877 
7878 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7879   SDLoc dl(V.getNode());
7880   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7881   SDValue VHi = DAG.getAnyExtOrTrunc(
7882       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7883       dl, MVT::i32);
7884   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7885   if (isBigEndian)
7886     std::swap (VLo, VHi);
7887   SDValue RegClass =
7888       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7889   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7890   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7891   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7892   return SDValue(
7893       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7894 }
7895 
7896 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7897                                        SmallVectorImpl<SDValue> & Results,
7898                                        SelectionDAG &DAG) {
7899   assert(N->getValueType(0) == MVT::i64 &&
7900          "AtomicCmpSwap on types less than 64 should be legal");
7901   SDValue Ops[] = {N->getOperand(1),
7902                    createGPRPairNode(DAG, N->getOperand(2)),
7903                    createGPRPairNode(DAG, N->getOperand(3)),
7904                    N->getOperand(0)};
7905   SDNode *CmpSwap = DAG.getMachineNode(
7906       ARM::CMP_SWAP_64, SDLoc(N),
7907       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7908 
7909   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
7910   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
7911 
7912   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7913 
7914   Results.push_back(
7915       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
7916                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7917   Results.push_back(
7918       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
7919                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7920   Results.push_back(SDValue(CmpSwap, 2));
7921 }
7922 
7923 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7924                           SelectionDAG &DAG) {
7925   const auto &TLI = DAG.getTargetLoweringInfo();
7926 
7927   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7928          "Custom lowering is MSVCRT specific!");
7929 
7930   SDLoc dl(Op);
7931   SDValue Val = Op.getOperand(0);
7932   MVT Ty = Val->getSimpleValueType(0);
7933   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7934   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7935                                          TLI.getPointerTy(DAG.getDataLayout()));
7936 
7937   TargetLowering::ArgListTy Args;
7938   TargetLowering::ArgListEntry Entry;
7939 
7940   Entry.Node = Val;
7941   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7942   Entry.IsZExt = true;
7943   Args.push_back(Entry);
7944 
7945   Entry.Node = Exponent;
7946   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7947   Entry.IsZExt = true;
7948   Args.push_back(Entry);
7949 
7950   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7951 
7952   // In the in-chain to the call is the entry node  If we are emitting a
7953   // tailcall, the chain will be mutated if the node has a non-entry input
7954   // chain.
7955   SDValue InChain = DAG.getEntryNode();
7956   SDValue TCChain = InChain;
7957 
7958   const Function &F = DAG.getMachineFunction().getFunction();
7959   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
7960               F.getReturnType() == LCRTy;
7961   if (IsTC)
7962     InChain = TCChain;
7963 
7964   TargetLowering::CallLoweringInfo CLI(DAG);
7965   CLI.setDebugLoc(dl)
7966       .setChain(InChain)
7967       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
7968       .setTailCall(IsTC);
7969   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
7970 
7971   // Return the chain (the DAG root) if it is a tail call
7972   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
7973 }
7974 
7975 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7976   LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
7977   switch (Op.getOpcode()) {
7978   default: llvm_unreachable("Don't know how to custom lower this!");
7979   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7980   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7981   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7982   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7983   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7984   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7985   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7986   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
7987   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7988   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7989   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7990   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7991   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7992   case ISD::SINT_TO_FP:
7993   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7994   case ISD::FP_TO_SINT:
7995   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7996   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7997   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7998   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7999   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
8000   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
8001   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
8002   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
8003                                                                Subtarget);
8004   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
8005   case ISD::SHL:
8006   case ISD::SRL:
8007   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
8008   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
8009   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
8010   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
8011   case ISD::SRL_PARTS:
8012   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
8013   case ISD::CTTZ:
8014   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
8015   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
8016   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
8017   case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
8018   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
8019   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
8020   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8021   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8022   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8023   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8024   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
8025   case ISD::MUL:           return LowerMUL(Op, DAG);
8026   case ISD::SDIV:
8027     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8028       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
8029     return LowerSDIV(Op, DAG);
8030   case ISD::UDIV:
8031     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8032       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
8033     return LowerUDIV(Op, DAG);
8034   case ISD::ADDCARRY:
8035   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
8036   case ISD::SADDO:
8037   case ISD::SSUBO:
8038     return LowerSignedALUO(Op, DAG);
8039   case ISD::UADDO:
8040   case ISD::USUBO:
8041     return LowerUnsignedALUO(Op, DAG);
8042   case ISD::ATOMIC_LOAD:
8043   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
8044   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
8045   case ISD::SDIVREM:
8046   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
8047   case ISD::DYNAMIC_STACKALLOC:
8048     if (Subtarget->isTargetWindows())
8049       return LowerDYNAMIC_STACKALLOC(Op, DAG);
8050     llvm_unreachable("Don't know how to custom lower this!");
8051   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
8052   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
8053   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
8054   case ARMISD::WIN__DBZCHK: return SDValue();
8055   }
8056 }
8057 
8058 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
8059                                  SelectionDAG &DAG) {
8060   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8061   unsigned Opc = 0;
8062   if (IntNo == Intrinsic::arm_smlald)
8063     Opc = ARMISD::SMLALD;
8064   else if (IntNo == Intrinsic::arm_smlaldx)
8065     Opc = ARMISD::SMLALDX;
8066   else if (IntNo == Intrinsic::arm_smlsld)
8067     Opc = ARMISD::SMLSLD;
8068   else if (IntNo == Intrinsic::arm_smlsldx)
8069     Opc = ARMISD::SMLSLDX;
8070   else
8071     return;
8072 
8073   SDLoc dl(N);
8074   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8075                            N->getOperand(3),
8076                            DAG.getConstant(0, dl, MVT::i32));
8077   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8078                            N->getOperand(3),
8079                            DAG.getConstant(1, dl, MVT::i32));
8080 
8081   SDValue LongMul = DAG.getNode(Opc, dl,
8082                                 DAG.getVTList(MVT::i32, MVT::i32),
8083                                 N->getOperand(1), N->getOperand(2),
8084                                 Lo, Hi);
8085   Results.push_back(LongMul.getValue(0));
8086   Results.push_back(LongMul.getValue(1));
8087 }
8088 
8089 /// ReplaceNodeResults - Replace the results of node with an illegal result
8090 /// type with new values built out of custom code.
8091 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
8092                                            SmallVectorImpl<SDValue> &Results,
8093                                            SelectionDAG &DAG) const {
8094   SDValue Res;
8095   switch (N->getOpcode()) {
8096   default:
8097     llvm_unreachable("Don't know how to custom expand this!");
8098   case ISD::READ_REGISTER:
8099     ExpandREAD_REGISTER(N, Results, DAG);
8100     break;
8101   case ISD::BITCAST:
8102     Res = ExpandBITCAST(N, DAG, Subtarget);
8103     break;
8104   case ISD::SRL:
8105   case ISD::SRA:
8106     Res = Expand64BitShift(N, DAG, Subtarget);
8107     break;
8108   case ISD::SREM:
8109   case ISD::UREM:
8110     Res = LowerREM(N, DAG);
8111     break;
8112   case ISD::SDIVREM:
8113   case ISD::UDIVREM:
8114     Res = LowerDivRem(SDValue(N, 0), DAG);
8115     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
8116     Results.push_back(Res.getValue(0));
8117     Results.push_back(Res.getValue(1));
8118     return;
8119   case ISD::READCYCLECOUNTER:
8120     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
8121     return;
8122   case ISD::UDIV:
8123   case ISD::SDIV:
8124     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
8125     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
8126                              Results);
8127   case ISD::ATOMIC_CMP_SWAP:
8128     ReplaceCMP_SWAP_64Results(N, Results, DAG);
8129     return;
8130   case ISD::INTRINSIC_WO_CHAIN:
8131     return ReplaceLongIntrinsic(N, Results, DAG);
8132   }
8133   if (Res.getNode())
8134     Results.push_back(Res);
8135 }
8136 
8137 //===----------------------------------------------------------------------===//
8138 //                           ARM Scheduler Hooks
8139 //===----------------------------------------------------------------------===//
8140 
8141 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
8142 /// registers the function context.
8143 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
8144                                                MachineBasicBlock *MBB,
8145                                                MachineBasicBlock *DispatchBB,
8146                                                int FI) const {
8147   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
8148          "ROPI/RWPI not currently supported with SjLj");
8149   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8150   DebugLoc dl = MI.getDebugLoc();
8151   MachineFunction *MF = MBB->getParent();
8152   MachineRegisterInfo *MRI = &MF->getRegInfo();
8153   MachineConstantPool *MCP = MF->getConstantPool();
8154   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
8155   const Function &F = MF->getFunction();
8156 
8157   bool isThumb = Subtarget->isThumb();
8158   bool isThumb2 = Subtarget->isThumb2();
8159 
8160   unsigned PCLabelId = AFI->createPICLabelUId();
8161   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
8162   ARMConstantPoolValue *CPV =
8163     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
8164   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
8165 
8166   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
8167                                            : &ARM::GPRRegClass;
8168 
8169   // Grab constant pool and fixed stack memory operands.
8170   MachineMemOperand *CPMMO =
8171       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
8172                                MachineMemOperand::MOLoad, 4, 4);
8173 
8174   MachineMemOperand *FIMMOSt =
8175       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
8176                                MachineMemOperand::MOStore, 4, 4);
8177 
8178   // Load the address of the dispatch MBB into the jump buffer.
8179   if (isThumb2) {
8180     // Incoming value: jbuf
8181     //   ldr.n  r5, LCPI1_1
8182     //   orr    r5, r5, #1
8183     //   add    r5, pc
8184     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
8185     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8186     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
8187         .addConstantPoolIndex(CPI)
8188         .addMemOperand(CPMMO)
8189         .add(predOps(ARMCC::AL));
8190     // Set the low bit because of thumb mode.
8191     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8192     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8193         .addReg(NewVReg1, RegState::Kill)
8194         .addImm(0x01)
8195         .add(predOps(ARMCC::AL))
8196         .add(condCodeOp());
8197     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8198     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8199       .addReg(NewVReg2, RegState::Kill)
8200       .addImm(PCLabelId);
8201     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8202         .addReg(NewVReg3, RegState::Kill)
8203         .addFrameIndex(FI)
8204         .addImm(36) // &jbuf[1] :: pc
8205         .addMemOperand(FIMMOSt)
8206         .add(predOps(ARMCC::AL));
8207   } else if (isThumb) {
8208     // Incoming value: jbuf
8209     //   ldr.n  r1, LCPI1_4
8210     //   add    r1, pc
8211     //   mov    r2, #1
8212     //   orrs   r1, r2
8213     //   add    r2, $jbuf, #+4 ; &jbuf[1]
8214     //   str    r1, [r2]
8215     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8216     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8217         .addConstantPoolIndex(CPI)
8218         .addMemOperand(CPMMO)
8219         .add(predOps(ARMCC::AL));
8220     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8221     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8222       .addReg(NewVReg1, RegState::Kill)
8223       .addImm(PCLabelId);
8224     // Set the low bit because of thumb mode.
8225     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8226     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8227         .addReg(ARM::CPSR, RegState::Define)
8228         .addImm(1)
8229         .add(predOps(ARMCC::AL));
8230     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8231     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8232         .addReg(ARM::CPSR, RegState::Define)
8233         .addReg(NewVReg2, RegState::Kill)
8234         .addReg(NewVReg3, RegState::Kill)
8235         .add(predOps(ARMCC::AL));
8236     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8237     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8238             .addFrameIndex(FI)
8239             .addImm(36); // &jbuf[1] :: pc
8240     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8241         .addReg(NewVReg4, RegState::Kill)
8242         .addReg(NewVReg5, RegState::Kill)
8243         .addImm(0)
8244         .addMemOperand(FIMMOSt)
8245         .add(predOps(ARMCC::AL));
8246   } else {
8247     // Incoming value: jbuf
8248     //   ldr  r1, LCPI1_1
8249     //   add  r1, pc, r1
8250     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
8251     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8252     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
8253         .addConstantPoolIndex(CPI)
8254         .addImm(0)
8255         .addMemOperand(CPMMO)
8256         .add(predOps(ARMCC::AL));
8257     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8258     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
8259         .addReg(NewVReg1, RegState::Kill)
8260         .addImm(PCLabelId)
8261         .add(predOps(ARMCC::AL));
8262     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
8263         .addReg(NewVReg2, RegState::Kill)
8264         .addFrameIndex(FI)
8265         .addImm(36) // &jbuf[1] :: pc
8266         .addMemOperand(FIMMOSt)
8267         .add(predOps(ARMCC::AL));
8268   }
8269 }
8270 
8271 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
8272                                               MachineBasicBlock *MBB) const {
8273   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8274   DebugLoc dl = MI.getDebugLoc();
8275   MachineFunction *MF = MBB->getParent();
8276   MachineRegisterInfo *MRI = &MF->getRegInfo();
8277   MachineFrameInfo &MFI = MF->getFrameInfo();
8278   int FI = MFI.getFunctionContextIndex();
8279 
8280   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
8281                                                         : &ARM::GPRnopcRegClass;
8282 
8283   // Get a mapping of the call site numbers to all of the landing pads they're
8284   // associated with.
8285   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
8286   unsigned MaxCSNum = 0;
8287   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8288        ++BB) {
8289     if (!BB->isEHPad()) continue;
8290 
8291     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8292     // pad.
8293     for (MachineBasicBlock::iterator
8294            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8295       if (!II->isEHLabel()) continue;
8296 
8297       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8298       if (!MF->hasCallSiteLandingPad(Sym)) continue;
8299 
8300       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8301       for (SmallVectorImpl<unsigned>::iterator
8302              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8303            CSI != CSE; ++CSI) {
8304         CallSiteNumToLPad[*CSI].push_back(&*BB);
8305         MaxCSNum = std::max(MaxCSNum, *CSI);
8306       }
8307       break;
8308     }
8309   }
8310 
8311   // Get an ordered list of the machine basic blocks for the jump table.
8312   std::vector<MachineBasicBlock*> LPadList;
8313   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8314   LPadList.reserve(CallSiteNumToLPad.size());
8315   for (unsigned I = 1; I <= MaxCSNum; ++I) {
8316     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8317     for (SmallVectorImpl<MachineBasicBlock*>::iterator
8318            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8319       LPadList.push_back(*II);
8320       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8321     }
8322   }
8323 
8324   assert(!LPadList.empty() &&
8325          "No landing pad destinations for the dispatch jump table!");
8326 
8327   // Create the jump table and associated information.
8328   MachineJumpTableInfo *JTI =
8329     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8330   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8331 
8332   // Create the MBBs for the dispatch code.
8333 
8334   // Shove the dispatch's address into the return slot in the function context.
8335   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8336   DispatchBB->setIsEHPad();
8337 
8338   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8339   unsigned trap_opcode;
8340   if (Subtarget->isThumb())
8341     trap_opcode = ARM::tTRAP;
8342   else
8343     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8344 
8345   BuildMI(TrapBB, dl, TII->get(trap_opcode));
8346   DispatchBB->addSuccessor(TrapBB);
8347 
8348   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8349   DispatchBB->addSuccessor(DispContBB);
8350 
8351   // Insert and MBBs.
8352   MF->insert(MF->end(), DispatchBB);
8353   MF->insert(MF->end(), DispContBB);
8354   MF->insert(MF->end(), TrapBB);
8355 
8356   // Insert code into the entry block that creates and registers the function
8357   // context.
8358   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8359 
8360   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8361       MachinePointerInfo::getFixedStack(*MF, FI),
8362       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8363 
8364   MachineInstrBuilder MIB;
8365   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8366 
8367   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8368   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8369 
8370   // Add a register mask with no preserved registers.  This results in all
8371   // registers being marked as clobbered. This can't work if the dispatch block
8372   // is in a Thumb1 function and is linked with ARM code which uses the FP
8373   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8374   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8375 
8376   bool IsPositionIndependent = isPositionIndependent();
8377   unsigned NumLPads = LPadList.size();
8378   if (Subtarget->isThumb2()) {
8379     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8380     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8381         .addFrameIndex(FI)
8382         .addImm(4)
8383         .addMemOperand(FIMMOLd)
8384         .add(predOps(ARMCC::AL));
8385 
8386     if (NumLPads < 256) {
8387       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8388           .addReg(NewVReg1)
8389           .addImm(LPadList.size())
8390           .add(predOps(ARMCC::AL));
8391     } else {
8392       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8393       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8394           .addImm(NumLPads & 0xFFFF)
8395           .add(predOps(ARMCC::AL));
8396 
8397       unsigned VReg2 = VReg1;
8398       if ((NumLPads & 0xFFFF0000) != 0) {
8399         VReg2 = MRI->createVirtualRegister(TRC);
8400         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8401             .addReg(VReg1)
8402             .addImm(NumLPads >> 16)
8403             .add(predOps(ARMCC::AL));
8404       }
8405 
8406       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8407           .addReg(NewVReg1)
8408           .addReg(VReg2)
8409           .add(predOps(ARMCC::AL));
8410     }
8411 
8412     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8413       .addMBB(TrapBB)
8414       .addImm(ARMCC::HI)
8415       .addReg(ARM::CPSR);
8416 
8417     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8418     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8419         .addJumpTableIndex(MJTI)
8420         .add(predOps(ARMCC::AL));
8421 
8422     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8423     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8424         .addReg(NewVReg3, RegState::Kill)
8425         .addReg(NewVReg1)
8426         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8427         .add(predOps(ARMCC::AL))
8428         .add(condCodeOp());
8429 
8430     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8431       .addReg(NewVReg4, RegState::Kill)
8432       .addReg(NewVReg1)
8433       .addJumpTableIndex(MJTI);
8434   } else if (Subtarget->isThumb()) {
8435     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8436     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8437         .addFrameIndex(FI)
8438         .addImm(1)
8439         .addMemOperand(FIMMOLd)
8440         .add(predOps(ARMCC::AL));
8441 
8442     if (NumLPads < 256) {
8443       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8444           .addReg(NewVReg1)
8445           .addImm(NumLPads)
8446           .add(predOps(ARMCC::AL));
8447     } else {
8448       MachineConstantPool *ConstantPool = MF->getConstantPool();
8449       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8450       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8451 
8452       // MachineConstantPool wants an explicit alignment.
8453       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8454       if (Align == 0)
8455         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8456       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8457 
8458       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8459       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8460           .addReg(VReg1, RegState::Define)
8461           .addConstantPoolIndex(Idx)
8462           .add(predOps(ARMCC::AL));
8463       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8464           .addReg(NewVReg1)
8465           .addReg(VReg1)
8466           .add(predOps(ARMCC::AL));
8467     }
8468 
8469     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8470       .addMBB(TrapBB)
8471       .addImm(ARMCC::HI)
8472       .addReg(ARM::CPSR);
8473 
8474     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8475     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8476         .addReg(ARM::CPSR, RegState::Define)
8477         .addReg(NewVReg1)
8478         .addImm(2)
8479         .add(predOps(ARMCC::AL));
8480 
8481     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8482     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8483         .addJumpTableIndex(MJTI)
8484         .add(predOps(ARMCC::AL));
8485 
8486     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8487     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8488         .addReg(ARM::CPSR, RegState::Define)
8489         .addReg(NewVReg2, RegState::Kill)
8490         .addReg(NewVReg3)
8491         .add(predOps(ARMCC::AL));
8492 
8493     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8494         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8495 
8496     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8497     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8498         .addReg(NewVReg4, RegState::Kill)
8499         .addImm(0)
8500         .addMemOperand(JTMMOLd)
8501         .add(predOps(ARMCC::AL));
8502 
8503     unsigned NewVReg6 = NewVReg5;
8504     if (IsPositionIndependent) {
8505       NewVReg6 = MRI->createVirtualRegister(TRC);
8506       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8507           .addReg(ARM::CPSR, RegState::Define)
8508           .addReg(NewVReg5, RegState::Kill)
8509           .addReg(NewVReg3)
8510           .add(predOps(ARMCC::AL));
8511     }
8512 
8513     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8514       .addReg(NewVReg6, RegState::Kill)
8515       .addJumpTableIndex(MJTI);
8516   } else {
8517     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8518     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8519         .addFrameIndex(FI)
8520         .addImm(4)
8521         .addMemOperand(FIMMOLd)
8522         .add(predOps(ARMCC::AL));
8523 
8524     if (NumLPads < 256) {
8525       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8526           .addReg(NewVReg1)
8527           .addImm(NumLPads)
8528           .add(predOps(ARMCC::AL));
8529     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8530       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8531       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8532           .addImm(NumLPads & 0xFFFF)
8533           .add(predOps(ARMCC::AL));
8534 
8535       unsigned VReg2 = VReg1;
8536       if ((NumLPads & 0xFFFF0000) != 0) {
8537         VReg2 = MRI->createVirtualRegister(TRC);
8538         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8539             .addReg(VReg1)
8540             .addImm(NumLPads >> 16)
8541             .add(predOps(ARMCC::AL));
8542       }
8543 
8544       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8545           .addReg(NewVReg1)
8546           .addReg(VReg2)
8547           .add(predOps(ARMCC::AL));
8548     } else {
8549       MachineConstantPool *ConstantPool = MF->getConstantPool();
8550       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8551       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8552 
8553       // MachineConstantPool wants an explicit alignment.
8554       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8555       if (Align == 0)
8556         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8557       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8558 
8559       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8560       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8561           .addReg(VReg1, RegState::Define)
8562           .addConstantPoolIndex(Idx)
8563           .addImm(0)
8564           .add(predOps(ARMCC::AL));
8565       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8566           .addReg(NewVReg1)
8567           .addReg(VReg1, RegState::Kill)
8568           .add(predOps(ARMCC::AL));
8569     }
8570 
8571     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8572       .addMBB(TrapBB)
8573       .addImm(ARMCC::HI)
8574       .addReg(ARM::CPSR);
8575 
8576     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8577     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8578         .addReg(NewVReg1)
8579         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8580         .add(predOps(ARMCC::AL))
8581         .add(condCodeOp());
8582     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8583     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8584         .addJumpTableIndex(MJTI)
8585         .add(predOps(ARMCC::AL));
8586 
8587     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8588         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8589     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8590     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8591         .addReg(NewVReg3, RegState::Kill)
8592         .addReg(NewVReg4)
8593         .addImm(0)
8594         .addMemOperand(JTMMOLd)
8595         .add(predOps(ARMCC::AL));
8596 
8597     if (IsPositionIndependent) {
8598       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8599         .addReg(NewVReg5, RegState::Kill)
8600         .addReg(NewVReg4)
8601         .addJumpTableIndex(MJTI);
8602     } else {
8603       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8604         .addReg(NewVReg5, RegState::Kill)
8605         .addJumpTableIndex(MJTI);
8606     }
8607   }
8608 
8609   // Add the jump table entries as successors to the MBB.
8610   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8611   for (std::vector<MachineBasicBlock*>::iterator
8612          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8613     MachineBasicBlock *CurMBB = *I;
8614     if (SeenMBBs.insert(CurMBB).second)
8615       DispContBB->addSuccessor(CurMBB);
8616   }
8617 
8618   // N.B. the order the invoke BBs are processed in doesn't matter here.
8619   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8620   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8621   for (MachineBasicBlock *BB : InvokeBBs) {
8622 
8623     // Remove the landing pad successor from the invoke block and replace it
8624     // with the new dispatch block.
8625     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8626                                                   BB->succ_end());
8627     while (!Successors.empty()) {
8628       MachineBasicBlock *SMBB = Successors.pop_back_val();
8629       if (SMBB->isEHPad()) {
8630         BB->removeSuccessor(SMBB);
8631         MBBLPads.push_back(SMBB);
8632       }
8633     }
8634 
8635     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8636     BB->normalizeSuccProbs();
8637 
8638     // Find the invoke call and mark all of the callee-saved registers as
8639     // 'implicit defined' so that they're spilled. This prevents code from
8640     // moving instructions to before the EH block, where they will never be
8641     // executed.
8642     for (MachineBasicBlock::reverse_iterator
8643            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8644       if (!II->isCall()) continue;
8645 
8646       DenseMap<unsigned, bool> DefRegs;
8647       for (MachineInstr::mop_iterator
8648              OI = II->operands_begin(), OE = II->operands_end();
8649            OI != OE; ++OI) {
8650         if (!OI->isReg()) continue;
8651         DefRegs[OI->getReg()] = true;
8652       }
8653 
8654       MachineInstrBuilder MIB(*MF, &*II);
8655 
8656       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8657         unsigned Reg = SavedRegs[i];
8658         if (Subtarget->isThumb2() &&
8659             !ARM::tGPRRegClass.contains(Reg) &&
8660             !ARM::hGPRRegClass.contains(Reg))
8661           continue;
8662         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8663           continue;
8664         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8665           continue;
8666         if (!DefRegs[Reg])
8667           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8668       }
8669 
8670       break;
8671     }
8672   }
8673 
8674   // Mark all former landing pads as non-landing pads. The dispatch is the only
8675   // landing pad now.
8676   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8677          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8678     (*I)->setIsEHPad(false);
8679 
8680   // The instruction is gone now.
8681   MI.eraseFromParent();
8682 }
8683 
8684 static
8685 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8686   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8687        E = MBB->succ_end(); I != E; ++I)
8688     if (*I != Succ)
8689       return *I;
8690   llvm_unreachable("Expecting a BB with two successors!");
8691 }
8692 
8693 /// Return the load opcode for a given load size. If load size >= 8,
8694 /// neon opcode will be returned.
8695 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8696   if (LdSize >= 8)
8697     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8698                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8699   if (IsThumb1)
8700     return LdSize == 4 ? ARM::tLDRi
8701                        : LdSize == 2 ? ARM::tLDRHi
8702                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8703   if (IsThumb2)
8704     return LdSize == 4 ? ARM::t2LDR_POST
8705                        : LdSize == 2 ? ARM::t2LDRH_POST
8706                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8707   return LdSize == 4 ? ARM::LDR_POST_IMM
8708                      : LdSize == 2 ? ARM::LDRH_POST
8709                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8710 }
8711 
8712 /// Return the store opcode for a given store size. If store size >= 8,
8713 /// neon opcode will be returned.
8714 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8715   if (StSize >= 8)
8716     return StSize == 16 ? ARM::VST1q32wb_fixed
8717                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8718   if (IsThumb1)
8719     return StSize == 4 ? ARM::tSTRi
8720                        : StSize == 2 ? ARM::tSTRHi
8721                                      : StSize == 1 ? ARM::tSTRBi : 0;
8722   if (IsThumb2)
8723     return StSize == 4 ? ARM::t2STR_POST
8724                        : StSize == 2 ? ARM::t2STRH_POST
8725                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8726   return StSize == 4 ? ARM::STR_POST_IMM
8727                      : StSize == 2 ? ARM::STRH_POST
8728                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8729 }
8730 
8731 /// Emit a post-increment load operation with given size. The instructions
8732 /// will be added to BB at Pos.
8733 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8734                        const TargetInstrInfo *TII, const DebugLoc &dl,
8735                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8736                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8737   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8738   assert(LdOpc != 0 && "Should have a load opcode");
8739   if (LdSize >= 8) {
8740     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8741         .addReg(AddrOut, RegState::Define)
8742         .addReg(AddrIn)
8743         .addImm(0)
8744         .add(predOps(ARMCC::AL));
8745   } else if (IsThumb1) {
8746     // load + update AddrIn
8747     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8748         .addReg(AddrIn)
8749         .addImm(0)
8750         .add(predOps(ARMCC::AL));
8751     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8752         .add(t1CondCodeOp())
8753         .addReg(AddrIn)
8754         .addImm(LdSize)
8755         .add(predOps(ARMCC::AL));
8756   } else if (IsThumb2) {
8757     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8758         .addReg(AddrOut, RegState::Define)
8759         .addReg(AddrIn)
8760         .addImm(LdSize)
8761         .add(predOps(ARMCC::AL));
8762   } else { // arm
8763     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8764         .addReg(AddrOut, RegState::Define)
8765         .addReg(AddrIn)
8766         .addReg(0)
8767         .addImm(LdSize)
8768         .add(predOps(ARMCC::AL));
8769   }
8770 }
8771 
8772 /// Emit a post-increment store operation with given size. The instructions
8773 /// will be added to BB at Pos.
8774 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8775                        const TargetInstrInfo *TII, const DebugLoc &dl,
8776                        unsigned StSize, unsigned Data, unsigned AddrIn,
8777                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8778   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8779   assert(StOpc != 0 && "Should have a store opcode");
8780   if (StSize >= 8) {
8781     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8782         .addReg(AddrIn)
8783         .addImm(0)
8784         .addReg(Data)
8785         .add(predOps(ARMCC::AL));
8786   } else if (IsThumb1) {
8787     // store + update AddrIn
8788     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8789         .addReg(Data)
8790         .addReg(AddrIn)
8791         .addImm(0)
8792         .add(predOps(ARMCC::AL));
8793     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8794         .add(t1CondCodeOp())
8795         .addReg(AddrIn)
8796         .addImm(StSize)
8797         .add(predOps(ARMCC::AL));
8798   } else if (IsThumb2) {
8799     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8800         .addReg(Data)
8801         .addReg(AddrIn)
8802         .addImm(StSize)
8803         .add(predOps(ARMCC::AL));
8804   } else { // arm
8805     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8806         .addReg(Data)
8807         .addReg(AddrIn)
8808         .addReg(0)
8809         .addImm(StSize)
8810         .add(predOps(ARMCC::AL));
8811   }
8812 }
8813 
8814 MachineBasicBlock *
8815 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8816                                    MachineBasicBlock *BB) const {
8817   // This pseudo instruction has 3 operands: dst, src, size
8818   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8819   // Otherwise, we will generate unrolled scalar copies.
8820   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8821   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8822   MachineFunction::iterator It = ++BB->getIterator();
8823 
8824   unsigned dest = MI.getOperand(0).getReg();
8825   unsigned src = MI.getOperand(1).getReg();
8826   unsigned SizeVal = MI.getOperand(2).getImm();
8827   unsigned Align = MI.getOperand(3).getImm();
8828   DebugLoc dl = MI.getDebugLoc();
8829 
8830   MachineFunction *MF = BB->getParent();
8831   MachineRegisterInfo &MRI = MF->getRegInfo();
8832   unsigned UnitSize = 0;
8833   const TargetRegisterClass *TRC = nullptr;
8834   const TargetRegisterClass *VecTRC = nullptr;
8835 
8836   bool IsThumb1 = Subtarget->isThumb1Only();
8837   bool IsThumb2 = Subtarget->isThumb2();
8838   bool IsThumb = Subtarget->isThumb();
8839 
8840   if (Align & 1) {
8841     UnitSize = 1;
8842   } else if (Align & 2) {
8843     UnitSize = 2;
8844   } else {
8845     // Check whether we can use NEON instructions.
8846     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
8847         Subtarget->hasNEON()) {
8848       if ((Align % 16 == 0) && SizeVal >= 16)
8849         UnitSize = 16;
8850       else if ((Align % 8 == 0) && SizeVal >= 8)
8851         UnitSize = 8;
8852     }
8853     // Can't use NEON instructions.
8854     if (UnitSize == 0)
8855       UnitSize = 4;
8856   }
8857 
8858   // Select the correct opcode and register class for unit size load/store
8859   bool IsNeon = UnitSize >= 8;
8860   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8861   if (IsNeon)
8862     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8863                             : UnitSize == 8 ? &ARM::DPRRegClass
8864                                             : nullptr;
8865 
8866   unsigned BytesLeft = SizeVal % UnitSize;
8867   unsigned LoopSize = SizeVal - BytesLeft;
8868 
8869   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8870     // Use LDR and STR to copy.
8871     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8872     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8873     unsigned srcIn = src;
8874     unsigned destIn = dest;
8875     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8876       unsigned srcOut = MRI.createVirtualRegister(TRC);
8877       unsigned destOut = MRI.createVirtualRegister(TRC);
8878       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8879       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8880                  IsThumb1, IsThumb2);
8881       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8882                  IsThumb1, IsThumb2);
8883       srcIn = srcOut;
8884       destIn = destOut;
8885     }
8886 
8887     // Handle the leftover bytes with LDRB and STRB.
8888     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8889     // [destOut] = STRB_POST(scratch, destIn, 1)
8890     for (unsigned i = 0; i < BytesLeft; i++) {
8891       unsigned srcOut = MRI.createVirtualRegister(TRC);
8892       unsigned destOut = MRI.createVirtualRegister(TRC);
8893       unsigned scratch = MRI.createVirtualRegister(TRC);
8894       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8895                  IsThumb1, IsThumb2);
8896       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8897                  IsThumb1, IsThumb2);
8898       srcIn = srcOut;
8899       destIn = destOut;
8900     }
8901     MI.eraseFromParent(); // The instruction is gone now.
8902     return BB;
8903   }
8904 
8905   // Expand the pseudo op to a loop.
8906   // thisMBB:
8907   //   ...
8908   //   movw varEnd, # --> with thumb2
8909   //   movt varEnd, #
8910   //   ldrcp varEnd, idx --> without thumb2
8911   //   fallthrough --> loopMBB
8912   // loopMBB:
8913   //   PHI varPhi, varEnd, varLoop
8914   //   PHI srcPhi, src, srcLoop
8915   //   PHI destPhi, dst, destLoop
8916   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8917   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8918   //   subs varLoop, varPhi, #UnitSize
8919   //   bne loopMBB
8920   //   fallthrough --> exitMBB
8921   // exitMBB:
8922   //   epilogue to handle left-over bytes
8923   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8924   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8925   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8926   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8927   MF->insert(It, loopMBB);
8928   MF->insert(It, exitMBB);
8929 
8930   // Transfer the remainder of BB and its successor edges to exitMBB.
8931   exitMBB->splice(exitMBB->begin(), BB,
8932                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8933   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8934 
8935   // Load an immediate to varEnd.
8936   unsigned varEnd = MRI.createVirtualRegister(TRC);
8937   if (Subtarget->useMovt(*MF)) {
8938     unsigned Vtmp = varEnd;
8939     if ((LoopSize & 0xFFFF0000) != 0)
8940       Vtmp = MRI.createVirtualRegister(TRC);
8941     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8942         .addImm(LoopSize & 0xFFFF)
8943         .add(predOps(ARMCC::AL));
8944 
8945     if ((LoopSize & 0xFFFF0000) != 0)
8946       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8947           .addReg(Vtmp)
8948           .addImm(LoopSize >> 16)
8949           .add(predOps(ARMCC::AL));
8950   } else {
8951     MachineConstantPool *ConstantPool = MF->getConstantPool();
8952     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8953     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8954 
8955     // MachineConstantPool wants an explicit alignment.
8956     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8957     if (Align == 0)
8958       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8959     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8960 
8961     if (IsThumb)
8962       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
8963           .addReg(varEnd, RegState::Define)
8964           .addConstantPoolIndex(Idx)
8965           .add(predOps(ARMCC::AL));
8966     else
8967       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
8968           .addReg(varEnd, RegState::Define)
8969           .addConstantPoolIndex(Idx)
8970           .addImm(0)
8971           .add(predOps(ARMCC::AL));
8972   }
8973   BB->addSuccessor(loopMBB);
8974 
8975   // Generate the loop body:
8976   //   varPhi = PHI(varLoop, varEnd)
8977   //   srcPhi = PHI(srcLoop, src)
8978   //   destPhi = PHI(destLoop, dst)
8979   MachineBasicBlock *entryBB = BB;
8980   BB = loopMBB;
8981   unsigned varLoop = MRI.createVirtualRegister(TRC);
8982   unsigned varPhi = MRI.createVirtualRegister(TRC);
8983   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8984   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8985   unsigned destLoop = MRI.createVirtualRegister(TRC);
8986   unsigned destPhi = MRI.createVirtualRegister(TRC);
8987 
8988   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8989     .addReg(varLoop).addMBB(loopMBB)
8990     .addReg(varEnd).addMBB(entryBB);
8991   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8992     .addReg(srcLoop).addMBB(loopMBB)
8993     .addReg(src).addMBB(entryBB);
8994   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8995     .addReg(destLoop).addMBB(loopMBB)
8996     .addReg(dest).addMBB(entryBB);
8997 
8998   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8999   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
9000   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9001   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
9002              IsThumb1, IsThumb2);
9003   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
9004              IsThumb1, IsThumb2);
9005 
9006   // Decrement loop variable by UnitSize.
9007   if (IsThumb1) {
9008     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
9009         .add(t1CondCodeOp())
9010         .addReg(varPhi)
9011         .addImm(UnitSize)
9012         .add(predOps(ARMCC::AL));
9013   } else {
9014     MachineInstrBuilder MIB =
9015         BuildMI(*BB, BB->end(), dl,
9016                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
9017     MIB.addReg(varPhi)
9018         .addImm(UnitSize)
9019         .add(predOps(ARMCC::AL))
9020         .add(condCodeOp());
9021     MIB->getOperand(5).setReg(ARM::CPSR);
9022     MIB->getOperand(5).setIsDef(true);
9023   }
9024   BuildMI(*BB, BB->end(), dl,
9025           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
9026       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
9027 
9028   // loopMBB can loop back to loopMBB or fall through to exitMBB.
9029   BB->addSuccessor(loopMBB);
9030   BB->addSuccessor(exitMBB);
9031 
9032   // Add epilogue to handle BytesLeft.
9033   BB = exitMBB;
9034   auto StartOfExit = exitMBB->begin();
9035 
9036   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9037   //   [destOut] = STRB_POST(scratch, destLoop, 1)
9038   unsigned srcIn = srcLoop;
9039   unsigned destIn = destLoop;
9040   for (unsigned i = 0; i < BytesLeft; i++) {
9041     unsigned srcOut = MRI.createVirtualRegister(TRC);
9042     unsigned destOut = MRI.createVirtualRegister(TRC);
9043     unsigned scratch = MRI.createVirtualRegister(TRC);
9044     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
9045                IsThumb1, IsThumb2);
9046     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
9047                IsThumb1, IsThumb2);
9048     srcIn = srcOut;
9049     destIn = destOut;
9050   }
9051 
9052   MI.eraseFromParent(); // The instruction is gone now.
9053   return BB;
9054 }
9055 
9056 MachineBasicBlock *
9057 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
9058                                        MachineBasicBlock *MBB) const {
9059   const TargetMachine &TM = getTargetMachine();
9060   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
9061   DebugLoc DL = MI.getDebugLoc();
9062 
9063   assert(Subtarget->isTargetWindows() &&
9064          "__chkstk is only supported on Windows");
9065   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
9066 
9067   // __chkstk takes the number of words to allocate on the stack in R4, and
9068   // returns the stack adjustment in number of bytes in R4.  This will not
9069   // clober any other registers (other than the obvious lr).
9070   //
9071   // Although, technically, IP should be considered a register which may be
9072   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
9073   // thumb-2 environment, so there is no interworking required.  As a result, we
9074   // do not expect a veneer to be emitted by the linker, clobbering IP.
9075   //
9076   // Each module receives its own copy of __chkstk, so no import thunk is
9077   // required, again, ensuring that IP is not clobbered.
9078   //
9079   // Finally, although some linkers may theoretically provide a trampoline for
9080   // out of range calls (which is quite common due to a 32M range limitation of
9081   // branches for Thumb), we can generate the long-call version via
9082   // -mcmodel=large, alleviating the need for the trampoline which may clobber
9083   // IP.
9084 
9085   switch (TM.getCodeModel()) {
9086   case CodeModel::Tiny:
9087     llvm_unreachable("Tiny code model not available on ARM.");
9088   case CodeModel::Small:
9089   case CodeModel::Medium:
9090   case CodeModel::Kernel:
9091     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
9092         .add(predOps(ARMCC::AL))
9093         .addExternalSymbol("__chkstk")
9094         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9095         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9096         .addReg(ARM::R12,
9097                 RegState::Implicit | RegState::Define | RegState::Dead)
9098         .addReg(ARM::CPSR,
9099                 RegState::Implicit | RegState::Define | RegState::Dead);
9100     break;
9101   case CodeModel::Large: {
9102     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9103     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
9104 
9105     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
9106       .addExternalSymbol("__chkstk");
9107     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
9108         .add(predOps(ARMCC::AL))
9109         .addReg(Reg, RegState::Kill)
9110         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9111         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9112         .addReg(ARM::R12,
9113                 RegState::Implicit | RegState::Define | RegState::Dead)
9114         .addReg(ARM::CPSR,
9115                 RegState::Implicit | RegState::Define | RegState::Dead);
9116     break;
9117   }
9118   }
9119 
9120   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
9121       .addReg(ARM::SP, RegState::Kill)
9122       .addReg(ARM::R4, RegState::Kill)
9123       .setMIFlags(MachineInstr::FrameSetup)
9124       .add(predOps(ARMCC::AL))
9125       .add(condCodeOp());
9126 
9127   MI.eraseFromParent();
9128   return MBB;
9129 }
9130 
9131 MachineBasicBlock *
9132 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
9133                                        MachineBasicBlock *MBB) const {
9134   DebugLoc DL = MI.getDebugLoc();
9135   MachineFunction *MF = MBB->getParent();
9136   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9137 
9138   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
9139   MF->insert(++MBB->getIterator(), ContBB);
9140   ContBB->splice(ContBB->begin(), MBB,
9141                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9142   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
9143   MBB->addSuccessor(ContBB);
9144 
9145   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9146   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
9147   MF->push_back(TrapBB);
9148   MBB->addSuccessor(TrapBB);
9149 
9150   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
9151       .addReg(MI.getOperand(0).getReg())
9152       .addImm(0)
9153       .add(predOps(ARMCC::AL));
9154   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
9155       .addMBB(TrapBB)
9156       .addImm(ARMCC::EQ)
9157       .addReg(ARM::CPSR);
9158 
9159   MI.eraseFromParent();
9160   return ContBB;
9161 }
9162 
9163 MachineBasicBlock *
9164 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9165                                                MachineBasicBlock *BB) const {
9166   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9167   DebugLoc dl = MI.getDebugLoc();
9168   bool isThumb2 = Subtarget->isThumb2();
9169   switch (MI.getOpcode()) {
9170   default: {
9171     MI.print(errs());
9172     llvm_unreachable("Unexpected instr type to insert");
9173   }
9174 
9175   // Thumb1 post-indexed loads are really just single-register LDMs.
9176   case ARM::tLDR_postidx: {
9177     MachineOperand Def(MI.getOperand(1));
9178     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
9179         .add(Def)  // Rn_wb
9180         .add(MI.getOperand(2))  // Rn
9181         .add(MI.getOperand(3))  // PredImm
9182         .add(MI.getOperand(4))  // PredReg
9183         .add(MI.getOperand(0)); // Rt
9184     MI.eraseFromParent();
9185     return BB;
9186   }
9187 
9188   // The Thumb2 pre-indexed stores have the same MI operands, they just
9189   // define them differently in the .td files from the isel patterns, so
9190   // they need pseudos.
9191   case ARM::t2STR_preidx:
9192     MI.setDesc(TII->get(ARM::t2STR_PRE));
9193     return BB;
9194   case ARM::t2STRB_preidx:
9195     MI.setDesc(TII->get(ARM::t2STRB_PRE));
9196     return BB;
9197   case ARM::t2STRH_preidx:
9198     MI.setDesc(TII->get(ARM::t2STRH_PRE));
9199     return BB;
9200 
9201   case ARM::STRi_preidx:
9202   case ARM::STRBi_preidx: {
9203     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9204                                                          : ARM::STRB_PRE_IMM;
9205     // Decode the offset.
9206     unsigned Offset = MI.getOperand(4).getImm();
9207     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
9208     Offset = ARM_AM::getAM2Offset(Offset);
9209     if (isSub)
9210       Offset = -Offset;
9211 
9212     MachineMemOperand *MMO = *MI.memoperands_begin();
9213     BuildMI(*BB, MI, dl, TII->get(NewOpc))
9214         .add(MI.getOperand(0)) // Rn_wb
9215         .add(MI.getOperand(1)) // Rt
9216         .add(MI.getOperand(2)) // Rn
9217         .addImm(Offset)        // offset (skip GPR==zero_reg)
9218         .add(MI.getOperand(5)) // pred
9219         .add(MI.getOperand(6))
9220         .addMemOperand(MMO);
9221     MI.eraseFromParent();
9222     return BB;
9223   }
9224   case ARM::STRr_preidx:
9225   case ARM::STRBr_preidx:
9226   case ARM::STRH_preidx: {
9227     unsigned NewOpc;
9228     switch (MI.getOpcode()) {
9229     default: llvm_unreachable("unexpected opcode!");
9230     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
9231     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
9232     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
9233     }
9234     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
9235     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
9236       MIB.add(MI.getOperand(i));
9237     MI.eraseFromParent();
9238     return BB;
9239   }
9240 
9241   case ARM::tMOVCCr_pseudo: {
9242     // To "insert" a SELECT_CC instruction, we actually have to insert the
9243     // diamond control-flow pattern.  The incoming instruction knows the
9244     // destination vreg to set, the condition code register to branch on, the
9245     // true/false values to select between, and a branch opcode to use.
9246     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9247     MachineFunction::iterator It = ++BB->getIterator();
9248 
9249     //  thisMBB:
9250     //  ...
9251     //   TrueVal = ...
9252     //   cmpTY ccX, r1, r2
9253     //   bCC copy1MBB
9254     //   fallthrough --> copy0MBB
9255     MachineBasicBlock *thisMBB  = BB;
9256     MachineFunction *F = BB->getParent();
9257     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9258     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
9259     F->insert(It, copy0MBB);
9260     F->insert(It, sinkMBB);
9261 
9262     // Transfer the remainder of BB and its successor edges to sinkMBB.
9263     sinkMBB->splice(sinkMBB->begin(), BB,
9264                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9265     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9266 
9267     BB->addSuccessor(copy0MBB);
9268     BB->addSuccessor(sinkMBB);
9269 
9270     BuildMI(BB, dl, TII->get(ARM::tBcc))
9271         .addMBB(sinkMBB)
9272         .addImm(MI.getOperand(3).getImm())
9273         .addReg(MI.getOperand(4).getReg());
9274 
9275     //  copy0MBB:
9276     //   %FalseValue = ...
9277     //   # fallthrough to sinkMBB
9278     BB = copy0MBB;
9279 
9280     // Update machine-CFG edges
9281     BB->addSuccessor(sinkMBB);
9282 
9283     //  sinkMBB:
9284     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9285     //  ...
9286     BB = sinkMBB;
9287     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
9288         .addReg(MI.getOperand(1).getReg())
9289         .addMBB(copy0MBB)
9290         .addReg(MI.getOperand(2).getReg())
9291         .addMBB(thisMBB);
9292 
9293     MI.eraseFromParent(); // The pseudo instruction is gone now.
9294     return BB;
9295   }
9296 
9297   case ARM::BCCi64:
9298   case ARM::BCCZi64: {
9299     // If there is an unconditional branch to the other successor, remove it.
9300     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9301 
9302     // Compare both parts that make up the double comparison separately for
9303     // equality.
9304     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9305 
9306     unsigned LHS1 = MI.getOperand(1).getReg();
9307     unsigned LHS2 = MI.getOperand(2).getReg();
9308     if (RHSisZero) {
9309       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9310           .addReg(LHS1)
9311           .addImm(0)
9312           .add(predOps(ARMCC::AL));
9313       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9314         .addReg(LHS2).addImm(0)
9315         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9316     } else {
9317       unsigned RHS1 = MI.getOperand(3).getReg();
9318       unsigned RHS2 = MI.getOperand(4).getReg();
9319       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9320           .addReg(LHS1)
9321           .addReg(RHS1)
9322           .add(predOps(ARMCC::AL));
9323       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9324         .addReg(LHS2).addReg(RHS2)
9325         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9326     }
9327 
9328     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9329     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9330     if (MI.getOperand(0).getImm() == ARMCC::NE)
9331       std::swap(destMBB, exitMBB);
9332 
9333     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9334       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9335     if (isThumb2)
9336       BuildMI(BB, dl, TII->get(ARM::t2B))
9337           .addMBB(exitMBB)
9338           .add(predOps(ARMCC::AL));
9339     else
9340       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9341 
9342     MI.eraseFromParent(); // The pseudo instruction is gone now.
9343     return BB;
9344   }
9345 
9346   case ARM::Int_eh_sjlj_setjmp:
9347   case ARM::Int_eh_sjlj_setjmp_nofp:
9348   case ARM::tInt_eh_sjlj_setjmp:
9349   case ARM::t2Int_eh_sjlj_setjmp:
9350   case ARM::t2Int_eh_sjlj_setjmp_nofp:
9351     return BB;
9352 
9353   case ARM::Int_eh_sjlj_setup_dispatch:
9354     EmitSjLjDispatchBlock(MI, BB);
9355     return BB;
9356 
9357   case ARM::ABS:
9358   case ARM::t2ABS: {
9359     // To insert an ABS instruction, we have to insert the
9360     // diamond control-flow pattern.  The incoming instruction knows the
9361     // source vreg to test against 0, the destination vreg to set,
9362     // the condition code register to branch on, the
9363     // true/false values to select between, and a branch opcode to use.
9364     // It transforms
9365     //     V1 = ABS V0
9366     // into
9367     //     V2 = MOVS V0
9368     //     BCC                      (branch to SinkBB if V0 >= 0)
9369     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
9370     //     SinkBB: V1 = PHI(V2, V3)
9371     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9372     MachineFunction::iterator BBI = ++BB->getIterator();
9373     MachineFunction *Fn = BB->getParent();
9374     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9375     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
9376     Fn->insert(BBI, RSBBB);
9377     Fn->insert(BBI, SinkBB);
9378 
9379     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9380     unsigned int ABSDstReg = MI.getOperand(0).getReg();
9381     bool ABSSrcKIll = MI.getOperand(1).isKill();
9382     bool isThumb2 = Subtarget->isThumb2();
9383     MachineRegisterInfo &MRI = Fn->getRegInfo();
9384     // In Thumb mode S must not be specified if source register is the SP or
9385     // PC and if destination register is the SP, so restrict register class
9386     unsigned NewRsbDstReg =
9387       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9388 
9389     // Transfer the remainder of BB and its successor edges to sinkMBB.
9390     SinkBB->splice(SinkBB->begin(), BB,
9391                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9392     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9393 
9394     BB->addSuccessor(RSBBB);
9395     BB->addSuccessor(SinkBB);
9396 
9397     // fall through to SinkMBB
9398     RSBBB->addSuccessor(SinkBB);
9399 
9400     // insert a cmp at the end of BB
9401     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9402         .addReg(ABSSrcReg)
9403         .addImm(0)
9404         .add(predOps(ARMCC::AL));
9405 
9406     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9407     BuildMI(BB, dl,
9408       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9409       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9410 
9411     // insert rsbri in RSBBB
9412     // Note: BCC and rsbri will be converted into predicated rsbmi
9413     // by if-conversion pass
9414     BuildMI(*RSBBB, RSBBB->begin(), dl,
9415             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9416         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9417         .addImm(0)
9418         .add(predOps(ARMCC::AL))
9419         .add(condCodeOp());
9420 
9421     // insert PHI in SinkBB,
9422     // reuse ABSDstReg to not change uses of ABS instruction
9423     BuildMI(*SinkBB, SinkBB->begin(), dl,
9424       TII->get(ARM::PHI), ABSDstReg)
9425       .addReg(NewRsbDstReg).addMBB(RSBBB)
9426       .addReg(ABSSrcReg).addMBB(BB);
9427 
9428     // remove ABS instruction
9429     MI.eraseFromParent();
9430 
9431     // return last added BB
9432     return SinkBB;
9433   }
9434   case ARM::COPY_STRUCT_BYVAL_I32:
9435     ++NumLoopByVals;
9436     return EmitStructByval(MI, BB);
9437   case ARM::WIN__CHKSTK:
9438     return EmitLowered__chkstk(MI, BB);
9439   case ARM::WIN__DBZCHK:
9440     return EmitLowered__dbzchk(MI, BB);
9441   }
9442 }
9443 
9444 /// Attaches vregs to MEMCPY that it will use as scratch registers
9445 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9446 /// instead of as a custom inserter because we need the use list from the SDNode.
9447 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9448                                     MachineInstr &MI, const SDNode *Node) {
9449   bool isThumb1 = Subtarget->isThumb1Only();
9450 
9451   DebugLoc DL = MI.getDebugLoc();
9452   MachineFunction *MF = MI.getParent()->getParent();
9453   MachineRegisterInfo &MRI = MF->getRegInfo();
9454   MachineInstrBuilder MIB(*MF, MI);
9455 
9456   // If the new dst/src is unused mark it as dead.
9457   if (!Node->hasAnyUseOfValue(0)) {
9458     MI.getOperand(0).setIsDead(true);
9459   }
9460   if (!Node->hasAnyUseOfValue(1)) {
9461     MI.getOperand(1).setIsDead(true);
9462   }
9463 
9464   // The MEMCPY both defines and kills the scratch registers.
9465   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9466     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9467                                                          : &ARM::GPRRegClass);
9468     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9469   }
9470 }
9471 
9472 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9473                                                       SDNode *Node) const {
9474   if (MI.getOpcode() == ARM::MEMCPY) {
9475     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9476     return;
9477   }
9478 
9479   const MCInstrDesc *MCID = &MI.getDesc();
9480   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9481   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9482   // operand is still set to noreg. If needed, set the optional operand's
9483   // register to CPSR, and remove the redundant implicit def.
9484   //
9485   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
9486 
9487   // Rename pseudo opcodes.
9488   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9489   unsigned ccOutIdx;
9490   if (NewOpc) {
9491     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9492     MCID = &TII->get(NewOpc);
9493 
9494     assert(MCID->getNumOperands() ==
9495            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9496         && "converted opcode should be the same except for cc_out"
9497            " (and, on Thumb1, pred)");
9498 
9499     MI.setDesc(*MCID);
9500 
9501     // Add the optional cc_out operand
9502     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9503 
9504     // On Thumb1, move all input operands to the end, then add the predicate
9505     if (Subtarget->isThumb1Only()) {
9506       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9507         MI.addOperand(MI.getOperand(1));
9508         MI.RemoveOperand(1);
9509       }
9510 
9511       // Restore the ties
9512       for (unsigned i = MI.getNumOperands(); i--;) {
9513         const MachineOperand& op = MI.getOperand(i);
9514         if (op.isReg() && op.isUse()) {
9515           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9516           if (DefIdx != -1)
9517             MI.tieOperands(DefIdx, i);
9518         }
9519       }
9520 
9521       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9522       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9523       ccOutIdx = 1;
9524     } else
9525       ccOutIdx = MCID->getNumOperands() - 1;
9526   } else
9527     ccOutIdx = MCID->getNumOperands() - 1;
9528 
9529   // Any ARM instruction that sets the 's' bit should specify an optional
9530   // "cc_out" operand in the last operand position.
9531   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9532     assert(!NewOpc && "Optional cc_out operand required");
9533     return;
9534   }
9535   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9536   // since we already have an optional CPSR def.
9537   bool definesCPSR = false;
9538   bool deadCPSR = false;
9539   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9540        ++i) {
9541     const MachineOperand &MO = MI.getOperand(i);
9542     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9543       definesCPSR = true;
9544       if (MO.isDead())
9545         deadCPSR = true;
9546       MI.RemoveOperand(i);
9547       break;
9548     }
9549   }
9550   if (!definesCPSR) {
9551     assert(!NewOpc && "Optional cc_out operand required");
9552     return;
9553   }
9554   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9555   if (deadCPSR) {
9556     assert(!MI.getOperand(ccOutIdx).getReg() &&
9557            "expect uninitialized optional cc_out operand");
9558     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9559     if (!Subtarget->isThumb1Only())
9560       return;
9561   }
9562 
9563   // If this instruction was defined with an optional CPSR def and its dag node
9564   // had a live implicit CPSR def, then activate the optional CPSR def.
9565   MachineOperand &MO = MI.getOperand(ccOutIdx);
9566   MO.setReg(ARM::CPSR);
9567   MO.setIsDef(true);
9568 }
9569 
9570 //===----------------------------------------------------------------------===//
9571 //                           ARM Optimization Hooks
9572 //===----------------------------------------------------------------------===//
9573 
9574 // Helper function that checks if N is a null or all ones constant.
9575 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9576   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9577 }
9578 
9579 // Return true if N is conditionally 0 or all ones.
9580 // Detects these expressions where cc is an i1 value:
9581 //
9582 //   (select cc 0, y)   [AllOnes=0]
9583 //   (select cc y, 0)   [AllOnes=0]
9584 //   (zext cc)          [AllOnes=0]
9585 //   (sext cc)          [AllOnes=0/1]
9586 //   (select cc -1, y)  [AllOnes=1]
9587 //   (select cc y, -1)  [AllOnes=1]
9588 //
9589 // Invert is set when N is the null/all ones constant when CC is false.
9590 // OtherOp is set to the alternative value of N.
9591 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9592                                        SDValue &CC, bool &Invert,
9593                                        SDValue &OtherOp,
9594                                        SelectionDAG &DAG) {
9595   switch (N->getOpcode()) {
9596   default: return false;
9597   case ISD::SELECT: {
9598     CC = N->getOperand(0);
9599     SDValue N1 = N->getOperand(1);
9600     SDValue N2 = N->getOperand(2);
9601     if (isZeroOrAllOnes(N1, AllOnes)) {
9602       Invert = false;
9603       OtherOp = N2;
9604       return true;
9605     }
9606     if (isZeroOrAllOnes(N2, AllOnes)) {
9607       Invert = true;
9608       OtherOp = N1;
9609       return true;
9610     }
9611     return false;
9612   }
9613   case ISD::ZERO_EXTEND:
9614     // (zext cc) can never be the all ones value.
9615     if (AllOnes)
9616       return false;
9617     LLVM_FALLTHROUGH;
9618   case ISD::SIGN_EXTEND: {
9619     SDLoc dl(N);
9620     EVT VT = N->getValueType(0);
9621     CC = N->getOperand(0);
9622     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9623       return false;
9624     Invert = !AllOnes;
9625     if (AllOnes)
9626       // When looking for an AllOnes constant, N is an sext, and the 'other'
9627       // value is 0.
9628       OtherOp = DAG.getConstant(0, dl, VT);
9629     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9630       // When looking for a 0 constant, N can be zext or sext.
9631       OtherOp = DAG.getConstant(1, dl, VT);
9632     else
9633       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9634                                 VT);
9635     return true;
9636   }
9637   }
9638 }
9639 
9640 // Combine a constant select operand into its use:
9641 //
9642 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9643 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9644 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9645 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9646 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9647 //
9648 // The transform is rejected if the select doesn't have a constant operand that
9649 // is null, or all ones when AllOnes is set.
9650 //
9651 // Also recognize sext/zext from i1:
9652 //
9653 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9654 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9655 //
9656 // These transformations eventually create predicated instructions.
9657 //
9658 // @param N       The node to transform.
9659 // @param Slct    The N operand that is a select.
9660 // @param OtherOp The other N operand (x above).
9661 // @param DCI     Context.
9662 // @param AllOnes Require the select constant to be all ones instead of null.
9663 // @returns The new node, or SDValue() on failure.
9664 static
9665 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9666                             TargetLowering::DAGCombinerInfo &DCI,
9667                             bool AllOnes = false) {
9668   SelectionDAG &DAG = DCI.DAG;
9669   EVT VT = N->getValueType(0);
9670   SDValue NonConstantVal;
9671   SDValue CCOp;
9672   bool SwapSelectOps;
9673   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9674                                   NonConstantVal, DAG))
9675     return SDValue();
9676 
9677   // Slct is now know to be the desired identity constant when CC is true.
9678   SDValue TrueVal = OtherOp;
9679   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9680                                  OtherOp, NonConstantVal);
9681   // Unless SwapSelectOps says CC should be false.
9682   if (SwapSelectOps)
9683     std::swap(TrueVal, FalseVal);
9684 
9685   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9686                      CCOp, TrueVal, FalseVal);
9687 }
9688 
9689 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9690 static
9691 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9692                                        TargetLowering::DAGCombinerInfo &DCI) {
9693   SDValue N0 = N->getOperand(0);
9694   SDValue N1 = N->getOperand(1);
9695   if (N0.getNode()->hasOneUse())
9696     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9697       return Result;
9698   if (N1.getNode()->hasOneUse())
9699     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9700       return Result;
9701   return SDValue();
9702 }
9703 
9704 static bool IsVUZPShuffleNode(SDNode *N) {
9705   // VUZP shuffle node.
9706   if (N->getOpcode() == ARMISD::VUZP)
9707     return true;
9708 
9709   // "VUZP" on i32 is an alias for VTRN.
9710   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9711     return true;
9712 
9713   return false;
9714 }
9715 
9716 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9717                                  TargetLowering::DAGCombinerInfo &DCI,
9718                                  const ARMSubtarget *Subtarget) {
9719   // Look for ADD(VUZP.0, VUZP.1).
9720   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9721       N0 == N1)
9722    return SDValue();
9723 
9724   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9725   if (!N->getValueType(0).is64BitVector())
9726     return SDValue();
9727 
9728   // Generate vpadd.
9729   SelectionDAG &DAG = DCI.DAG;
9730   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9731   SDLoc dl(N);
9732   SDNode *Unzip = N0.getNode();
9733   EVT VT = N->getValueType(0);
9734 
9735   SmallVector<SDValue, 8> Ops;
9736   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9737                                 TLI.getPointerTy(DAG.getDataLayout())));
9738   Ops.push_back(Unzip->getOperand(0));
9739   Ops.push_back(Unzip->getOperand(1));
9740 
9741   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9742 }
9743 
9744 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9745                                       TargetLowering::DAGCombinerInfo &DCI,
9746                                       const ARMSubtarget *Subtarget) {
9747   // Check for two extended operands.
9748   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9749         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9750       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9751         N1.getOpcode() == ISD::ZERO_EXTEND))
9752     return SDValue();
9753 
9754   SDValue N00 = N0.getOperand(0);
9755   SDValue N10 = N1.getOperand(0);
9756 
9757   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9758   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9759       N00 == N10)
9760     return SDValue();
9761 
9762   // We only recognize Q register paddl here; this can't be reached until
9763   // after type legalization.
9764   if (!N00.getValueType().is64BitVector() ||
9765       !N0.getValueType().is128BitVector())
9766     return SDValue();
9767 
9768   // Generate vpaddl.
9769   SelectionDAG &DAG = DCI.DAG;
9770   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9771   SDLoc dl(N);
9772   EVT VT = N->getValueType(0);
9773 
9774   SmallVector<SDValue, 8> Ops;
9775   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9776   unsigned Opcode;
9777   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9778     Opcode = Intrinsic::arm_neon_vpaddls;
9779   else
9780     Opcode = Intrinsic::arm_neon_vpaddlu;
9781   Ops.push_back(DAG.getConstant(Opcode, dl,
9782                                 TLI.getPointerTy(DAG.getDataLayout())));
9783   EVT ElemTy = N00.getValueType().getVectorElementType();
9784   unsigned NumElts = VT.getVectorNumElements();
9785   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9786   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9787                                N00.getOperand(0), N00.getOperand(1));
9788   Ops.push_back(Concat);
9789 
9790   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9791 }
9792 
9793 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9794 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9795 // much easier to match.
9796 static SDValue
9797 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9798                                TargetLowering::DAGCombinerInfo &DCI,
9799                                const ARMSubtarget *Subtarget) {
9800   // Only perform optimization if after legalize, and if NEON is available. We
9801   // also expected both operands to be BUILD_VECTORs.
9802   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9803       || N0.getOpcode() != ISD::BUILD_VECTOR
9804       || N1.getOpcode() != ISD::BUILD_VECTOR)
9805     return SDValue();
9806 
9807   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9808   EVT VT = N->getValueType(0);
9809   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9810     return SDValue();
9811 
9812   // Check that the vector operands are of the right form.
9813   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9814   // operands, where N is the size of the formed vector.
9815   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9816   // index such that we have a pair wise add pattern.
9817 
9818   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9819   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9820     return SDValue();
9821   SDValue Vec = N0->getOperand(0)->getOperand(0);
9822   SDNode *V = Vec.getNode();
9823   unsigned nextIndex = 0;
9824 
9825   // For each operands to the ADD which are BUILD_VECTORs,
9826   // check to see if each of their operands are an EXTRACT_VECTOR with
9827   // the same vector and appropriate index.
9828   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9829     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9830         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9831 
9832       SDValue ExtVec0 = N0->getOperand(i);
9833       SDValue ExtVec1 = N1->getOperand(i);
9834 
9835       // First operand is the vector, verify its the same.
9836       if (V != ExtVec0->getOperand(0).getNode() ||
9837           V != ExtVec1->getOperand(0).getNode())
9838         return SDValue();
9839 
9840       // Second is the constant, verify its correct.
9841       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9842       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9843 
9844       // For the constant, we want to see all the even or all the odd.
9845       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9846           || C1->getZExtValue() != nextIndex+1)
9847         return SDValue();
9848 
9849       // Increment index.
9850       nextIndex+=2;
9851     } else
9852       return SDValue();
9853   }
9854 
9855   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9856   // we're using the entire input vector, otherwise there's a size/legality
9857   // mismatch somewhere.
9858   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9859       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9860     return SDValue();
9861 
9862   // Create VPADDL node.
9863   SelectionDAG &DAG = DCI.DAG;
9864   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9865 
9866   SDLoc dl(N);
9867 
9868   // Build operand list.
9869   SmallVector<SDValue, 8> Ops;
9870   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9871                                 TLI.getPointerTy(DAG.getDataLayout())));
9872 
9873   // Input is the vector.
9874   Ops.push_back(Vec);
9875 
9876   // Get widened type and narrowed type.
9877   MVT widenType;
9878   unsigned numElem = VT.getVectorNumElements();
9879 
9880   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9881   switch (inputLaneType.getSimpleVT().SimpleTy) {
9882     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9883     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9884     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9885     default:
9886       llvm_unreachable("Invalid vector element type for padd optimization.");
9887   }
9888 
9889   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9890   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9891   return DAG.getNode(ExtOp, dl, VT, tmp);
9892 }
9893 
9894 static SDValue findMUL_LOHI(SDValue V) {
9895   if (V->getOpcode() == ISD::UMUL_LOHI ||
9896       V->getOpcode() == ISD::SMUL_LOHI)
9897     return V;
9898   return SDValue();
9899 }
9900 
9901 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9902                                         TargetLowering::DAGCombinerInfo &DCI,
9903                                         const ARMSubtarget *Subtarget) {
9904   if (Subtarget->isThumb()) {
9905     if (!Subtarget->hasDSP())
9906       return SDValue();
9907   } else if (!Subtarget->hasV5TEOps())
9908     return SDValue();
9909 
9910   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
9911   // accumulates the product into a 64-bit value. The 16-bit values will
9912   // be sign extended somehow or SRA'd into 32-bit values
9913   // (addc (adde (mul 16bit, 16bit), lo), hi)
9914   SDValue Mul = AddcNode->getOperand(0);
9915   SDValue Lo = AddcNode->getOperand(1);
9916   if (Mul.getOpcode() != ISD::MUL) {
9917     Lo = AddcNode->getOperand(0);
9918     Mul = AddcNode->getOperand(1);
9919     if (Mul.getOpcode() != ISD::MUL)
9920       return SDValue();
9921   }
9922 
9923   SDValue SRA = AddeNode->getOperand(0);
9924   SDValue Hi = AddeNode->getOperand(1);
9925   if (SRA.getOpcode() != ISD::SRA) {
9926     SRA = AddeNode->getOperand(1);
9927     Hi = AddeNode->getOperand(0);
9928     if (SRA.getOpcode() != ISD::SRA)
9929       return SDValue();
9930   }
9931   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
9932     if (Const->getZExtValue() != 31)
9933       return SDValue();
9934   } else
9935     return SDValue();
9936 
9937   if (SRA.getOperand(0) != Mul)
9938     return SDValue();
9939 
9940   SelectionDAG &DAG = DCI.DAG;
9941   SDLoc dl(AddcNode);
9942   unsigned Opcode = 0;
9943   SDValue Op0;
9944   SDValue Op1;
9945 
9946   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
9947     Opcode = ARMISD::SMLALBB;
9948     Op0 = Mul.getOperand(0);
9949     Op1 = Mul.getOperand(1);
9950   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
9951     Opcode = ARMISD::SMLALBT;
9952     Op0 = Mul.getOperand(0);
9953     Op1 = Mul.getOperand(1).getOperand(0);
9954   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
9955     Opcode = ARMISD::SMLALTB;
9956     Op0 = Mul.getOperand(0).getOperand(0);
9957     Op1 = Mul.getOperand(1);
9958   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
9959     Opcode = ARMISD::SMLALTT;
9960     Op0 = Mul->getOperand(0).getOperand(0);
9961     Op1 = Mul->getOperand(1).getOperand(0);
9962   }
9963 
9964   if (!Op0 || !Op1)
9965     return SDValue();
9966 
9967   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
9968                               Op0, Op1, Lo, Hi);
9969   // Replace the ADDs' nodes uses by the MLA node's values.
9970   SDValue HiMLALResult(SMLAL.getNode(), 1);
9971   SDValue LoMLALResult(SMLAL.getNode(), 0);
9972 
9973   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9974   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9975 
9976   // Return original node to notify the driver to stop replacing.
9977   SDValue resNode(AddcNode, 0);
9978   return resNode;
9979 }
9980 
9981 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
9982                                      TargetLowering::DAGCombinerInfo &DCI,
9983                                      const ARMSubtarget *Subtarget) {
9984   // Look for multiply add opportunities.
9985   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9986   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9987   // a glue link from the first add to the second add.
9988   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9989   // a S/UMLAL instruction.
9990   //                  UMUL_LOHI
9991   //                 / :lo    \ :hi
9992   //                V          \          [no multiline comment]
9993   //    loAdd ->  ADDC         |
9994   //                 \ :carry /
9995   //                  V      V
9996   //                    ADDE   <- hiAdd
9997   //
9998   // In the special case where only the higher part of a signed result is used
9999   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
10000   // a constant with the exact value of 0x80000000, we recognize we are dealing
10001   // with a "rounded multiply and add" (or subtract) and transform it into
10002   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
10003 
10004   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
10005           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
10006          "Expect an ADDE or SUBE");
10007 
10008   assert(AddeSubeNode->getNumOperands() == 3 &&
10009          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
10010          "ADDE node has the wrong inputs");
10011 
10012   // Check that we are chained to the right ADDC or SUBC node.
10013   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
10014   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10015        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
10016       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
10017        AddcSubcNode->getOpcode() != ARMISD::SUBC))
10018     return SDValue();
10019 
10020   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
10021   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
10022 
10023   // Check if the two operands are from the same mul_lohi node.
10024   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
10025     return SDValue();
10026 
10027   assert(AddcSubcNode->getNumValues() == 2 &&
10028          AddcSubcNode->getValueType(0) == MVT::i32 &&
10029          "Expect ADDC with two result values. First: i32");
10030 
10031   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
10032   // maybe a SMLAL which multiplies two 16-bit values.
10033   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10034       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
10035       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
10036       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
10037       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
10038     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
10039 
10040   // Check for the triangle shape.
10041   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
10042   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
10043 
10044   // Make sure that the ADDE/SUBE operands are not coming from the same node.
10045   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
10046     return SDValue();
10047 
10048   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
10049   bool IsLeftOperandMUL = false;
10050   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
10051   if (MULOp == SDValue())
10052     MULOp = findMUL_LOHI(AddeSubeOp1);
10053   else
10054     IsLeftOperandMUL = true;
10055   if (MULOp == SDValue())
10056     return SDValue();
10057 
10058   // Figure out the right opcode.
10059   unsigned Opc = MULOp->getOpcode();
10060   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
10061 
10062   // Figure out the high and low input values to the MLAL node.
10063   SDValue *HiAddSub = nullptr;
10064   SDValue *LoMul = nullptr;
10065   SDValue *LowAddSub = nullptr;
10066 
10067   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
10068   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
10069     return SDValue();
10070 
10071   if (IsLeftOperandMUL)
10072     HiAddSub = &AddeSubeOp1;
10073   else
10074     HiAddSub = &AddeSubeOp0;
10075 
10076   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
10077   // whose low result is fed to the ADDC/SUBC we are checking.
10078 
10079   if (AddcSubcOp0 == MULOp.getValue(0)) {
10080     LoMul = &AddcSubcOp0;
10081     LowAddSub = &AddcSubcOp1;
10082   }
10083   if (AddcSubcOp1 == MULOp.getValue(0)) {
10084     LoMul = &AddcSubcOp1;
10085     LowAddSub = &AddcSubcOp0;
10086   }
10087 
10088   if (!LoMul)
10089     return SDValue();
10090 
10091   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
10092   // the replacement below will create a cycle.
10093   if (AddcSubcNode == HiAddSub->getNode() ||
10094       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
10095     return SDValue();
10096 
10097   // Create the merged node.
10098   SelectionDAG &DAG = DCI.DAG;
10099 
10100   // Start building operand list.
10101   SmallVector<SDValue, 8> Ops;
10102   Ops.push_back(LoMul->getOperand(0));
10103   Ops.push_back(LoMul->getOperand(1));
10104 
10105   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
10106   // the case, we must be doing signed multiplication and only use the higher
10107   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
10108   // addition or subtraction with the value of 0x800000.
10109   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
10110       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
10111       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
10112       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
10113           0x80000000) {
10114     Ops.push_back(*HiAddSub);
10115     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
10116       FinalOpc = ARMISD::SMMLSR;
10117     } else {
10118       FinalOpc = ARMISD::SMMLAR;
10119     }
10120     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
10121     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
10122 
10123     return SDValue(AddeSubeNode, 0);
10124   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
10125     // SMMLS is generated during instruction selection and the rest of this
10126     // function can not handle the case where AddcSubcNode is a SUBC.
10127     return SDValue();
10128 
10129   // Finish building the operand list for {U/S}MLAL
10130   Ops.push_back(*LowAddSub);
10131   Ops.push_back(*HiAddSub);
10132 
10133   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
10134                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10135 
10136   // Replace the ADDs' nodes uses by the MLA node's values.
10137   SDValue HiMLALResult(MLALNode.getNode(), 1);
10138   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
10139 
10140   SDValue LoMLALResult(MLALNode.getNode(), 0);
10141   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
10142 
10143   // Return original node to notify the driver to stop replacing.
10144   return SDValue(AddeSubeNode, 0);
10145 }
10146 
10147 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
10148                                       TargetLowering::DAGCombinerInfo &DCI,
10149                                       const ARMSubtarget *Subtarget) {
10150   // UMAAL is similar to UMLAL except that it adds two unsigned values.
10151   // While trying to combine for the other MLAL nodes, first search for the
10152   // chance to use UMAAL. Check if Addc uses a node which has already
10153   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
10154   // as the addend, and it's handled in PerformUMLALCombine.
10155 
10156   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10157     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10158 
10159   // Check that we have a glued ADDC node.
10160   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
10161   if (AddcNode->getOpcode() != ARMISD::ADDC)
10162     return SDValue();
10163 
10164   // Find the converted UMAAL or quit if it doesn't exist.
10165   SDNode *UmlalNode = nullptr;
10166   SDValue AddHi;
10167   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
10168     UmlalNode = AddcNode->getOperand(0).getNode();
10169     AddHi = AddcNode->getOperand(1);
10170   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
10171     UmlalNode = AddcNode->getOperand(1).getNode();
10172     AddHi = AddcNode->getOperand(0);
10173   } else {
10174     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10175   }
10176 
10177   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
10178   // the ADDC as well as Zero.
10179   if (!isNullConstant(UmlalNode->getOperand(3)))
10180     return SDValue();
10181 
10182   if ((isNullConstant(AddeNode->getOperand(0)) &&
10183        AddeNode->getOperand(1).getNode() == UmlalNode) ||
10184       (AddeNode->getOperand(0).getNode() == UmlalNode &&
10185        isNullConstant(AddeNode->getOperand(1)))) {
10186     SelectionDAG &DAG = DCI.DAG;
10187     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
10188                       UmlalNode->getOperand(2), AddHi };
10189     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
10190                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10191 
10192     // Replace the ADDs' nodes uses by the UMAAL node's values.
10193     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
10194     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
10195 
10196     // Return original node to notify the driver to stop replacing.
10197     return SDValue(AddeNode, 0);
10198   }
10199   return SDValue();
10200 }
10201 
10202 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
10203                                    const ARMSubtarget *Subtarget) {
10204   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10205     return SDValue();
10206 
10207   // Check that we have a pair of ADDC and ADDE as operands.
10208   // Both addends of the ADDE must be zero.
10209   SDNode* AddcNode = N->getOperand(2).getNode();
10210   SDNode* AddeNode = N->getOperand(3).getNode();
10211   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
10212       (AddeNode->getOpcode() == ARMISD::ADDE) &&
10213       isNullConstant(AddeNode->getOperand(0)) &&
10214       isNullConstant(AddeNode->getOperand(1)) &&
10215       (AddeNode->getOperand(2).getNode() == AddcNode))
10216     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
10217                        DAG.getVTList(MVT::i32, MVT::i32),
10218                        {N->getOperand(0), N->getOperand(1),
10219                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
10220   else
10221     return SDValue();
10222 }
10223 
10224 static SDValue PerformAddcSubcCombine(SDNode *N,
10225                                       TargetLowering::DAGCombinerInfo &DCI,
10226                                       const ARMSubtarget *Subtarget) {
10227   SelectionDAG &DAG(DCI.DAG);
10228 
10229   if (N->getOpcode() == ARMISD::SUBC) {
10230     // (SUBC (ADDE 0, 0, C), 1) -> C
10231     SDValue LHS = N->getOperand(0);
10232     SDValue RHS = N->getOperand(1);
10233     if (LHS->getOpcode() == ARMISD::ADDE &&
10234         isNullConstant(LHS->getOperand(0)) &&
10235         isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
10236       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
10237     }
10238   }
10239 
10240   if (Subtarget->isThumb1Only()) {
10241     SDValue RHS = N->getOperand(1);
10242     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10243       int32_t imm = C->getSExtValue();
10244       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
10245         SDLoc DL(N);
10246         RHS = DAG.getConstant(-imm, DL, MVT::i32);
10247         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
10248                                                            : ARMISD::ADDC;
10249         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
10250       }
10251     }
10252   }
10253 
10254   return SDValue();
10255 }
10256 
10257 static SDValue PerformAddeSubeCombine(SDNode *N,
10258                                       TargetLowering::DAGCombinerInfo &DCI,
10259                                       const ARMSubtarget *Subtarget) {
10260   if (Subtarget->isThumb1Only()) {
10261     SelectionDAG &DAG = DCI.DAG;
10262     SDValue RHS = N->getOperand(1);
10263     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10264       int64_t imm = C->getSExtValue();
10265       if (imm < 0) {
10266         SDLoc DL(N);
10267 
10268         // The with-carry-in form matches bitwise not instead of the negation.
10269         // Effectively, the inverse interpretation of the carry flag already
10270         // accounts for part of the negation.
10271         RHS = DAG.getConstant(~imm, DL, MVT::i32);
10272 
10273         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
10274                                                            : ARMISD::ADDE;
10275         return DAG.getNode(Opcode, DL, N->getVTList(),
10276                            N->getOperand(0), RHS, N->getOperand(2));
10277       }
10278     }
10279   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
10280     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
10281   }
10282   return SDValue();
10283 }
10284 
10285 /// PerformADDECombine - Target-specific dag combine transform from
10286 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
10287 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
10288 static SDValue PerformADDECombine(SDNode *N,
10289                                   TargetLowering::DAGCombinerInfo &DCI,
10290                                   const ARMSubtarget *Subtarget) {
10291   // Only ARM and Thumb2 support UMLAL/SMLAL.
10292   if (Subtarget->isThumb1Only())
10293     return PerformAddeSubeCombine(N, DCI, Subtarget);
10294 
10295   // Only perform the checks after legalize when the pattern is available.
10296   if (DCI.isBeforeLegalize()) return SDValue();
10297 
10298   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
10299 }
10300 
10301 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
10302 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
10303 /// called with the default operands, and if that fails, with commuted
10304 /// operands.
10305 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
10306                                           TargetLowering::DAGCombinerInfo &DCI,
10307                                           const ARMSubtarget *Subtarget){
10308   // Attempt to create vpadd for this add.
10309   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
10310     return Result;
10311 
10312   // Attempt to create vpaddl for this add.
10313   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
10314     return Result;
10315   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
10316                                                       Subtarget))
10317     return Result;
10318 
10319   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10320   if (N0.getNode()->hasOneUse())
10321     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
10322       return Result;
10323   return SDValue();
10324 }
10325 
10326 bool
10327 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
10328                                                  CombineLevel Level) const {
10329   if (Level == BeforeLegalizeTypes)
10330     return true;
10331 
10332   if (Subtarget->isThumb() && Subtarget->isThumb1Only())
10333     return true;
10334 
10335   if (N->getOpcode() != ISD::SHL)
10336     return true;
10337 
10338   // Turn off commute-with-shift transform after legalization, so it doesn't
10339   // conflict with PerformSHLSimplify.  (We could try to detect when
10340   // PerformSHLSimplify would trigger more precisely, but it isn't
10341   // really necessary.)
10342   return false;
10343 }
10344 
10345 static SDValue PerformSHLSimplify(SDNode *N,
10346                                 TargetLowering::DAGCombinerInfo &DCI,
10347                                 const ARMSubtarget *ST) {
10348   // Allow the generic combiner to identify potential bswaps.
10349   if (DCI.isBeforeLegalize())
10350     return SDValue();
10351 
10352   // DAG combiner will fold:
10353   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
10354   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
10355   // Other code patterns that can be also be modified have the following form:
10356   // b + ((a << 1) | 510)
10357   // b + ((a << 1) & 510)
10358   // b + ((a << 1) ^ 510)
10359   // b + ((a << 1) + 510)
10360 
10361   // Many instructions can  perform the shift for free, but it requires both
10362   // the operands to be registers. If c1 << c2 is too large, a mov immediate
10363   // instruction will needed. So, unfold back to the original pattern if:
10364   // - if c1 and c2 are small enough that they don't require mov imms.
10365   // - the user(s) of the node can perform an shl
10366 
10367   // No shifted operands for 16-bit instructions.
10368   if (ST->isThumb() && ST->isThumb1Only())
10369     return SDValue();
10370 
10371   // Check that all the users could perform the shl themselves.
10372   for (auto U : N->uses()) {
10373     switch(U->getOpcode()) {
10374     default:
10375       return SDValue();
10376     case ISD::SUB:
10377     case ISD::ADD:
10378     case ISD::AND:
10379     case ISD::OR:
10380     case ISD::XOR:
10381     case ISD::SETCC:
10382     case ARMISD::CMP:
10383       // Check that the user isn't already using a constant because there
10384       // aren't any instructions that support an immediate operand and a
10385       // shifted operand.
10386       if (isa<ConstantSDNode>(U->getOperand(0)) ||
10387           isa<ConstantSDNode>(U->getOperand(1)))
10388         return SDValue();
10389 
10390       // Check that it's not already using a shift.
10391       if (U->getOperand(0).getOpcode() == ISD::SHL ||
10392           U->getOperand(1).getOpcode() == ISD::SHL)
10393         return SDValue();
10394       break;
10395     }
10396   }
10397 
10398   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
10399       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
10400     return SDValue();
10401 
10402   if (N->getOperand(0).getOpcode() != ISD::SHL)
10403     return SDValue();
10404 
10405   SDValue SHL = N->getOperand(0);
10406 
10407   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
10408   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
10409   if (!C1ShlC2 || !C2)
10410     return SDValue();
10411 
10412   APInt C2Int = C2->getAPIntValue();
10413   APInt C1Int = C1ShlC2->getAPIntValue();
10414 
10415   // Check that performing a lshr will not lose any information.
10416   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
10417                                      C2Int.getBitWidth() - C2->getZExtValue());
10418   if ((C1Int & Mask) != C1Int)
10419     return SDValue();
10420 
10421   // Shift the first constant.
10422   C1Int.lshrInPlace(C2Int);
10423 
10424   // The immediates are encoded as an 8-bit value that can be rotated.
10425   auto LargeImm = [](const APInt &Imm) {
10426     unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
10427     return Imm.getBitWidth() - Zeros > 8;
10428   };
10429 
10430   if (LargeImm(C1Int) || LargeImm(C2Int))
10431     return SDValue();
10432 
10433   SelectionDAG &DAG = DCI.DAG;
10434   SDLoc dl(N);
10435   SDValue X = SHL.getOperand(0);
10436   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
10437                               DAG.getConstant(C1Int, dl, MVT::i32));
10438   // Shift left to compensate for the lshr of C1Int.
10439   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
10440 
10441   LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
10442              SHL.dump(); N->dump());
10443   LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
10444   return Res;
10445 }
10446 
10447 
10448 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
10449 ///
10450 static SDValue PerformADDCombine(SDNode *N,
10451                                  TargetLowering::DAGCombinerInfo &DCI,
10452                                  const ARMSubtarget *Subtarget) {
10453   SDValue N0 = N->getOperand(0);
10454   SDValue N1 = N->getOperand(1);
10455 
10456   // Only works one way, because it needs an immediate operand.
10457   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10458     return Result;
10459 
10460   // First try with the default operand order.
10461   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
10462     return Result;
10463 
10464   // If that didn't work, try again with the operands commuted.
10465   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
10466 }
10467 
10468 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
10469 ///
10470 static SDValue PerformSUBCombine(SDNode *N,
10471                                  TargetLowering::DAGCombinerInfo &DCI) {
10472   SDValue N0 = N->getOperand(0);
10473   SDValue N1 = N->getOperand(1);
10474 
10475   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10476   if (N1.getNode()->hasOneUse())
10477     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10478       return Result;
10479 
10480   return SDValue();
10481 }
10482 
10483 /// PerformVMULCombine
10484 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10485 /// special multiplier accumulator forwarding.
10486 ///   vmul d3, d0, d2
10487 ///   vmla d3, d1, d2
10488 /// is faster than
10489 ///   vadd d3, d0, d1
10490 ///   vmul d3, d3, d2
10491 //  However, for (A + B) * (A + B),
10492 //    vadd d2, d0, d1
10493 //    vmul d3, d0, d2
10494 //    vmla d3, d1, d2
10495 //  is slower than
10496 //    vadd d2, d0, d1
10497 //    vmul d3, d2, d2
10498 static SDValue PerformVMULCombine(SDNode *N,
10499                                   TargetLowering::DAGCombinerInfo &DCI,
10500                                   const ARMSubtarget *Subtarget) {
10501   if (!Subtarget->hasVMLxForwarding())
10502     return SDValue();
10503 
10504   SelectionDAG &DAG = DCI.DAG;
10505   SDValue N0 = N->getOperand(0);
10506   SDValue N1 = N->getOperand(1);
10507   unsigned Opcode = N0.getOpcode();
10508   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10509       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10510     Opcode = N1.getOpcode();
10511     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10512         Opcode != ISD::FADD && Opcode != ISD::FSUB)
10513       return SDValue();
10514     std::swap(N0, N1);
10515   }
10516 
10517   if (N0 == N1)
10518     return SDValue();
10519 
10520   EVT VT = N->getValueType(0);
10521   SDLoc DL(N);
10522   SDValue N00 = N0->getOperand(0);
10523   SDValue N01 = N0->getOperand(1);
10524   return DAG.getNode(Opcode, DL, VT,
10525                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10526                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10527 }
10528 
10529 static SDValue PerformMULCombine(SDNode *N,
10530                                  TargetLowering::DAGCombinerInfo &DCI,
10531                                  const ARMSubtarget *Subtarget) {
10532   SelectionDAG &DAG = DCI.DAG;
10533 
10534   if (Subtarget->isThumb1Only())
10535     return SDValue();
10536 
10537   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10538     return SDValue();
10539 
10540   EVT VT = N->getValueType(0);
10541   if (VT.is64BitVector() || VT.is128BitVector())
10542     return PerformVMULCombine(N, DCI, Subtarget);
10543   if (VT != MVT::i32)
10544     return SDValue();
10545 
10546   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10547   if (!C)
10548     return SDValue();
10549 
10550   int64_t MulAmt = C->getSExtValue();
10551   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10552 
10553   ShiftAmt = ShiftAmt & (32 - 1);
10554   SDValue V = N->getOperand(0);
10555   SDLoc DL(N);
10556 
10557   SDValue Res;
10558   MulAmt >>= ShiftAmt;
10559 
10560   if (MulAmt >= 0) {
10561     if (isPowerOf2_32(MulAmt - 1)) {
10562       // (mul x, 2^N + 1) => (add (shl x, N), x)
10563       Res = DAG.getNode(ISD::ADD, DL, VT,
10564                         V,
10565                         DAG.getNode(ISD::SHL, DL, VT,
10566                                     V,
10567                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
10568                                                     MVT::i32)));
10569     } else if (isPowerOf2_32(MulAmt + 1)) {
10570       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10571       Res = DAG.getNode(ISD::SUB, DL, VT,
10572                         DAG.getNode(ISD::SHL, DL, VT,
10573                                     V,
10574                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10575                                                     MVT::i32)),
10576                         V);
10577     } else
10578       return SDValue();
10579   } else {
10580     uint64_t MulAmtAbs = -MulAmt;
10581     if (isPowerOf2_32(MulAmtAbs + 1)) {
10582       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10583       Res = DAG.getNode(ISD::SUB, DL, VT,
10584                         V,
10585                         DAG.getNode(ISD::SHL, DL, VT,
10586                                     V,
10587                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10588                                                     MVT::i32)));
10589     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10590       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10591       Res = DAG.getNode(ISD::ADD, DL, VT,
10592                         V,
10593                         DAG.getNode(ISD::SHL, DL, VT,
10594                                     V,
10595                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10596                                                     MVT::i32)));
10597       Res = DAG.getNode(ISD::SUB, DL, VT,
10598                         DAG.getConstant(0, DL, MVT::i32), Res);
10599     } else
10600       return SDValue();
10601   }
10602 
10603   if (ShiftAmt != 0)
10604     Res = DAG.getNode(ISD::SHL, DL, VT,
10605                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10606 
10607   // Do not add new nodes to DAG combiner worklist.
10608   DCI.CombineTo(N, Res, false);
10609   return SDValue();
10610 }
10611 
10612 static SDValue CombineANDShift(SDNode *N,
10613                                TargetLowering::DAGCombinerInfo &DCI,
10614                                const ARMSubtarget *Subtarget) {
10615   // Allow DAGCombine to pattern-match before we touch the canonical form.
10616   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10617     return SDValue();
10618 
10619   if (N->getValueType(0) != MVT::i32)
10620     return SDValue();
10621 
10622   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10623   if (!N1C)
10624     return SDValue();
10625 
10626   uint32_t C1 = (uint32_t)N1C->getZExtValue();
10627   // Don't transform uxtb/uxth.
10628   if (C1 == 255 || C1 == 65535)
10629     return SDValue();
10630 
10631   SDNode *N0 = N->getOperand(0).getNode();
10632   if (!N0->hasOneUse())
10633     return SDValue();
10634 
10635   if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
10636     return SDValue();
10637 
10638   bool LeftShift = N0->getOpcode() == ISD::SHL;
10639 
10640   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10641   if (!N01C)
10642     return SDValue();
10643 
10644   uint32_t C2 = (uint32_t)N01C->getZExtValue();
10645   if (!C2 || C2 >= 32)
10646     return SDValue();
10647 
10648   SelectionDAG &DAG = DCI.DAG;
10649   SDLoc DL(N);
10650 
10651   // We have a pattern of the form "(and (shl x, c2) c1)" or
10652   // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
10653   // transform to a pair of shifts, to save materializing c1.
10654 
10655   // First pattern: right shift, and c1+1 is a power of two.
10656   // FIXME: Also check reversed pattern (left shift, and ~c1+1 is a power
10657   // of two).
10658   // FIXME: Use demanded bits?
10659   if (!LeftShift && isMask_32(C1)) {
10660     uint32_t C3 = countLeadingZeros(C1);
10661     if (C2 < C3) {
10662       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
10663                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
10664       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
10665                          DAG.getConstant(C3, DL, MVT::i32));
10666     }
10667   }
10668 
10669   // Second pattern: left shift, and (c1>>c2)+1 is a power of two.
10670   // FIXME: Also check reversed pattern (right shift, and ~(c1<<c2)+1
10671   // is a power of two).
10672   // FIXME: Use demanded bits?
10673   if (LeftShift && isShiftedMask_32(C1)) {
10674     uint32_t C3 = countLeadingZeros(C1);
10675     if (C2 + C3 < 32 && C1 == ((-1U << (C2 + C3)) >> C3)) {
10676       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
10677                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
10678       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
10679                         DAG.getConstant(C3, DL, MVT::i32));
10680     }
10681   }
10682 
10683   // FIXME: Transform "(and (shl x, c2) c1)" ->
10684   // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
10685   // c1.
10686   return SDValue();
10687 }
10688 
10689 static SDValue PerformANDCombine(SDNode *N,
10690                                  TargetLowering::DAGCombinerInfo &DCI,
10691                                  const ARMSubtarget *Subtarget) {
10692   // Attempt to use immediate-form VBIC
10693   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10694   SDLoc dl(N);
10695   EVT VT = N->getValueType(0);
10696   SelectionDAG &DAG = DCI.DAG;
10697 
10698   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10699     return SDValue();
10700 
10701   APInt SplatBits, SplatUndef;
10702   unsigned SplatBitSize;
10703   bool HasAnyUndefs;
10704   if (BVN &&
10705       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10706     if (SplatBitSize <= 64) {
10707       EVT VbicVT;
10708       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10709                                       SplatUndef.getZExtValue(), SplatBitSize,
10710                                       DAG, dl, VbicVT, VT.is128BitVector(),
10711                                       OtherModImm);
10712       if (Val.getNode()) {
10713         SDValue Input =
10714           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10715         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10716         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10717       }
10718     }
10719   }
10720 
10721   if (!Subtarget->isThumb1Only()) {
10722     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10723     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10724       return Result;
10725 
10726     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10727       return Result;
10728   }
10729 
10730   if (Subtarget->isThumb1Only())
10731     if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
10732       return Result;
10733 
10734   return SDValue();
10735 }
10736 
10737 // Try combining OR nodes to SMULWB, SMULWT.
10738 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10739                                          TargetLowering::DAGCombinerInfo &DCI,
10740                                          const ARMSubtarget *Subtarget) {
10741   if (!Subtarget->hasV6Ops() ||
10742       (Subtarget->isThumb() &&
10743        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10744     return SDValue();
10745 
10746   SDValue SRL = OR->getOperand(0);
10747   SDValue SHL = OR->getOperand(1);
10748 
10749   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10750     SRL = OR->getOperand(1);
10751     SHL = OR->getOperand(0);
10752   }
10753   if (!isSRL16(SRL) || !isSHL16(SHL))
10754     return SDValue();
10755 
10756   // The first operands to the shifts need to be the two results from the
10757   // same smul_lohi node.
10758   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10759        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10760     return SDValue();
10761 
10762   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10763   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10764       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10765     return SDValue();
10766 
10767   // Now we have:
10768   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10769   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10770   // For SMUWB the 16-bit value will signed extended somehow.
10771   // For SMULWT only the SRA is required.
10772   // Check both sides of SMUL_LOHI
10773   SDValue OpS16 = SMULLOHI->getOperand(0);
10774   SDValue OpS32 = SMULLOHI->getOperand(1);
10775 
10776   SelectionDAG &DAG = DCI.DAG;
10777   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10778     OpS16 = OpS32;
10779     OpS32 = SMULLOHI->getOperand(0);
10780   }
10781 
10782   SDLoc dl(OR);
10783   unsigned Opcode = 0;
10784   if (isS16(OpS16, DAG))
10785     Opcode = ARMISD::SMULWB;
10786   else if (isSRA16(OpS16)) {
10787     Opcode = ARMISD::SMULWT;
10788     OpS16 = OpS16->getOperand(0);
10789   }
10790   else
10791     return SDValue();
10792 
10793   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10794   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10795   return SDValue(OR, 0);
10796 }
10797 
10798 static SDValue PerformORCombineToBFI(SDNode *N,
10799                                      TargetLowering::DAGCombinerInfo &DCI,
10800                                      const ARMSubtarget *Subtarget) {
10801   // BFI is only available on V6T2+
10802   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10803     return SDValue();
10804 
10805   EVT VT = N->getValueType(0);
10806   SDValue N0 = N->getOperand(0);
10807   SDValue N1 = N->getOperand(1);
10808   SelectionDAG &DAG = DCI.DAG;
10809   SDLoc DL(N);
10810   // 1) or (and A, mask), val => ARMbfi A, val, mask
10811   //      iff (val & mask) == val
10812   //
10813   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10814   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10815   //          && mask == ~mask2
10816   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10817   //          && ~mask == mask2
10818   //  (i.e., copy a bitfield value into another bitfield of the same width)
10819 
10820   if (VT != MVT::i32)
10821     return SDValue();
10822 
10823   SDValue N00 = N0.getOperand(0);
10824 
10825   // The value and the mask need to be constants so we can verify this is
10826   // actually a bitfield set. If the mask is 0xffff, we can do better
10827   // via a movt instruction, so don't use BFI in that case.
10828   SDValue MaskOp = N0.getOperand(1);
10829   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10830   if (!MaskC)
10831     return SDValue();
10832   unsigned Mask = MaskC->getZExtValue();
10833   if (Mask == 0xffff)
10834     return SDValue();
10835   SDValue Res;
10836   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10837   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10838   if (N1C) {
10839     unsigned Val = N1C->getZExtValue();
10840     if ((Val & ~Mask) != Val)
10841       return SDValue();
10842 
10843     if (ARM::isBitFieldInvertedMask(Mask)) {
10844       Val >>= countTrailingZeros(~Mask);
10845 
10846       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10847                         DAG.getConstant(Val, DL, MVT::i32),
10848                         DAG.getConstant(Mask, DL, MVT::i32));
10849 
10850       DCI.CombineTo(N, Res, false);
10851       // Return value from the original node to inform the combiner than N is
10852       // now dead.
10853       return SDValue(N, 0);
10854     }
10855   } else if (N1.getOpcode() == ISD::AND) {
10856     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10857     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10858     if (!N11C)
10859       return SDValue();
10860     unsigned Mask2 = N11C->getZExtValue();
10861 
10862     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10863     // as is to match.
10864     if (ARM::isBitFieldInvertedMask(Mask) &&
10865         (Mask == ~Mask2)) {
10866       // The pack halfword instruction works better for masks that fit it,
10867       // so use that when it's available.
10868       if (Subtarget->hasDSP() &&
10869           (Mask == 0xffff || Mask == 0xffff0000))
10870         return SDValue();
10871       // 2a
10872       unsigned amt = countTrailingZeros(Mask2);
10873       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10874                         DAG.getConstant(amt, DL, MVT::i32));
10875       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10876                         DAG.getConstant(Mask, DL, MVT::i32));
10877       DCI.CombineTo(N, Res, false);
10878       // Return value from the original node to inform the combiner than N is
10879       // now dead.
10880       return SDValue(N, 0);
10881     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10882                (~Mask == Mask2)) {
10883       // The pack halfword instruction works better for masks that fit it,
10884       // so use that when it's available.
10885       if (Subtarget->hasDSP() &&
10886           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10887         return SDValue();
10888       // 2b
10889       unsigned lsb = countTrailingZeros(Mask);
10890       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10891                         DAG.getConstant(lsb, DL, MVT::i32));
10892       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10893                         DAG.getConstant(Mask2, DL, MVT::i32));
10894       DCI.CombineTo(N, Res, false);
10895       // Return value from the original node to inform the combiner than N is
10896       // now dead.
10897       return SDValue(N, 0);
10898     }
10899   }
10900 
10901   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10902       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10903       ARM::isBitFieldInvertedMask(~Mask)) {
10904     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10905     // where lsb(mask) == #shamt and masked bits of B are known zero.
10906     SDValue ShAmt = N00.getOperand(1);
10907     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10908     unsigned LSB = countTrailingZeros(Mask);
10909     if (ShAmtC != LSB)
10910       return SDValue();
10911 
10912     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10913                       DAG.getConstant(~Mask, DL, MVT::i32));
10914 
10915     DCI.CombineTo(N, Res, false);
10916     // Return value from the original node to inform the combiner than N is
10917     // now dead.
10918     return SDValue(N, 0);
10919   }
10920 
10921   return SDValue();
10922 }
10923 
10924 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
10925 static SDValue PerformORCombine(SDNode *N,
10926                                 TargetLowering::DAGCombinerInfo &DCI,
10927                                 const ARMSubtarget *Subtarget) {
10928   // Attempt to use immediate-form VORR
10929   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10930   SDLoc dl(N);
10931   EVT VT = N->getValueType(0);
10932   SelectionDAG &DAG = DCI.DAG;
10933 
10934   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10935     return SDValue();
10936 
10937   APInt SplatBits, SplatUndef;
10938   unsigned SplatBitSize;
10939   bool HasAnyUndefs;
10940   if (BVN && Subtarget->hasNEON() &&
10941       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10942     if (SplatBitSize <= 64) {
10943       EVT VorrVT;
10944       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
10945                                       SplatUndef.getZExtValue(), SplatBitSize,
10946                                       DAG, dl, VorrVT, VT.is128BitVector(),
10947                                       OtherModImm);
10948       if (Val.getNode()) {
10949         SDValue Input =
10950           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
10951         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
10952         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
10953       }
10954     }
10955   }
10956 
10957   if (!Subtarget->isThumb1Only()) {
10958     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10959     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10960       return Result;
10961     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
10962       return Result;
10963   }
10964 
10965   SDValue N0 = N->getOperand(0);
10966   SDValue N1 = N->getOperand(1);
10967 
10968   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
10969   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
10970       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10971 
10972     // The code below optimizes (or (and X, Y), Z).
10973     // The AND operand needs to have a single user to make these optimizations
10974     // profitable.
10975     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
10976       return SDValue();
10977 
10978     APInt SplatUndef;
10979     unsigned SplatBitSize;
10980     bool HasAnyUndefs;
10981 
10982     APInt SplatBits0, SplatBits1;
10983     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
10984     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
10985     // Ensure that the second operand of both ands are constants
10986     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
10987                                       HasAnyUndefs) && !HasAnyUndefs) {
10988         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
10989                                           HasAnyUndefs) && !HasAnyUndefs) {
10990             // Ensure that the bit width of the constants are the same and that
10991             // the splat arguments are logical inverses as per the pattern we
10992             // are trying to simplify.
10993             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
10994                 SplatBits0 == ~SplatBits1) {
10995                 // Canonicalize the vector type to make instruction selection
10996                 // simpler.
10997                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
10998                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
10999                                              N0->getOperand(1),
11000                                              N0->getOperand(0),
11001                                              N1->getOperand(0));
11002                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11003             }
11004         }
11005     }
11006   }
11007 
11008   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
11009   // reasonable.
11010   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
11011     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
11012       return Res;
11013   }
11014 
11015   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11016     return Result;
11017 
11018   return SDValue();
11019 }
11020 
11021 static SDValue PerformXORCombine(SDNode *N,
11022                                  TargetLowering::DAGCombinerInfo &DCI,
11023                                  const ARMSubtarget *Subtarget) {
11024   EVT VT = N->getValueType(0);
11025   SelectionDAG &DAG = DCI.DAG;
11026 
11027   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11028     return SDValue();
11029 
11030   if (!Subtarget->isThumb1Only()) {
11031     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
11032     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11033       return Result;
11034 
11035     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11036       return Result;
11037   }
11038 
11039   return SDValue();
11040 }
11041 
11042 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
11043 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
11044 // their position in "to" (Rd).
11045 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
11046   assert(N->getOpcode() == ARMISD::BFI);
11047 
11048   SDValue From = N->getOperand(1);
11049   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
11050   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
11051 
11052   // If the Base came from a SHR #C, we can deduce that it is really testing bit
11053   // #C in the base of the SHR.
11054   if (From->getOpcode() == ISD::SRL &&
11055       isa<ConstantSDNode>(From->getOperand(1))) {
11056     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
11057     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
11058     FromMask <<= Shift.getLimitedValue(31);
11059     From = From->getOperand(0);
11060   }
11061 
11062   return From;
11063 }
11064 
11065 // If A and B contain one contiguous set of bits, does A | B == A . B?
11066 //
11067 // Neither A nor B must be zero.
11068 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
11069   unsigned LastActiveBitInA =  A.countTrailingZeros();
11070   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
11071   return LastActiveBitInA - 1 == FirstActiveBitInB;
11072 }
11073 
11074 static SDValue FindBFIToCombineWith(SDNode *N) {
11075   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
11076   // if one exists.
11077   APInt ToMask, FromMask;
11078   SDValue From = ParseBFI(N, ToMask, FromMask);
11079   SDValue To = N->getOperand(0);
11080 
11081   // Now check for a compatible BFI to merge with. We can pass through BFIs that
11082   // aren't compatible, but not if they set the same bit in their destination as
11083   // we do (or that of any BFI we're going to combine with).
11084   SDValue V = To;
11085   APInt CombinedToMask = ToMask;
11086   while (V.getOpcode() == ARMISD::BFI) {
11087     APInt NewToMask, NewFromMask;
11088     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
11089     if (NewFrom != From) {
11090       // This BFI has a different base. Keep going.
11091       CombinedToMask |= NewToMask;
11092       V = V.getOperand(0);
11093       continue;
11094     }
11095 
11096     // Do the written bits conflict with any we've seen so far?
11097     if ((NewToMask & CombinedToMask).getBoolValue())
11098       // Conflicting bits - bail out because going further is unsafe.
11099       return SDValue();
11100 
11101     // Are the new bits contiguous when combined with the old bits?
11102     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
11103         BitsProperlyConcatenate(FromMask, NewFromMask))
11104       return V;
11105     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
11106         BitsProperlyConcatenate(NewFromMask, FromMask))
11107       return V;
11108 
11109     // We've seen a write to some bits, so track it.
11110     CombinedToMask |= NewToMask;
11111     // Keep going...
11112     V = V.getOperand(0);
11113   }
11114 
11115   return SDValue();
11116 }
11117 
11118 static SDValue PerformBFICombine(SDNode *N,
11119                                  TargetLowering::DAGCombinerInfo &DCI) {
11120   SDValue N1 = N->getOperand(1);
11121   if (N1.getOpcode() == ISD::AND) {
11122     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
11123     // the bits being cleared by the AND are not demanded by the BFI.
11124     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11125     if (!N11C)
11126       return SDValue();
11127     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11128     unsigned LSB = countTrailingZeros(~InvMask);
11129     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
11130     assert(Width <
11131                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
11132            "undefined behavior");
11133     unsigned Mask = (1u << Width) - 1;
11134     unsigned Mask2 = N11C->getZExtValue();
11135     if ((Mask & (~Mask2)) == 0)
11136       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
11137                              N->getOperand(0), N1.getOperand(0),
11138                              N->getOperand(2));
11139   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
11140     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
11141     // Keep track of any consecutive bits set that all come from the same base
11142     // value. We can combine these together into a single BFI.
11143     SDValue CombineBFI = FindBFIToCombineWith(N);
11144     if (CombineBFI == SDValue())
11145       return SDValue();
11146 
11147     // We've found a BFI.
11148     APInt ToMask1, FromMask1;
11149     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
11150 
11151     APInt ToMask2, FromMask2;
11152     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
11153     assert(From1 == From2);
11154     (void)From2;
11155 
11156     // First, unlink CombineBFI.
11157     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
11158     // Then create a new BFI, combining the two together.
11159     APInt NewFromMask = FromMask1 | FromMask2;
11160     APInt NewToMask = ToMask1 | ToMask2;
11161 
11162     EVT VT = N->getValueType(0);
11163     SDLoc dl(N);
11164 
11165     if (NewFromMask[0] == 0)
11166       From1 = DCI.DAG.getNode(
11167         ISD::SRL, dl, VT, From1,
11168         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
11169     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
11170                            DCI.DAG.getConstant(~NewToMask, dl, VT));
11171   }
11172   return SDValue();
11173 }
11174 
11175 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
11176 /// ARMISD::VMOVRRD.
11177 static SDValue PerformVMOVRRDCombine(SDNode *N,
11178                                      TargetLowering::DAGCombinerInfo &DCI,
11179                                      const ARMSubtarget *Subtarget) {
11180   // vmovrrd(vmovdrr x, y) -> x,y
11181   SDValue InDouble = N->getOperand(0);
11182   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
11183     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
11184 
11185   // vmovrrd(load f64) -> (load i32), (load i32)
11186   SDNode *InNode = InDouble.getNode();
11187   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
11188       InNode->getValueType(0) == MVT::f64 &&
11189       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
11190       !cast<LoadSDNode>(InNode)->isVolatile()) {
11191     // TODO: Should this be done for non-FrameIndex operands?
11192     LoadSDNode *LD = cast<LoadSDNode>(InNode);
11193 
11194     SelectionDAG &DAG = DCI.DAG;
11195     SDLoc DL(LD);
11196     SDValue BasePtr = LD->getBasePtr();
11197     SDValue NewLD1 =
11198         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
11199                     LD->getAlignment(), LD->getMemOperand()->getFlags());
11200 
11201     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11202                                     DAG.getConstant(4, DL, MVT::i32));
11203     SDValue NewLD2 = DAG.getLoad(
11204         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
11205         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
11206 
11207     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
11208     if (DCI.DAG.getDataLayout().isBigEndian())
11209       std::swap (NewLD1, NewLD2);
11210     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
11211     return Result;
11212   }
11213 
11214   return SDValue();
11215 }
11216 
11217 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
11218 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
11219 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
11220   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
11221   SDValue Op0 = N->getOperand(0);
11222   SDValue Op1 = N->getOperand(1);
11223   if (Op0.getOpcode() == ISD::BITCAST)
11224     Op0 = Op0.getOperand(0);
11225   if (Op1.getOpcode() == ISD::BITCAST)
11226     Op1 = Op1.getOperand(0);
11227   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
11228       Op0.getNode() == Op1.getNode() &&
11229       Op0.getResNo() == 0 && Op1.getResNo() == 1)
11230     return DAG.getNode(ISD::BITCAST, SDLoc(N),
11231                        N->getValueType(0), Op0.getOperand(0));
11232   return SDValue();
11233 }
11234 
11235 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
11236 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
11237 /// i64 vector to have f64 elements, since the value can then be loaded
11238 /// directly into a VFP register.
11239 static bool hasNormalLoadOperand(SDNode *N) {
11240   unsigned NumElts = N->getValueType(0).getVectorNumElements();
11241   for (unsigned i = 0; i < NumElts; ++i) {
11242     SDNode *Elt = N->getOperand(i).getNode();
11243     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
11244       return true;
11245   }
11246   return false;
11247 }
11248 
11249 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
11250 /// ISD::BUILD_VECTOR.
11251 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
11252                                           TargetLowering::DAGCombinerInfo &DCI,
11253                                           const ARMSubtarget *Subtarget) {
11254   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
11255   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
11256   // into a pair of GPRs, which is fine when the value is used as a scalar,
11257   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
11258   SelectionDAG &DAG = DCI.DAG;
11259   if (N->getNumOperands() == 2)
11260     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
11261       return RV;
11262 
11263   // Load i64 elements as f64 values so that type legalization does not split
11264   // them up into i32 values.
11265   EVT VT = N->getValueType(0);
11266   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
11267     return SDValue();
11268   SDLoc dl(N);
11269   SmallVector<SDValue, 8> Ops;
11270   unsigned NumElts = VT.getVectorNumElements();
11271   for (unsigned i = 0; i < NumElts; ++i) {
11272     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
11273     Ops.push_back(V);
11274     // Make the DAGCombiner fold the bitcast.
11275     DCI.AddToWorklist(V.getNode());
11276   }
11277   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
11278   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
11279   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11280 }
11281 
11282 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
11283 static SDValue
11284 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11285   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
11286   // At that time, we may have inserted bitcasts from integer to float.
11287   // If these bitcasts have survived DAGCombine, change the lowering of this
11288   // BUILD_VECTOR in something more vector friendly, i.e., that does not
11289   // force to use floating point types.
11290 
11291   // Make sure we can change the type of the vector.
11292   // This is possible iff:
11293   // 1. The vector is only used in a bitcast to a integer type. I.e.,
11294   //    1.1. Vector is used only once.
11295   //    1.2. Use is a bit convert to an integer type.
11296   // 2. The size of its operands are 32-bits (64-bits are not legal).
11297   EVT VT = N->getValueType(0);
11298   EVT EltVT = VT.getVectorElementType();
11299 
11300   // Check 1.1. and 2.
11301   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
11302     return SDValue();
11303 
11304   // By construction, the input type must be float.
11305   assert(EltVT == MVT::f32 && "Unexpected type!");
11306 
11307   // Check 1.2.
11308   SDNode *Use = *N->use_begin();
11309   if (Use->getOpcode() != ISD::BITCAST ||
11310       Use->getValueType(0).isFloatingPoint())
11311     return SDValue();
11312 
11313   // Check profitability.
11314   // Model is, if more than half of the relevant operands are bitcast from
11315   // i32, turn the build_vector into a sequence of insert_vector_elt.
11316   // Relevant operands are everything that is not statically
11317   // (i.e., at compile time) bitcasted.
11318   unsigned NumOfBitCastedElts = 0;
11319   unsigned NumElts = VT.getVectorNumElements();
11320   unsigned NumOfRelevantElts = NumElts;
11321   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
11322     SDValue Elt = N->getOperand(Idx);
11323     if (Elt->getOpcode() == ISD::BITCAST) {
11324       // Assume only bit cast to i32 will go away.
11325       if (Elt->getOperand(0).getValueType() == MVT::i32)
11326         ++NumOfBitCastedElts;
11327     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
11328       // Constants are statically casted, thus do not count them as
11329       // relevant operands.
11330       --NumOfRelevantElts;
11331   }
11332 
11333   // Check if more than half of the elements require a non-free bitcast.
11334   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
11335     return SDValue();
11336 
11337   SelectionDAG &DAG = DCI.DAG;
11338   // Create the new vector type.
11339   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
11340   // Check if the type is legal.
11341   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11342   if (!TLI.isTypeLegal(VecVT))
11343     return SDValue();
11344 
11345   // Combine:
11346   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
11347   // => BITCAST INSERT_VECTOR_ELT
11348   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
11349   //                      (BITCAST EN), N.
11350   SDValue Vec = DAG.getUNDEF(VecVT);
11351   SDLoc dl(N);
11352   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
11353     SDValue V = N->getOperand(Idx);
11354     if (V.isUndef())
11355       continue;
11356     if (V.getOpcode() == ISD::BITCAST &&
11357         V->getOperand(0).getValueType() == MVT::i32)
11358       // Fold obvious case.
11359       V = V.getOperand(0);
11360     else {
11361       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
11362       // Make the DAGCombiner fold the bitcasts.
11363       DCI.AddToWorklist(V.getNode());
11364     }
11365     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
11366     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
11367   }
11368   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
11369   // Make the DAGCombiner fold the bitcasts.
11370   DCI.AddToWorklist(Vec.getNode());
11371   return Vec;
11372 }
11373 
11374 /// PerformInsertEltCombine - Target-specific dag combine xforms for
11375 /// ISD::INSERT_VECTOR_ELT.
11376 static SDValue PerformInsertEltCombine(SDNode *N,
11377                                        TargetLowering::DAGCombinerInfo &DCI) {
11378   // Bitcast an i64 load inserted into a vector to f64.
11379   // Otherwise, the i64 value will be legalized to a pair of i32 values.
11380   EVT VT = N->getValueType(0);
11381   SDNode *Elt = N->getOperand(1).getNode();
11382   if (VT.getVectorElementType() != MVT::i64 ||
11383       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
11384     return SDValue();
11385 
11386   SelectionDAG &DAG = DCI.DAG;
11387   SDLoc dl(N);
11388   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11389                                  VT.getVectorNumElements());
11390   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
11391   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
11392   // Make the DAGCombiner fold the bitcasts.
11393   DCI.AddToWorklist(Vec.getNode());
11394   DCI.AddToWorklist(V.getNode());
11395   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
11396                                Vec, V, N->getOperand(2));
11397   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
11398 }
11399 
11400 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
11401 /// ISD::VECTOR_SHUFFLE.
11402 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
11403   // The LLVM shufflevector instruction does not require the shuffle mask
11404   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
11405   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
11406   // operands do not match the mask length, they are extended by concatenating
11407   // them with undef vectors.  That is probably the right thing for other
11408   // targets, but for NEON it is better to concatenate two double-register
11409   // size vector operands into a single quad-register size vector.  Do that
11410   // transformation here:
11411   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
11412   //   shuffle(concat(v1, v2), undef)
11413   SDValue Op0 = N->getOperand(0);
11414   SDValue Op1 = N->getOperand(1);
11415   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
11416       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
11417       Op0.getNumOperands() != 2 ||
11418       Op1.getNumOperands() != 2)
11419     return SDValue();
11420   SDValue Concat0Op1 = Op0.getOperand(1);
11421   SDValue Concat1Op1 = Op1.getOperand(1);
11422   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
11423     return SDValue();
11424   // Skip the transformation if any of the types are illegal.
11425   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11426   EVT VT = N->getValueType(0);
11427   if (!TLI.isTypeLegal(VT) ||
11428       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
11429       !TLI.isTypeLegal(Concat1Op1.getValueType()))
11430     return SDValue();
11431 
11432   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11433                                   Op0.getOperand(0), Op1.getOperand(0));
11434   // Translate the shuffle mask.
11435   SmallVector<int, 16> NewMask;
11436   unsigned NumElts = VT.getVectorNumElements();
11437   unsigned HalfElts = NumElts/2;
11438   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11439   for (unsigned n = 0; n < NumElts; ++n) {
11440     int MaskElt = SVN->getMaskElt(n);
11441     int NewElt = -1;
11442     if (MaskElt < (int)HalfElts)
11443       NewElt = MaskElt;
11444     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
11445       NewElt = HalfElts + MaskElt - NumElts;
11446     NewMask.push_back(NewElt);
11447   }
11448   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
11449                               DAG.getUNDEF(VT), NewMask);
11450 }
11451 
11452 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
11453 /// NEON load/store intrinsics, and generic vector load/stores, to merge
11454 /// base address updates.
11455 /// For generic load/stores, the memory type is assumed to be a vector.
11456 /// The caller is assumed to have checked legality.
11457 static SDValue CombineBaseUpdate(SDNode *N,
11458                                  TargetLowering::DAGCombinerInfo &DCI) {
11459   SelectionDAG &DAG = DCI.DAG;
11460   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
11461                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
11462   const bool isStore = N->getOpcode() == ISD::STORE;
11463   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
11464   SDValue Addr = N->getOperand(AddrOpIdx);
11465   MemSDNode *MemN = cast<MemSDNode>(N);
11466   SDLoc dl(N);
11467 
11468   // Search for a use of the address operand that is an increment.
11469   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11470          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11471     SDNode *User = *UI;
11472     if (User->getOpcode() != ISD::ADD ||
11473         UI.getUse().getResNo() != Addr.getResNo())
11474       continue;
11475 
11476     // Check that the add is independent of the load/store.  Otherwise, folding
11477     // it would create a cycle. We can avoid searching through Addr as it's a
11478     // predecessor to both.
11479     SmallPtrSet<const SDNode *, 32> Visited;
11480     SmallVector<const SDNode *, 16> Worklist;
11481     Visited.insert(Addr.getNode());
11482     Worklist.push_back(N);
11483     Worklist.push_back(User);
11484     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
11485         SDNode::hasPredecessorHelper(User, Visited, Worklist))
11486       continue;
11487 
11488     // Find the new opcode for the updating load/store.
11489     bool isLoadOp = true;
11490     bool isLaneOp = false;
11491     unsigned NewOpc = 0;
11492     unsigned NumVecs = 0;
11493     if (isIntrinsic) {
11494       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11495       switch (IntNo) {
11496       default: llvm_unreachable("unexpected intrinsic for Neon base update");
11497       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
11498         NumVecs = 1; break;
11499       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
11500         NumVecs = 2; break;
11501       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
11502         NumVecs = 3; break;
11503       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
11504         NumVecs = 4; break;
11505       case Intrinsic::arm_neon_vld2dup:
11506       case Intrinsic::arm_neon_vld3dup:
11507       case Intrinsic::arm_neon_vld4dup:
11508         // TODO: Support updating VLDxDUP nodes. For now, we just skip
11509         // combining base updates for such intrinsics.
11510         continue;
11511       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
11512         NumVecs = 2; isLaneOp = true; break;
11513       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
11514         NumVecs = 3; isLaneOp = true; break;
11515       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
11516         NumVecs = 4; isLaneOp = true; break;
11517       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
11518         NumVecs = 1; isLoadOp = false; break;
11519       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
11520         NumVecs = 2; isLoadOp = false; break;
11521       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
11522         NumVecs = 3; isLoadOp = false; break;
11523       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
11524         NumVecs = 4; isLoadOp = false; break;
11525       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
11526         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
11527       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
11528         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
11529       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
11530         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
11531       }
11532     } else {
11533       isLaneOp = true;
11534       switch (N->getOpcode()) {
11535       default: llvm_unreachable("unexpected opcode for Neon base update");
11536       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
11537       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
11538       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
11539       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
11540       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
11541         NumVecs = 1; isLaneOp = false; break;
11542       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
11543         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
11544       }
11545     }
11546 
11547     // Find the size of memory referenced by the load/store.
11548     EVT VecTy;
11549     if (isLoadOp) {
11550       VecTy = N->getValueType(0);
11551     } else if (isIntrinsic) {
11552       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
11553     } else {
11554       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
11555       VecTy = N->getOperand(1).getValueType();
11556     }
11557 
11558     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11559     if (isLaneOp)
11560       NumBytes /= VecTy.getVectorNumElements();
11561 
11562     // If the increment is a constant, it must match the memory ref size.
11563     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11564     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
11565     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
11566       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
11567       // separate instructions that make it harder to use a non-constant update.
11568       continue;
11569     }
11570 
11571     // OK, we found an ADD we can fold into the base update.
11572     // Now, create a _UPD node, taking care of not breaking alignment.
11573 
11574     EVT AlignedVecTy = VecTy;
11575     unsigned Alignment = MemN->getAlignment();
11576 
11577     // If this is a less-than-standard-aligned load/store, change the type to
11578     // match the standard alignment.
11579     // The alignment is overlooked when selecting _UPD variants; and it's
11580     // easier to introduce bitcasts here than fix that.
11581     // There are 3 ways to get to this base-update combine:
11582     // - intrinsics: they are assumed to be properly aligned (to the standard
11583     //   alignment of the memory type), so we don't need to do anything.
11584     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
11585     //   intrinsics, so, likewise, there's nothing to do.
11586     // - generic load/store instructions: the alignment is specified as an
11587     //   explicit operand, rather than implicitly as the standard alignment
11588     //   of the memory type (like the intrisics).  We need to change the
11589     //   memory type to match the explicit alignment.  That way, we don't
11590     //   generate non-standard-aligned ARMISD::VLDx nodes.
11591     if (isa<LSBaseSDNode>(N)) {
11592       if (Alignment == 0)
11593         Alignment = 1;
11594       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
11595         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
11596         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
11597         assert(!isLaneOp && "Unexpected generic load/store lane.");
11598         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
11599         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
11600       }
11601       // Don't set an explicit alignment on regular load/stores that we want
11602       // to transform to VLD/VST 1_UPD nodes.
11603       // This matches the behavior of regular load/stores, which only get an
11604       // explicit alignment if the MMO alignment is larger than the standard
11605       // alignment of the memory type.
11606       // Intrinsics, however, always get an explicit alignment, set to the
11607       // alignment of the MMO.
11608       Alignment = 1;
11609     }
11610 
11611     // Create the new updating load/store node.
11612     // First, create an SDVTList for the new updating node's results.
11613     EVT Tys[6];
11614     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
11615     unsigned n;
11616     for (n = 0; n < NumResultVecs; ++n)
11617       Tys[n] = AlignedVecTy;
11618     Tys[n++] = MVT::i32;
11619     Tys[n] = MVT::Other;
11620     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
11621 
11622     // Then, gather the new node's operands.
11623     SmallVector<SDValue, 8> Ops;
11624     Ops.push_back(N->getOperand(0)); // incoming chain
11625     Ops.push_back(N->getOperand(AddrOpIdx));
11626     Ops.push_back(Inc);
11627 
11628     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
11629       // Try to match the intrinsic's signature
11630       Ops.push_back(StN->getValue());
11631     } else {
11632       // Loads (and of course intrinsics) match the intrinsics' signature,
11633       // so just add all but the alignment operand.
11634       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
11635         Ops.push_back(N->getOperand(i));
11636     }
11637 
11638     // For all node types, the alignment operand is always the last one.
11639     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
11640 
11641     // If this is a non-standard-aligned STORE, the penultimate operand is the
11642     // stored value.  Bitcast it to the aligned type.
11643     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11644       SDValue &StVal = Ops[Ops.size()-2];
11645       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11646     }
11647 
11648     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11649     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11650                                            MemN->getMemOperand());
11651 
11652     // Update the uses.
11653     SmallVector<SDValue, 5> NewResults;
11654     for (unsigned i = 0; i < NumResultVecs; ++i)
11655       NewResults.push_back(SDValue(UpdN.getNode(), i));
11656 
11657     // If this is an non-standard-aligned LOAD, the first result is the loaded
11658     // value.  Bitcast it to the expected result type.
11659     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11660       SDValue &LdVal = NewResults[0];
11661       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11662     }
11663 
11664     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11665     DCI.CombineTo(N, NewResults);
11666     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11667 
11668     break;
11669   }
11670   return SDValue();
11671 }
11672 
11673 static SDValue PerformVLDCombine(SDNode *N,
11674                                  TargetLowering::DAGCombinerInfo &DCI) {
11675   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11676     return SDValue();
11677 
11678   return CombineBaseUpdate(N, DCI);
11679 }
11680 
11681 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11682 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11683 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
11684 /// return true.
11685 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11686   SelectionDAG &DAG = DCI.DAG;
11687   EVT VT = N->getValueType(0);
11688   // vldN-dup instructions only support 64-bit vectors for N > 1.
11689   if (!VT.is64BitVector())
11690     return false;
11691 
11692   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11693   SDNode *VLD = N->getOperand(0).getNode();
11694   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11695     return false;
11696   unsigned NumVecs = 0;
11697   unsigned NewOpc = 0;
11698   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11699   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11700     NumVecs = 2;
11701     NewOpc = ARMISD::VLD2DUP;
11702   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11703     NumVecs = 3;
11704     NewOpc = ARMISD::VLD3DUP;
11705   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11706     NumVecs = 4;
11707     NewOpc = ARMISD::VLD4DUP;
11708   } else {
11709     return false;
11710   }
11711 
11712   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11713   // numbers match the load.
11714   unsigned VLDLaneNo =
11715     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11716   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11717        UI != UE; ++UI) {
11718     // Ignore uses of the chain result.
11719     if (UI.getUse().getResNo() == NumVecs)
11720       continue;
11721     SDNode *User = *UI;
11722     if (User->getOpcode() != ARMISD::VDUPLANE ||
11723         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11724       return false;
11725   }
11726 
11727   // Create the vldN-dup node.
11728   EVT Tys[5];
11729   unsigned n;
11730   for (n = 0; n < NumVecs; ++n)
11731     Tys[n] = VT;
11732   Tys[n] = MVT::Other;
11733   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11734   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11735   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11736   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11737                                            Ops, VLDMemInt->getMemoryVT(),
11738                                            VLDMemInt->getMemOperand());
11739 
11740   // Update the uses.
11741   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11742        UI != UE; ++UI) {
11743     unsigned ResNo = UI.getUse().getResNo();
11744     // Ignore uses of the chain result.
11745     if (ResNo == NumVecs)
11746       continue;
11747     SDNode *User = *UI;
11748     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11749   }
11750 
11751   // Now the vldN-lane intrinsic is dead except for its chain result.
11752   // Update uses of the chain.
11753   std::vector<SDValue> VLDDupResults;
11754   for (unsigned n = 0; n < NumVecs; ++n)
11755     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11756   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11757   DCI.CombineTo(VLD, VLDDupResults);
11758 
11759   return true;
11760 }
11761 
11762 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11763 /// ARMISD::VDUPLANE.
11764 static SDValue PerformVDUPLANECombine(SDNode *N,
11765                                       TargetLowering::DAGCombinerInfo &DCI) {
11766   SDValue Op = N->getOperand(0);
11767 
11768   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11769   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11770   if (CombineVLDDUP(N, DCI))
11771     return SDValue(N, 0);
11772 
11773   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11774   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11775   while (Op.getOpcode() == ISD::BITCAST)
11776     Op = Op.getOperand(0);
11777   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11778     return SDValue();
11779 
11780   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11781   unsigned EltSize = Op.getScalarValueSizeInBits();
11782   // The canonical VMOV for a zero vector uses a 32-bit element size.
11783   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11784   unsigned EltBits;
11785   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11786     EltSize = 8;
11787   EVT VT = N->getValueType(0);
11788   if (EltSize > VT.getScalarSizeInBits())
11789     return SDValue();
11790 
11791   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11792 }
11793 
11794 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11795 static SDValue PerformVDUPCombine(SDNode *N,
11796                                   TargetLowering::DAGCombinerInfo &DCI) {
11797   SelectionDAG &DAG = DCI.DAG;
11798   SDValue Op = N->getOperand(0);
11799 
11800   // Match VDUP(LOAD) -> VLD1DUP.
11801   // We match this pattern here rather than waiting for isel because the
11802   // transform is only legal for unindexed loads.
11803   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11804   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11805       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11806     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11807                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11808     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11809     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11810                                              Ops, LD->getMemoryVT(),
11811                                              LD->getMemOperand());
11812     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11813     return VLDDup;
11814   }
11815 
11816   return SDValue();
11817 }
11818 
11819 static SDValue PerformLOADCombine(SDNode *N,
11820                                   TargetLowering::DAGCombinerInfo &DCI) {
11821   EVT VT = N->getValueType(0);
11822 
11823   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11824   if (ISD::isNormalLoad(N) && VT.isVector() &&
11825       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11826     return CombineBaseUpdate(N, DCI);
11827 
11828   return SDValue();
11829 }
11830 
11831 /// PerformSTORECombine - Target-specific dag combine xforms for
11832 /// ISD::STORE.
11833 static SDValue PerformSTORECombine(SDNode *N,
11834                                    TargetLowering::DAGCombinerInfo &DCI) {
11835   StoreSDNode *St = cast<StoreSDNode>(N);
11836   if (St->isVolatile())
11837     return SDValue();
11838 
11839   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11840   // pack all of the elements in one place.  Next, store to memory in fewer
11841   // chunks.
11842   SDValue StVal = St->getValue();
11843   EVT VT = StVal.getValueType();
11844   if (St->isTruncatingStore() && VT.isVector()) {
11845     SelectionDAG &DAG = DCI.DAG;
11846     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11847     EVT StVT = St->getMemoryVT();
11848     unsigned NumElems = VT.getVectorNumElements();
11849     assert(StVT != VT && "Cannot truncate to the same type");
11850     unsigned FromEltSz = VT.getScalarSizeInBits();
11851     unsigned ToEltSz = StVT.getScalarSizeInBits();
11852 
11853     // From, To sizes and ElemCount must be pow of two
11854     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11855 
11856     // We are going to use the original vector elt for storing.
11857     // Accumulated smaller vector elements must be a multiple of the store size.
11858     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11859 
11860     unsigned SizeRatio  = FromEltSz / ToEltSz;
11861     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11862 
11863     // Create a type on which we perform the shuffle.
11864     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11865                                      NumElems*SizeRatio);
11866     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11867 
11868     SDLoc DL(St);
11869     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11870     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11871     for (unsigned i = 0; i < NumElems; ++i)
11872       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11873                           ? (i + 1) * SizeRatio - 1
11874                           : i * SizeRatio;
11875 
11876     // Can't shuffle using an illegal type.
11877     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11878 
11879     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11880                                 DAG.getUNDEF(WideVec.getValueType()),
11881                                 ShuffleVec);
11882     // At this point all of the data is stored at the bottom of the
11883     // register. We now need to save it to mem.
11884 
11885     // Find the largest store unit
11886     MVT StoreType = MVT::i8;
11887     for (MVT Tp : MVT::integer_valuetypes()) {
11888       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11889         StoreType = Tp;
11890     }
11891     // Didn't find a legal store type.
11892     if (!TLI.isTypeLegal(StoreType))
11893       return SDValue();
11894 
11895     // Bitcast the original vector into a vector of store-size units
11896     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11897             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11898     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11899     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11900     SmallVector<SDValue, 8> Chains;
11901     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11902                                         TLI.getPointerTy(DAG.getDataLayout()));
11903     SDValue BasePtr = St->getBasePtr();
11904 
11905     // Perform one or more big stores into memory.
11906     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11907     for (unsigned I = 0; I < E; I++) {
11908       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11909                                    StoreType, ShuffWide,
11910                                    DAG.getIntPtrConstant(I, DL));
11911       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
11912                                 St->getPointerInfo(), St->getAlignment(),
11913                                 St->getMemOperand()->getFlags());
11914       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
11915                             Increment);
11916       Chains.push_back(Ch);
11917     }
11918     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11919   }
11920 
11921   if (!ISD::isNormalStore(St))
11922     return SDValue();
11923 
11924   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
11925   // ARM stores of arguments in the same cache line.
11926   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
11927       StVal.getNode()->hasOneUse()) {
11928     SelectionDAG  &DAG = DCI.DAG;
11929     bool isBigEndian = DAG.getDataLayout().isBigEndian();
11930     SDLoc DL(St);
11931     SDValue BasePtr = St->getBasePtr();
11932     SDValue NewST1 = DAG.getStore(
11933         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
11934         BasePtr, St->getPointerInfo(), St->getAlignment(),
11935         St->getMemOperand()->getFlags());
11936 
11937     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11938                                     DAG.getConstant(4, DL, MVT::i32));
11939     return DAG.getStore(NewST1.getValue(0), DL,
11940                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
11941                         OffsetPtr, St->getPointerInfo(),
11942                         std::min(4U, St->getAlignment() / 2),
11943                         St->getMemOperand()->getFlags());
11944   }
11945 
11946   if (StVal.getValueType() == MVT::i64 &&
11947       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11948 
11949     // Bitcast an i64 store extracted from a vector to f64.
11950     // Otherwise, the i64 value will be legalized to a pair of i32 values.
11951     SelectionDAG &DAG = DCI.DAG;
11952     SDLoc dl(StVal);
11953     SDValue IntVec = StVal.getOperand(0);
11954     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11955                                    IntVec.getValueType().getVectorNumElements());
11956     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
11957     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11958                                  Vec, StVal.getOperand(1));
11959     dl = SDLoc(N);
11960     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
11961     // Make the DAGCombiner fold the bitcasts.
11962     DCI.AddToWorklist(Vec.getNode());
11963     DCI.AddToWorklist(ExtElt.getNode());
11964     DCI.AddToWorklist(V.getNode());
11965     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
11966                         St->getPointerInfo(), St->getAlignment(),
11967                         St->getMemOperand()->getFlags(), St->getAAInfo());
11968   }
11969 
11970   // If this is a legal vector store, try to combine it into a VST1_UPD.
11971   if (ISD::isNormalStore(N) && VT.isVector() &&
11972       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11973     return CombineBaseUpdate(N, DCI);
11974 
11975   return SDValue();
11976 }
11977 
11978 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11979 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11980 /// when the VMUL has a constant operand that is a power of 2.
11981 ///
11982 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11983 ///  vmul.f32        d16, d17, d16
11984 ///  vcvt.s32.f32    d16, d16
11985 /// becomes:
11986 ///  vcvt.s32.f32    d16, d16, #3
11987 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11988                                   const ARMSubtarget *Subtarget) {
11989   if (!Subtarget->hasNEON())
11990     return SDValue();
11991 
11992   SDValue Op = N->getOperand(0);
11993   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11994       Op.getOpcode() != ISD::FMUL)
11995     return SDValue();
11996 
11997   SDValue ConstVec = Op->getOperand(1);
11998   if (!isa<BuildVectorSDNode>(ConstVec))
11999     return SDValue();
12000 
12001   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
12002   uint32_t FloatBits = FloatTy.getSizeInBits();
12003   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
12004   uint32_t IntBits = IntTy.getSizeInBits();
12005   unsigned NumLanes = Op.getValueType().getVectorNumElements();
12006   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
12007     // These instructions only exist converting from f32 to i32. We can handle
12008     // smaller integers by generating an extra truncate, but larger ones would
12009     // be lossy. We also can't handle more then 4 lanes, since these intructions
12010     // only support v2i32/v4i32 types.
12011     return SDValue();
12012   }
12013 
12014   BitVector UndefElements;
12015   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12016   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12017   if (C == -1 || C == 0 || C > 32)
12018     return SDValue();
12019 
12020   SDLoc dl(N);
12021   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
12022   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
12023     Intrinsic::arm_neon_vcvtfp2fxu;
12024   SDValue FixConv = DAG.getNode(
12025       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12026       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
12027       DAG.getConstant(C, dl, MVT::i32));
12028 
12029   if (IntBits < FloatBits)
12030     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
12031 
12032   return FixConv;
12033 }
12034 
12035 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
12036 /// can replace combinations of VCVT (integer to floating-point) and VDIV
12037 /// when the VDIV has a constant operand that is a power of 2.
12038 ///
12039 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
12040 ///  vcvt.f32.s32    d16, d16
12041 ///  vdiv.f32        d16, d17, d16
12042 /// becomes:
12043 ///  vcvt.f32.s32    d16, d16, #3
12044 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
12045                                   const ARMSubtarget *Subtarget) {
12046   if (!Subtarget->hasNEON())
12047     return SDValue();
12048 
12049   SDValue Op = N->getOperand(0);
12050   unsigned OpOpcode = Op.getNode()->getOpcode();
12051   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
12052       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
12053     return SDValue();
12054 
12055   SDValue ConstVec = N->getOperand(1);
12056   if (!isa<BuildVectorSDNode>(ConstVec))
12057     return SDValue();
12058 
12059   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
12060   uint32_t FloatBits = FloatTy.getSizeInBits();
12061   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
12062   uint32_t IntBits = IntTy.getSizeInBits();
12063   unsigned NumLanes = Op.getValueType().getVectorNumElements();
12064   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
12065     // These instructions only exist converting from i32 to f32. We can handle
12066     // smaller integers by generating an extra extend, but larger ones would
12067     // be lossy. We also can't handle more then 4 lanes, since these intructions
12068     // only support v2i32/v4i32 types.
12069     return SDValue();
12070   }
12071 
12072   BitVector UndefElements;
12073   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12074   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12075   if (C == -1 || C == 0 || C > 32)
12076     return SDValue();
12077 
12078   SDLoc dl(N);
12079   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
12080   SDValue ConvInput = Op.getOperand(0);
12081   if (IntBits < FloatBits)
12082     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
12083                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12084                             ConvInput);
12085 
12086   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
12087     Intrinsic::arm_neon_vcvtfxu2fp;
12088   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
12089                      Op.getValueType(),
12090                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
12091                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
12092 }
12093 
12094 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
12095 /// operand of a vector shift operation, where all the elements of the
12096 /// build_vector must have the same constant integer value.
12097 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
12098   // Ignore bit_converts.
12099   while (Op.getOpcode() == ISD::BITCAST)
12100     Op = Op.getOperand(0);
12101   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
12102   APInt SplatBits, SplatUndef;
12103   unsigned SplatBitSize;
12104   bool HasAnyUndefs;
12105   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
12106                                       HasAnyUndefs, ElementBits) ||
12107       SplatBitSize > ElementBits)
12108     return false;
12109   Cnt = SplatBits.getSExtValue();
12110   return true;
12111 }
12112 
12113 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
12114 /// operand of a vector shift left operation.  That value must be in the range:
12115 ///   0 <= Value < ElementBits for a left shift; or
12116 ///   0 <= Value <= ElementBits for a long left shift.
12117 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
12118   assert(VT.isVector() && "vector shift count is not a vector type");
12119   int64_t ElementBits = VT.getScalarSizeInBits();
12120   if (! getVShiftImm(Op, ElementBits, Cnt))
12121     return false;
12122   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
12123 }
12124 
12125 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
12126 /// operand of a vector shift right operation.  For a shift opcode, the value
12127 /// is positive, but for an intrinsic the value count must be negative. The
12128 /// absolute value must be in the range:
12129 ///   1 <= |Value| <= ElementBits for a right shift; or
12130 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
12131 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
12132                          int64_t &Cnt) {
12133   assert(VT.isVector() && "vector shift count is not a vector type");
12134   int64_t ElementBits = VT.getScalarSizeInBits();
12135   if (! getVShiftImm(Op, ElementBits, Cnt))
12136     return false;
12137   if (!isIntrinsic)
12138     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
12139   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
12140     Cnt = -Cnt;
12141     return true;
12142   }
12143   return false;
12144 }
12145 
12146 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
12147 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
12148   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12149   switch (IntNo) {
12150   default:
12151     // Don't do anything for most intrinsics.
12152     break;
12153 
12154   // Vector shifts: check for immediate versions and lower them.
12155   // Note: This is done during DAG combining instead of DAG legalizing because
12156   // the build_vectors for 64-bit vector element shift counts are generally
12157   // not legal, and it is hard to see their values after they get legalized to
12158   // loads from a constant pool.
12159   case Intrinsic::arm_neon_vshifts:
12160   case Intrinsic::arm_neon_vshiftu:
12161   case Intrinsic::arm_neon_vrshifts:
12162   case Intrinsic::arm_neon_vrshiftu:
12163   case Intrinsic::arm_neon_vrshiftn:
12164   case Intrinsic::arm_neon_vqshifts:
12165   case Intrinsic::arm_neon_vqshiftu:
12166   case Intrinsic::arm_neon_vqshiftsu:
12167   case Intrinsic::arm_neon_vqshiftns:
12168   case Intrinsic::arm_neon_vqshiftnu:
12169   case Intrinsic::arm_neon_vqshiftnsu:
12170   case Intrinsic::arm_neon_vqrshiftns:
12171   case Intrinsic::arm_neon_vqrshiftnu:
12172   case Intrinsic::arm_neon_vqrshiftnsu: {
12173     EVT VT = N->getOperand(1).getValueType();
12174     int64_t Cnt;
12175     unsigned VShiftOpc = 0;
12176 
12177     switch (IntNo) {
12178     case Intrinsic::arm_neon_vshifts:
12179     case Intrinsic::arm_neon_vshiftu:
12180       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
12181         VShiftOpc = ARMISD::VSHL;
12182         break;
12183       }
12184       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
12185         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
12186                      ARMISD::VSHRs : ARMISD::VSHRu);
12187         break;
12188       }
12189       return SDValue();
12190 
12191     case Intrinsic::arm_neon_vrshifts:
12192     case Intrinsic::arm_neon_vrshiftu:
12193       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
12194         break;
12195       return SDValue();
12196 
12197     case Intrinsic::arm_neon_vqshifts:
12198     case Intrinsic::arm_neon_vqshiftu:
12199       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12200         break;
12201       return SDValue();
12202 
12203     case Intrinsic::arm_neon_vqshiftsu:
12204       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12205         break;
12206       llvm_unreachable("invalid shift count for vqshlu intrinsic");
12207 
12208     case Intrinsic::arm_neon_vrshiftn:
12209     case Intrinsic::arm_neon_vqshiftns:
12210     case Intrinsic::arm_neon_vqshiftnu:
12211     case Intrinsic::arm_neon_vqshiftnsu:
12212     case Intrinsic::arm_neon_vqrshiftns:
12213     case Intrinsic::arm_neon_vqrshiftnu:
12214     case Intrinsic::arm_neon_vqrshiftnsu:
12215       // Narrowing shifts require an immediate right shift.
12216       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
12217         break;
12218       llvm_unreachable("invalid shift count for narrowing vector shift "
12219                        "intrinsic");
12220 
12221     default:
12222       llvm_unreachable("unhandled vector shift");
12223     }
12224 
12225     switch (IntNo) {
12226     case Intrinsic::arm_neon_vshifts:
12227     case Intrinsic::arm_neon_vshiftu:
12228       // Opcode already set above.
12229       break;
12230     case Intrinsic::arm_neon_vrshifts:
12231       VShiftOpc = ARMISD::VRSHRs; break;
12232     case Intrinsic::arm_neon_vrshiftu:
12233       VShiftOpc = ARMISD::VRSHRu; break;
12234     case Intrinsic::arm_neon_vrshiftn:
12235       VShiftOpc = ARMISD::VRSHRN; break;
12236     case Intrinsic::arm_neon_vqshifts:
12237       VShiftOpc = ARMISD::VQSHLs; break;
12238     case Intrinsic::arm_neon_vqshiftu:
12239       VShiftOpc = ARMISD::VQSHLu; break;
12240     case Intrinsic::arm_neon_vqshiftsu:
12241       VShiftOpc = ARMISD::VQSHLsu; break;
12242     case Intrinsic::arm_neon_vqshiftns:
12243       VShiftOpc = ARMISD::VQSHRNs; break;
12244     case Intrinsic::arm_neon_vqshiftnu:
12245       VShiftOpc = ARMISD::VQSHRNu; break;
12246     case Intrinsic::arm_neon_vqshiftnsu:
12247       VShiftOpc = ARMISD::VQSHRNsu; break;
12248     case Intrinsic::arm_neon_vqrshiftns:
12249       VShiftOpc = ARMISD::VQRSHRNs; break;
12250     case Intrinsic::arm_neon_vqrshiftnu:
12251       VShiftOpc = ARMISD::VQRSHRNu; break;
12252     case Intrinsic::arm_neon_vqrshiftnsu:
12253       VShiftOpc = ARMISD::VQRSHRNsu; break;
12254     }
12255 
12256     SDLoc dl(N);
12257     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12258                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
12259   }
12260 
12261   case Intrinsic::arm_neon_vshiftins: {
12262     EVT VT = N->getOperand(1).getValueType();
12263     int64_t Cnt;
12264     unsigned VShiftOpc = 0;
12265 
12266     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
12267       VShiftOpc = ARMISD::VSLI;
12268     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
12269       VShiftOpc = ARMISD::VSRI;
12270     else {
12271       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
12272     }
12273 
12274     SDLoc dl(N);
12275     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12276                        N->getOperand(1), N->getOperand(2),
12277                        DAG.getConstant(Cnt, dl, MVT::i32));
12278   }
12279 
12280   case Intrinsic::arm_neon_vqrshifts:
12281   case Intrinsic::arm_neon_vqrshiftu:
12282     // No immediate versions of these to check for.
12283     break;
12284   }
12285 
12286   return SDValue();
12287 }
12288 
12289 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
12290 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
12291 /// combining instead of DAG legalizing because the build_vectors for 64-bit
12292 /// vector element shift counts are generally not legal, and it is hard to see
12293 /// their values after they get legalized to loads from a constant pool.
12294 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
12295                                    const ARMSubtarget *ST) {
12296   EVT VT = N->getValueType(0);
12297   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
12298     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
12299     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
12300     SDValue N1 = N->getOperand(1);
12301     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
12302       SDValue N0 = N->getOperand(0);
12303       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
12304           DAG.MaskedValueIsZero(N0.getOperand(0),
12305                                 APInt::getHighBitsSet(32, 16)))
12306         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
12307     }
12308   }
12309 
12310   // Nothing to be done for scalar shifts.
12311   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12312   if (!VT.isVector() || !TLI.isTypeLegal(VT))
12313     return SDValue();
12314 
12315   assert(ST->hasNEON() && "unexpected vector shift");
12316   int64_t Cnt;
12317 
12318   switch (N->getOpcode()) {
12319   default: llvm_unreachable("unexpected shift opcode");
12320 
12321   case ISD::SHL:
12322     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
12323       SDLoc dl(N);
12324       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
12325                          DAG.getConstant(Cnt, dl, MVT::i32));
12326     }
12327     break;
12328 
12329   case ISD::SRA:
12330   case ISD::SRL:
12331     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
12332       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
12333                             ARMISD::VSHRs : ARMISD::VSHRu);
12334       SDLoc dl(N);
12335       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
12336                          DAG.getConstant(Cnt, dl, MVT::i32));
12337     }
12338   }
12339   return SDValue();
12340 }
12341 
12342 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
12343 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
12344 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
12345                                     const ARMSubtarget *ST) {
12346   SDValue N0 = N->getOperand(0);
12347 
12348   // Check for sign- and zero-extensions of vector extract operations of 8-
12349   // and 16-bit vector elements.  NEON supports these directly.  They are
12350   // handled during DAG combining because type legalization will promote them
12351   // to 32-bit types and it is messy to recognize the operations after that.
12352   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12353     SDValue Vec = N0.getOperand(0);
12354     SDValue Lane = N0.getOperand(1);
12355     EVT VT = N->getValueType(0);
12356     EVT EltVT = N0.getValueType();
12357     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12358 
12359     if (VT == MVT::i32 &&
12360         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
12361         TLI.isTypeLegal(Vec.getValueType()) &&
12362         isa<ConstantSDNode>(Lane)) {
12363 
12364       unsigned Opc = 0;
12365       switch (N->getOpcode()) {
12366       default: llvm_unreachable("unexpected opcode");
12367       case ISD::SIGN_EXTEND:
12368         Opc = ARMISD::VGETLANEs;
12369         break;
12370       case ISD::ZERO_EXTEND:
12371       case ISD::ANY_EXTEND:
12372         Opc = ARMISD::VGETLANEu;
12373         break;
12374       }
12375       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
12376     }
12377   }
12378 
12379   return SDValue();
12380 }
12381 
12382 static const APInt *isPowerOf2Constant(SDValue V) {
12383   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12384   if (!C)
12385     return nullptr;
12386   const APInt *CV = &C->getAPIntValue();
12387   return CV->isPowerOf2() ? CV : nullptr;
12388 }
12389 
12390 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
12391   // If we have a CMOV, OR and AND combination such as:
12392   //   if (x & CN)
12393   //     y |= CM;
12394   //
12395   // And:
12396   //   * CN is a single bit;
12397   //   * All bits covered by CM are known zero in y
12398   //
12399   // Then we can convert this into a sequence of BFI instructions. This will
12400   // always be a win if CM is a single bit, will always be no worse than the
12401   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
12402   // three bits (due to the extra IT instruction).
12403 
12404   SDValue Op0 = CMOV->getOperand(0);
12405   SDValue Op1 = CMOV->getOperand(1);
12406   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
12407   auto CC = CCNode->getAPIntValue().getLimitedValue();
12408   SDValue CmpZ = CMOV->getOperand(4);
12409 
12410   // The compare must be against zero.
12411   if (!isNullConstant(CmpZ->getOperand(1)))
12412     return SDValue();
12413 
12414   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
12415   SDValue And = CmpZ->getOperand(0);
12416   if (And->getOpcode() != ISD::AND)
12417     return SDValue();
12418   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
12419   if (!AndC)
12420     return SDValue();
12421   SDValue X = And->getOperand(0);
12422 
12423   if (CC == ARMCC::EQ) {
12424     // We're performing an "equal to zero" compare. Swap the operands so we
12425     // canonicalize on a "not equal to zero" compare.
12426     std::swap(Op0, Op1);
12427   } else {
12428     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
12429   }
12430 
12431   if (Op1->getOpcode() != ISD::OR)
12432     return SDValue();
12433 
12434   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
12435   if (!OrC)
12436     return SDValue();
12437   SDValue Y = Op1->getOperand(0);
12438 
12439   if (Op0 != Y)
12440     return SDValue();
12441 
12442   // Now, is it profitable to continue?
12443   APInt OrCI = OrC->getAPIntValue();
12444   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
12445   if (OrCI.countPopulation() > Heuristic)
12446     return SDValue();
12447 
12448   // Lastly, can we determine that the bits defined by OrCI
12449   // are zero in Y?
12450   KnownBits Known;
12451   DAG.computeKnownBits(Y, Known);
12452   if ((OrCI & Known.Zero) != OrCI)
12453     return SDValue();
12454 
12455   // OK, we can do the combine.
12456   SDValue V = Y;
12457   SDLoc dl(X);
12458   EVT VT = X.getValueType();
12459   unsigned BitInX = AndC->logBase2();
12460 
12461   if (BitInX != 0) {
12462     // We must shift X first.
12463     X = DAG.getNode(ISD::SRL, dl, VT, X,
12464                     DAG.getConstant(BitInX, dl, VT));
12465   }
12466 
12467   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
12468        BitInY < NumActiveBits; ++BitInY) {
12469     if (OrCI[BitInY] == 0)
12470       continue;
12471     APInt Mask(VT.getSizeInBits(), 0);
12472     Mask.setBit(BitInY);
12473     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
12474                     // Confusingly, the operand is an *inverted* mask.
12475                     DAG.getConstant(~Mask, dl, VT));
12476   }
12477 
12478   return V;
12479 }
12480 
12481 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
12482 SDValue
12483 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
12484   SDValue Cmp = N->getOperand(4);
12485   if (Cmp.getOpcode() != ARMISD::CMPZ)
12486     // Only looking at NE cases.
12487     return SDValue();
12488 
12489   EVT VT = N->getValueType(0);
12490   SDLoc dl(N);
12491   SDValue LHS = Cmp.getOperand(0);
12492   SDValue RHS = Cmp.getOperand(1);
12493   SDValue Chain = N->getOperand(0);
12494   SDValue BB = N->getOperand(1);
12495   SDValue ARMcc = N->getOperand(2);
12496   ARMCC::CondCodes CC =
12497     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12498 
12499   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
12500   // -> (brcond Chain BB CC CPSR Cmp)
12501   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
12502       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
12503       LHS->getOperand(0)->hasOneUse()) {
12504     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
12505     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
12506     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12507     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12508     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
12509         (LHS01C && LHS01C->getZExtValue() == 1) &&
12510         (LHS1C && LHS1C->getZExtValue() == 1) &&
12511         (RHSC && RHSC->getZExtValue() == 0)) {
12512       return DAG.getNode(
12513           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
12514           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
12515     }
12516   }
12517 
12518   return SDValue();
12519 }
12520 
12521 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
12522 SDValue
12523 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
12524   SDValue Cmp = N->getOperand(4);
12525   if (Cmp.getOpcode() != ARMISD::CMPZ)
12526     // Only looking at EQ and NE cases.
12527     return SDValue();
12528 
12529   EVT VT = N->getValueType(0);
12530   SDLoc dl(N);
12531   SDValue LHS = Cmp.getOperand(0);
12532   SDValue RHS = Cmp.getOperand(1);
12533   SDValue FalseVal = N->getOperand(0);
12534   SDValue TrueVal = N->getOperand(1);
12535   SDValue ARMcc = N->getOperand(2);
12536   ARMCC::CondCodes CC =
12537     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12538 
12539   // BFI is only available on V6T2+.
12540   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
12541     SDValue R = PerformCMOVToBFICombine(N, DAG);
12542     if (R)
12543       return R;
12544   }
12545 
12546   // Simplify
12547   //   mov     r1, r0
12548   //   cmp     r1, x
12549   //   mov     r0, y
12550   //   moveq   r0, x
12551   // to
12552   //   cmp     r0, x
12553   //   movne   r0, y
12554   //
12555   //   mov     r1, r0
12556   //   cmp     r1, x
12557   //   mov     r0, x
12558   //   movne   r0, y
12559   // to
12560   //   cmp     r0, x
12561   //   movne   r0, y
12562   /// FIXME: Turn this into a target neutral optimization?
12563   SDValue Res;
12564   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
12565     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
12566                       N->getOperand(3), Cmp);
12567   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
12568     SDValue ARMcc;
12569     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
12570     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
12571                       N->getOperand(3), NewCmp);
12572   }
12573 
12574   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
12575   // -> (cmov F T CC CPSR Cmp)
12576   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
12577     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
12578     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12579     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12580     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
12581         (LHS1C && LHS1C->getZExtValue() == 1) &&
12582         (RHSC && RHSC->getZExtValue() == 0)) {
12583       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
12584                          LHS->getOperand(2), LHS->getOperand(3),
12585                          LHS->getOperand(4));
12586     }
12587   }
12588 
12589   if (!VT.isInteger())
12590       return SDValue();
12591 
12592   // Materialize a boolean comparison for integers so we can avoid branching.
12593   if (isNullConstant(FalseVal)) {
12594     if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
12595       if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
12596         // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
12597         // right 5 bits will make that 32 be 1, otherwise it will be 0.
12598         // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
12599         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12600         Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
12601                           DAG.getConstant(5, dl, MVT::i32));
12602       } else {
12603         // CMOV 0, 1, ==, (CMPZ x, y) ->
12604         //     (ADDCARRY (SUB x, y), t:0, t:1)
12605         // where t = (SUBCARRY 0, (SUB x, y), 0)
12606         //
12607         // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
12608         // x != y. In other words, a carry C == 1 when x == y, C == 0
12609         // otherwise.
12610         // The final ADDCARRY computes
12611         //     x - y + (0 - (x - y)) + C == C
12612         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12613         SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12614         SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
12615         // ISD::SUBCARRY returns a borrow but we want the carry here
12616         // actually.
12617         SDValue Carry =
12618             DAG.getNode(ISD::SUB, dl, MVT::i32,
12619                         DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
12620         Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
12621       }
12622     } else if (CC == ARMCC::NE && LHS != RHS &&
12623                (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
12624       // This seems pointless but will allow us to combine it further below.
12625       // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUB x, y), z, !=, (CMPZ x, y)
12626       SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12627       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
12628                         N->getOperand(3), Cmp);
12629     }
12630   } else if (isNullConstant(TrueVal)) {
12631     if (CC == ARMCC::EQ && LHS != RHS &&
12632         (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
12633       // This seems pointless but will allow us to combine it further below
12634       // Note that we change == for != as this is the dual for the case above.
12635       // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUB x, y), z, !=, (CMPZ x, y)
12636       SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12637       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
12638                         DAG.getConstant(ARMCC::NE, dl, MVT::i32),
12639                         N->getOperand(3), Cmp);
12640     }
12641   }
12642 
12643   // On Thumb1, the DAG above may be further combined if z is a power of 2
12644   // (z == 2 ^ K).
12645   // CMOV (SUB x, y), z, !=, (CMPZ x, y) ->
12646   //       merge t3, t4
12647   // where t1 = (SUBCARRY (SUB x, y), z, 0)
12648   //       t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
12649   //       t3 = if K != 0 then (SHL t2:0, K) else t2:0
12650   //       t4 = (SUB 1, t2:1)   [ we want a carry, not a borrow ]
12651   const APInt *TrueConst;
12652   if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
12653       (FalseVal.getOpcode() == ISD::SUB) && (FalseVal.getOperand(0) == LHS) &&
12654       (FalseVal.getOperand(1) == RHS) &&
12655       (TrueConst = isPowerOf2Constant(TrueVal))) {
12656     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12657     unsigned ShiftAmount = TrueConst->logBase2();
12658     if (ShiftAmount)
12659       TrueVal = DAG.getConstant(1, dl, VT);
12660     SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
12661     Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
12662     // Make it a carry, not a borrow.
12663     SDValue Carry = DAG.getNode(
12664         ISD::SUB, dl, VT, DAG.getConstant(1, dl, MVT::i32), Res.getValue(1));
12665     Res = DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Res, Carry);
12666 
12667     if (ShiftAmount)
12668       Res = DAG.getNode(ISD::SHL, dl, VT, Res,
12669                         DAG.getConstant(ShiftAmount, dl, MVT::i32));
12670   }
12671 
12672   if (Res.getNode()) {
12673     KnownBits Known;
12674     DAG.computeKnownBits(SDValue(N,0), Known);
12675     // Capture demanded bits information that would be otherwise lost.
12676     if (Known.Zero == 0xfffffffe)
12677       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12678                         DAG.getValueType(MVT::i1));
12679     else if (Known.Zero == 0xffffff00)
12680       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12681                         DAG.getValueType(MVT::i8));
12682     else if (Known.Zero == 0xffff0000)
12683       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12684                         DAG.getValueType(MVT::i16));
12685   }
12686 
12687   return Res;
12688 }
12689 
12690 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
12691                                              DAGCombinerInfo &DCI) const {
12692   switch (N->getOpcode()) {
12693   default: break;
12694   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
12695   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
12696   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
12697   case ISD::SUB:        return PerformSUBCombine(N, DCI);
12698   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
12699   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
12700   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
12701   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
12702   case ARMISD::ADDC:
12703   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
12704   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
12705   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
12706   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
12707   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
12708   case ISD::STORE:      return PerformSTORECombine(N, DCI);
12709   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
12710   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
12711   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
12712   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
12713   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
12714   case ISD::FP_TO_SINT:
12715   case ISD::FP_TO_UINT:
12716     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
12717   case ISD::FDIV:
12718     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
12719   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
12720   case ISD::SHL:
12721   case ISD::SRA:
12722   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
12723   case ISD::SIGN_EXTEND:
12724   case ISD::ZERO_EXTEND:
12725   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
12726   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
12727   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
12728   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
12729   case ARMISD::VLD1DUP:
12730   case ARMISD::VLD2DUP:
12731   case ARMISD::VLD3DUP:
12732   case ARMISD::VLD4DUP:
12733     return PerformVLDCombine(N, DCI);
12734   case ARMISD::BUILD_VECTOR:
12735     return PerformARMBUILD_VECTORCombine(N, DCI);
12736   case ARMISD::SMULWB: {
12737     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12738     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12739     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12740       return SDValue();
12741     break;
12742   }
12743   case ARMISD::SMULWT: {
12744     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12745     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12746     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12747       return SDValue();
12748     break;
12749   }
12750   case ARMISD::SMLALBB: {
12751     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12752     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12753     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12754         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12755       return SDValue();
12756     break;
12757   }
12758   case ARMISD::SMLALBT: {
12759     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12760     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12761     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12762     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12763     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12764         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12765       return SDValue();
12766     break;
12767   }
12768   case ARMISD::SMLALTB: {
12769     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12770     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12771     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12772     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12773     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12774         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12775       return SDValue();
12776     break;
12777   }
12778   case ARMISD::SMLALTT: {
12779     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12780     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12781     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12782         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12783       return SDValue();
12784     break;
12785   }
12786   case ISD::INTRINSIC_VOID:
12787   case ISD::INTRINSIC_W_CHAIN:
12788     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12789     case Intrinsic::arm_neon_vld1:
12790     case Intrinsic::arm_neon_vld1x2:
12791     case Intrinsic::arm_neon_vld1x3:
12792     case Intrinsic::arm_neon_vld1x4:
12793     case Intrinsic::arm_neon_vld2:
12794     case Intrinsic::arm_neon_vld3:
12795     case Intrinsic::arm_neon_vld4:
12796     case Intrinsic::arm_neon_vld2lane:
12797     case Intrinsic::arm_neon_vld3lane:
12798     case Intrinsic::arm_neon_vld4lane:
12799     case Intrinsic::arm_neon_vld2dup:
12800     case Intrinsic::arm_neon_vld3dup:
12801     case Intrinsic::arm_neon_vld4dup:
12802     case Intrinsic::arm_neon_vst1:
12803     case Intrinsic::arm_neon_vst1x2:
12804     case Intrinsic::arm_neon_vst1x3:
12805     case Intrinsic::arm_neon_vst1x4:
12806     case Intrinsic::arm_neon_vst2:
12807     case Intrinsic::arm_neon_vst3:
12808     case Intrinsic::arm_neon_vst4:
12809     case Intrinsic::arm_neon_vst2lane:
12810     case Intrinsic::arm_neon_vst3lane:
12811     case Intrinsic::arm_neon_vst4lane:
12812       return PerformVLDCombine(N, DCI);
12813     default: break;
12814     }
12815     break;
12816   }
12817   return SDValue();
12818 }
12819 
12820 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12821                                                           EVT VT) const {
12822   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12823 }
12824 
12825 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12826                                                        unsigned,
12827                                                        unsigned,
12828                                                        bool *Fast) const {
12829   // Depends what it gets converted into if the type is weird.
12830   if (!VT.isSimple())
12831     return false;
12832 
12833   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12834   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12835 
12836   switch (VT.getSimpleVT().SimpleTy) {
12837   default:
12838     return false;
12839   case MVT::i8:
12840   case MVT::i16:
12841   case MVT::i32: {
12842     // Unaligned access can use (for example) LRDB, LRDH, LDR
12843     if (AllowsUnaligned) {
12844       if (Fast)
12845         *Fast = Subtarget->hasV7Ops();
12846       return true;
12847     }
12848     return false;
12849   }
12850   case MVT::f64:
12851   case MVT::v2f64: {
12852     // For any little-endian targets with neon, we can support unaligned ld/st
12853     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12854     // A big-endian target may also explicitly support unaligned accesses
12855     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12856       if (Fast)
12857         *Fast = true;
12858       return true;
12859     }
12860     return false;
12861   }
12862   }
12863 }
12864 
12865 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12866                        unsigned AlignCheck) {
12867   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12868           (DstAlign == 0 || DstAlign % AlignCheck == 0));
12869 }
12870 
12871 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12872                                            unsigned DstAlign, unsigned SrcAlign,
12873                                            bool IsMemset, bool ZeroMemset,
12874                                            bool MemcpyStrSrc,
12875                                            MachineFunction &MF) const {
12876   const Function &F = MF.getFunction();
12877 
12878   // See if we can use NEON instructions for this...
12879   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12880       !F.hasFnAttribute(Attribute::NoImplicitFloat)) {
12881     bool Fast;
12882     if (Size >= 16 &&
12883         (memOpAlign(SrcAlign, DstAlign, 16) ||
12884          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12885       return MVT::v2f64;
12886     } else if (Size >= 8 &&
12887                (memOpAlign(SrcAlign, DstAlign, 8) ||
12888                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12889                  Fast))) {
12890       return MVT::f64;
12891     }
12892   }
12893 
12894   // Let the target-independent logic figure it out.
12895   return MVT::Other;
12896 }
12897 
12898 // 64-bit integers are split into their high and low parts and held in two
12899 // different registers, so the trunc is free since the low register can just
12900 // be used.
12901 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
12902   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
12903     return false;
12904   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
12905   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
12906   return (SrcBits == 64 && DestBits == 32);
12907 }
12908 
12909 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
12910   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
12911       !DstVT.isInteger())
12912     return false;
12913   unsigned SrcBits = SrcVT.getSizeInBits();
12914   unsigned DestBits = DstVT.getSizeInBits();
12915   return (SrcBits == 64 && DestBits == 32);
12916 }
12917 
12918 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12919   if (Val.getOpcode() != ISD::LOAD)
12920     return false;
12921 
12922   EVT VT1 = Val.getValueType();
12923   if (!VT1.isSimple() || !VT1.isInteger() ||
12924       !VT2.isSimple() || !VT2.isInteger())
12925     return false;
12926 
12927   switch (VT1.getSimpleVT().SimpleTy) {
12928   default: break;
12929   case MVT::i1:
12930   case MVT::i8:
12931   case MVT::i16:
12932     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
12933     return true;
12934   }
12935 
12936   return false;
12937 }
12938 
12939 bool ARMTargetLowering::isFNegFree(EVT VT) const {
12940   if (!VT.isSimple())
12941     return false;
12942 
12943   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
12944   // negate values directly (fneg is free). So, we don't want to let the DAG
12945   // combiner rewrite fneg into xors and some other instructions.  For f16 and
12946   // FullFP16 argument passing, some bitcast nodes may be introduced,
12947   // triggering this DAG combine rewrite, so we are avoiding that with this.
12948   switch (VT.getSimpleVT().SimpleTy) {
12949   default: break;
12950   case MVT::f16:
12951     return Subtarget->hasFullFP16();
12952   }
12953 
12954   return false;
12955 }
12956 
12957 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
12958   EVT VT = ExtVal.getValueType();
12959 
12960   if (!isTypeLegal(VT))
12961     return false;
12962 
12963   // Don't create a loadext if we can fold the extension into a wide/long
12964   // instruction.
12965   // If there's more than one user instruction, the loadext is desirable no
12966   // matter what.  There can be two uses by the same instruction.
12967   if (ExtVal->use_empty() ||
12968       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
12969     return true;
12970 
12971   SDNode *U = *ExtVal->use_begin();
12972   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
12973        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
12974     return false;
12975 
12976   return true;
12977 }
12978 
12979 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
12980   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12981     return false;
12982 
12983   if (!isTypeLegal(EVT::getEVT(Ty1)))
12984     return false;
12985 
12986   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
12987 
12988   // Assuming the caller doesn't have a zeroext or signext return parameter,
12989   // truncation all the way down to i1 is valid.
12990   return true;
12991 }
12992 
12993 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
12994                                                 const AddrMode &AM, Type *Ty,
12995                                                 unsigned AS) const {
12996   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
12997     if (Subtarget->hasFPAO())
12998       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
12999     return 0;
13000   }
13001   return -1;
13002 }
13003 
13004 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
13005   if (V < 0)
13006     return false;
13007 
13008   unsigned Scale = 1;
13009   switch (VT.getSimpleVT().SimpleTy) {
13010   default: return false;
13011   case MVT::i1:
13012   case MVT::i8:
13013     // Scale == 1;
13014     break;
13015   case MVT::i16:
13016     // Scale == 2;
13017     Scale = 2;
13018     break;
13019   case MVT::i32:
13020     // Scale == 4;
13021     Scale = 4;
13022     break;
13023   }
13024 
13025   if ((V & (Scale - 1)) != 0)
13026     return false;
13027   V /= Scale;
13028   return V == (V & ((1LL << 5) - 1));
13029 }
13030 
13031 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
13032                                       const ARMSubtarget *Subtarget) {
13033   bool isNeg = false;
13034   if (V < 0) {
13035     isNeg = true;
13036     V = - V;
13037   }
13038 
13039   switch (VT.getSimpleVT().SimpleTy) {
13040   default: return false;
13041   case MVT::i1:
13042   case MVT::i8:
13043   case MVT::i16:
13044   case MVT::i32:
13045     // + imm12 or - imm8
13046     if (isNeg)
13047       return V == (V & ((1LL << 8) - 1));
13048     return V == (V & ((1LL << 12) - 1));
13049   case MVT::f32:
13050   case MVT::f64:
13051     // Same as ARM mode. FIXME: NEON?
13052     if (!Subtarget->hasVFP2())
13053       return false;
13054     if ((V & 3) != 0)
13055       return false;
13056     V >>= 2;
13057     return V == (V & ((1LL << 8) - 1));
13058   }
13059 }
13060 
13061 /// isLegalAddressImmediate - Return true if the integer value can be used
13062 /// as the offset of the target addressing mode for load / store of the
13063 /// given type.
13064 static bool isLegalAddressImmediate(int64_t V, EVT VT,
13065                                     const ARMSubtarget *Subtarget) {
13066   if (V == 0)
13067     return true;
13068 
13069   if (!VT.isSimple())
13070     return false;
13071 
13072   if (Subtarget->isThumb1Only())
13073     return isLegalT1AddressImmediate(V, VT);
13074   else if (Subtarget->isThumb2())
13075     return isLegalT2AddressImmediate(V, VT, Subtarget);
13076 
13077   // ARM mode.
13078   if (V < 0)
13079     V = - V;
13080   switch (VT.getSimpleVT().SimpleTy) {
13081   default: return false;
13082   case MVT::i1:
13083   case MVT::i8:
13084   case MVT::i32:
13085     // +- imm12
13086     return V == (V & ((1LL << 12) - 1));
13087   case MVT::i16:
13088     // +- imm8
13089     return V == (V & ((1LL << 8) - 1));
13090   case MVT::f32:
13091   case MVT::f64:
13092     if (!Subtarget->hasVFP2()) // FIXME: NEON?
13093       return false;
13094     if ((V & 3) != 0)
13095       return false;
13096     V >>= 2;
13097     return V == (V & ((1LL << 8) - 1));
13098   }
13099 }
13100 
13101 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
13102                                                       EVT VT) const {
13103   int Scale = AM.Scale;
13104   if (Scale < 0)
13105     return false;
13106 
13107   switch (VT.getSimpleVT().SimpleTy) {
13108   default: return false;
13109   case MVT::i1:
13110   case MVT::i8:
13111   case MVT::i16:
13112   case MVT::i32:
13113     if (Scale == 1)
13114       return true;
13115     // r + r << imm
13116     Scale = Scale & ~1;
13117     return Scale == 2 || Scale == 4 || Scale == 8;
13118   case MVT::i64:
13119     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
13120     // version in Thumb mode.
13121     // r + r
13122     if (Scale == 1)
13123       return true;
13124     // r * 2 (this can be lowered to r + r).
13125     if (!AM.HasBaseReg && Scale == 2)
13126       return true;
13127     return false;
13128   case MVT::isVoid:
13129     // Note, we allow "void" uses (basically, uses that aren't loads or
13130     // stores), because arm allows folding a scale into many arithmetic
13131     // operations.  This should be made more precise and revisited later.
13132 
13133     // Allow r << imm, but the imm has to be a multiple of two.
13134     if (Scale & 1) return false;
13135     return isPowerOf2_32(Scale);
13136   }
13137 }
13138 
13139 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
13140                                                       EVT VT) const {
13141   const int Scale = AM.Scale;
13142 
13143   // Negative scales are not supported in Thumb1.
13144   if (Scale < 0)
13145     return false;
13146 
13147   // Thumb1 addressing modes do not support register scaling excepting the
13148   // following cases:
13149   // 1. Scale == 1 means no scaling.
13150   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
13151   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
13152 }
13153 
13154 /// isLegalAddressingMode - Return true if the addressing mode represented
13155 /// by AM is legal for this target, for a load/store of the specified type.
13156 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
13157                                               const AddrMode &AM, Type *Ty,
13158                                               unsigned AS, Instruction *I) const {
13159   EVT VT = getValueType(DL, Ty, true);
13160   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
13161     return false;
13162 
13163   // Can never fold addr of global into load/store.
13164   if (AM.BaseGV)
13165     return false;
13166 
13167   switch (AM.Scale) {
13168   case 0:  // no scale reg, must be "r+i" or "r", or "i".
13169     break;
13170   default:
13171     // ARM doesn't support any R+R*scale+imm addr modes.
13172     if (AM.BaseOffs)
13173       return false;
13174 
13175     if (!VT.isSimple())
13176       return false;
13177 
13178     if (Subtarget->isThumb1Only())
13179       return isLegalT1ScaledAddressingMode(AM, VT);
13180 
13181     if (Subtarget->isThumb2())
13182       return isLegalT2ScaledAddressingMode(AM, VT);
13183 
13184     int Scale = AM.Scale;
13185     switch (VT.getSimpleVT().SimpleTy) {
13186     default: return false;
13187     case MVT::i1:
13188     case MVT::i8:
13189     case MVT::i32:
13190       if (Scale < 0) Scale = -Scale;
13191       if (Scale == 1)
13192         return true;
13193       // r + r << imm
13194       return isPowerOf2_32(Scale & ~1);
13195     case MVT::i16:
13196     case MVT::i64:
13197       // r +/- r
13198       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
13199         return true;
13200       // r * 2 (this can be lowered to r + r).
13201       if (!AM.HasBaseReg && Scale == 2)
13202         return true;
13203       return false;
13204 
13205     case MVT::isVoid:
13206       // Note, we allow "void" uses (basically, uses that aren't loads or
13207       // stores), because arm allows folding a scale into many arithmetic
13208       // operations.  This should be made more precise and revisited later.
13209 
13210       // Allow r << imm, but the imm has to be a multiple of two.
13211       if (Scale & 1) return false;
13212       return isPowerOf2_32(Scale);
13213     }
13214   }
13215   return true;
13216 }
13217 
13218 /// isLegalICmpImmediate - Return true if the specified immediate is legal
13219 /// icmp immediate, that is the target has icmp instructions which can compare
13220 /// a register against the immediate without having to materialize the
13221 /// immediate into a register.
13222 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13223   // Thumb2 and ARM modes can use cmn for negative immediates.
13224   if (!Subtarget->isThumb())
13225     return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
13226            ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
13227   if (Subtarget->isThumb2())
13228     return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
13229            ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
13230   // Thumb1 doesn't have cmn, and only 8-bit immediates.
13231   return Imm >= 0 && Imm <= 255;
13232 }
13233 
13234 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
13235 /// *or sub* immediate, that is the target has add or sub instructions which can
13236 /// add a register with the immediate without having to materialize the
13237 /// immediate into a register.
13238 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13239   // Same encoding for add/sub, just flip the sign.
13240   int64_t AbsImm = std::abs(Imm);
13241   if (!Subtarget->isThumb())
13242     return ARM_AM::getSOImmVal(AbsImm) != -1;
13243   if (Subtarget->isThumb2())
13244     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
13245   // Thumb1 only has 8-bit unsigned immediate.
13246   return AbsImm >= 0 && AbsImm <= 255;
13247 }
13248 
13249 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
13250                                       bool isSEXTLoad, SDValue &Base,
13251                                       SDValue &Offset, bool &isInc,
13252                                       SelectionDAG &DAG) {
13253   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13254     return false;
13255 
13256   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
13257     // AddressingMode 3
13258     Base = Ptr->getOperand(0);
13259     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13260       int RHSC = (int)RHS->getZExtValue();
13261       if (RHSC < 0 && RHSC > -256) {
13262         assert(Ptr->getOpcode() == ISD::ADD);
13263         isInc = false;
13264         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13265         return true;
13266       }
13267     }
13268     isInc = (Ptr->getOpcode() == ISD::ADD);
13269     Offset = Ptr->getOperand(1);
13270     return true;
13271   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
13272     // AddressingMode 2
13273     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13274       int RHSC = (int)RHS->getZExtValue();
13275       if (RHSC < 0 && RHSC > -0x1000) {
13276         assert(Ptr->getOpcode() == ISD::ADD);
13277         isInc = false;
13278         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13279         Base = Ptr->getOperand(0);
13280         return true;
13281       }
13282     }
13283 
13284     if (Ptr->getOpcode() == ISD::ADD) {
13285       isInc = true;
13286       ARM_AM::ShiftOpc ShOpcVal=
13287         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
13288       if (ShOpcVal != ARM_AM::no_shift) {
13289         Base = Ptr->getOperand(1);
13290         Offset = Ptr->getOperand(0);
13291       } else {
13292         Base = Ptr->getOperand(0);
13293         Offset = Ptr->getOperand(1);
13294       }
13295       return true;
13296     }
13297 
13298     isInc = (Ptr->getOpcode() == ISD::ADD);
13299     Base = Ptr->getOperand(0);
13300     Offset = Ptr->getOperand(1);
13301     return true;
13302   }
13303 
13304   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
13305   return false;
13306 }
13307 
13308 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
13309                                      bool isSEXTLoad, SDValue &Base,
13310                                      SDValue &Offset, bool &isInc,
13311                                      SelectionDAG &DAG) {
13312   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13313     return false;
13314 
13315   Base = Ptr->getOperand(0);
13316   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13317     int RHSC = (int)RHS->getZExtValue();
13318     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
13319       assert(Ptr->getOpcode() == ISD::ADD);
13320       isInc = false;
13321       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13322       return true;
13323     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
13324       isInc = Ptr->getOpcode() == ISD::ADD;
13325       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
13326       return true;
13327     }
13328   }
13329 
13330   return false;
13331 }
13332 
13333 /// getPreIndexedAddressParts - returns true by value, base pointer and
13334 /// offset pointer and addressing mode by reference if the node's address
13335 /// can be legally represented as pre-indexed load / store address.
13336 bool
13337 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
13338                                              SDValue &Offset,
13339                                              ISD::MemIndexedMode &AM,
13340                                              SelectionDAG &DAG) const {
13341   if (Subtarget->isThumb1Only())
13342     return false;
13343 
13344   EVT VT;
13345   SDValue Ptr;
13346   bool isSEXTLoad = false;
13347   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13348     Ptr = LD->getBasePtr();
13349     VT  = LD->getMemoryVT();
13350     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13351   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13352     Ptr = ST->getBasePtr();
13353     VT  = ST->getMemoryVT();
13354   } else
13355     return false;
13356 
13357   bool isInc;
13358   bool isLegal = false;
13359   if (Subtarget->isThumb2())
13360     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13361                                        Offset, isInc, DAG);
13362   else
13363     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13364                                         Offset, isInc, DAG);
13365   if (!isLegal)
13366     return false;
13367 
13368   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
13369   return true;
13370 }
13371 
13372 /// getPostIndexedAddressParts - returns true by value, base pointer and
13373 /// offset pointer and addressing mode by reference if this node can be
13374 /// combined with a load / store to form a post-indexed load / store.
13375 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
13376                                                    SDValue &Base,
13377                                                    SDValue &Offset,
13378                                                    ISD::MemIndexedMode &AM,
13379                                                    SelectionDAG &DAG) const {
13380   EVT VT;
13381   SDValue Ptr;
13382   bool isSEXTLoad = false, isNonExt;
13383   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13384     VT  = LD->getMemoryVT();
13385     Ptr = LD->getBasePtr();
13386     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13387     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
13388   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13389     VT  = ST->getMemoryVT();
13390     Ptr = ST->getBasePtr();
13391     isNonExt = !ST->isTruncatingStore();
13392   } else
13393     return false;
13394 
13395   if (Subtarget->isThumb1Only()) {
13396     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
13397     // must be non-extending/truncating, i32, with an offset of 4.
13398     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
13399     if (Op->getOpcode() != ISD::ADD || !isNonExt)
13400       return false;
13401     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
13402     if (!RHS || RHS->getZExtValue() != 4)
13403       return false;
13404 
13405     Offset = Op->getOperand(1);
13406     Base = Op->getOperand(0);
13407     AM = ISD::POST_INC;
13408     return true;
13409   }
13410 
13411   bool isInc;
13412   bool isLegal = false;
13413   if (Subtarget->isThumb2())
13414     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13415                                        isInc, DAG);
13416   else
13417     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13418                                         isInc, DAG);
13419   if (!isLegal)
13420     return false;
13421 
13422   if (Ptr != Base) {
13423     // Swap base ptr and offset to catch more post-index load / store when
13424     // it's legal. In Thumb2 mode, offset must be an immediate.
13425     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
13426         !Subtarget->isThumb2())
13427       std::swap(Base, Offset);
13428 
13429     // Post-indexed load / store update the base pointer.
13430     if (Ptr != Base)
13431       return false;
13432   }
13433 
13434   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
13435   return true;
13436 }
13437 
13438 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13439                                                       KnownBits &Known,
13440                                                       const APInt &DemandedElts,
13441                                                       const SelectionDAG &DAG,
13442                                                       unsigned Depth) const {
13443   unsigned BitWidth = Known.getBitWidth();
13444   Known.resetAll();
13445   switch (Op.getOpcode()) {
13446   default: break;
13447   case ARMISD::ADDC:
13448   case ARMISD::ADDE:
13449   case ARMISD::SUBC:
13450   case ARMISD::SUBE:
13451     // Special cases when we convert a carry to a boolean.
13452     if (Op.getResNo() == 0) {
13453       SDValue LHS = Op.getOperand(0);
13454       SDValue RHS = Op.getOperand(1);
13455       // (ADDE 0, 0, C) will give us a single bit.
13456       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
13457           isNullConstant(RHS)) {
13458         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13459         return;
13460       }
13461     }
13462     break;
13463   case ARMISD::CMOV: {
13464     // Bits are known zero/one if known on the LHS and RHS.
13465     DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1);
13466     if (Known.isUnknown())
13467       return;
13468 
13469     KnownBits KnownRHS;
13470     DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1);
13471     Known.Zero &= KnownRHS.Zero;
13472     Known.One  &= KnownRHS.One;
13473     return;
13474   }
13475   case ISD::INTRINSIC_W_CHAIN: {
13476     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
13477     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
13478     switch (IntID) {
13479     default: return;
13480     case Intrinsic::arm_ldaex:
13481     case Intrinsic::arm_ldrex: {
13482       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
13483       unsigned MemBits = VT.getScalarSizeInBits();
13484       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
13485       return;
13486     }
13487     }
13488   }
13489   case ARMISD::BFI: {
13490     // Conservatively, we can recurse down the first operand
13491     // and just mask out all affected bits.
13492     DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1);
13493 
13494     // The operand to BFI is already a mask suitable for removing the bits it
13495     // sets.
13496     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
13497     const APInt &Mask = CI->getAPIntValue();
13498     Known.Zero &= Mask;
13499     Known.One &= Mask;
13500     return;
13501   }
13502   }
13503 }
13504 
13505 bool
13506 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
13507                                                 const APInt &DemandedAPInt,
13508                                                 TargetLoweringOpt &TLO) const {
13509   // Delay optimization, so we don't have to deal with illegal types, or block
13510   // optimizations.
13511   if (!TLO.LegalOps)
13512     return false;
13513 
13514   // Only optimize AND for now.
13515   if (Op.getOpcode() != ISD::AND)
13516     return false;
13517 
13518   EVT VT = Op.getValueType();
13519 
13520   // Ignore vectors.
13521   if (VT.isVector())
13522     return false;
13523 
13524   assert(VT == MVT::i32 && "Unexpected integer type");
13525 
13526   // Make sure the RHS really is a constant.
13527   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13528   if (!C)
13529     return false;
13530 
13531   unsigned Mask = C->getZExtValue();
13532 
13533   unsigned Demanded = DemandedAPInt.getZExtValue();
13534   unsigned ShrunkMask = Mask & Demanded;
13535   unsigned ExpandedMask = Mask | ~Demanded;
13536 
13537   // If the mask is all zeros, let the target-independent code replace the
13538   // result with zero.
13539   if (ShrunkMask == 0)
13540     return false;
13541 
13542   // If the mask is all ones, erase the AND. (Currently, the target-independent
13543   // code won't do this, so we have to do it explicitly to avoid an infinite
13544   // loop in obscure cases.)
13545   if (ExpandedMask == ~0U)
13546     return TLO.CombineTo(Op, Op.getOperand(0));
13547 
13548   auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
13549     return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
13550   };
13551   auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
13552     if (NewMask == Mask)
13553       return true;
13554     SDLoc DL(Op);
13555     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
13556     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
13557     return TLO.CombineTo(Op, NewOp);
13558   };
13559 
13560   // Prefer uxtb mask.
13561   if (IsLegalMask(0xFF))
13562     return UseMask(0xFF);
13563 
13564   // Prefer uxth mask.
13565   if (IsLegalMask(0xFFFF))
13566     return UseMask(0xFFFF);
13567 
13568   // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
13569   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
13570   if (ShrunkMask < 256)
13571     return UseMask(ShrunkMask);
13572 
13573   // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
13574   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
13575   if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
13576     return UseMask(ExpandedMask);
13577 
13578   // Potential improvements:
13579   //
13580   // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
13581   // We could try to prefer Thumb1 immediates which can be lowered to a
13582   // two-instruction sequence.
13583   // We could try to recognize more legal ARM/Thumb2 immediates here.
13584 
13585   return false;
13586 }
13587 
13588 
13589 //===----------------------------------------------------------------------===//
13590 //                           ARM Inline Assembly Support
13591 //===----------------------------------------------------------------------===//
13592 
13593 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
13594   // Looking for "rev" which is V6+.
13595   if (!Subtarget->hasV6Ops())
13596     return false;
13597 
13598   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13599   std::string AsmStr = IA->getAsmString();
13600   SmallVector<StringRef, 4> AsmPieces;
13601   SplitString(AsmStr, AsmPieces, ";\n");
13602 
13603   switch (AsmPieces.size()) {
13604   default: return false;
13605   case 1:
13606     AsmStr = AsmPieces[0];
13607     AsmPieces.clear();
13608     SplitString(AsmStr, AsmPieces, " \t,");
13609 
13610     // rev $0, $1
13611     if (AsmPieces.size() == 3 &&
13612         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
13613         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
13614       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13615       if (Ty && Ty->getBitWidth() == 32)
13616         return IntrinsicLowering::LowerToByteSwap(CI);
13617     }
13618     break;
13619   }
13620 
13621   return false;
13622 }
13623 
13624 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
13625   // At this point, we have to lower this constraint to something else, so we
13626   // lower it to an "r" or "w". However, by doing this we will force the result
13627   // to be in register, while the X constraint is much more permissive.
13628   //
13629   // Although we are correct (we are free to emit anything, without
13630   // constraints), we might break use cases that would expect us to be more
13631   // efficient and emit something else.
13632   if (!Subtarget->hasVFP2())
13633     return "r";
13634   if (ConstraintVT.isFloatingPoint())
13635     return "w";
13636   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
13637      (ConstraintVT.getSizeInBits() == 64 ||
13638       ConstraintVT.getSizeInBits() == 128))
13639     return "w";
13640 
13641   return "r";
13642 }
13643 
13644 /// getConstraintType - Given a constraint letter, return the type of
13645 /// constraint it is for this target.
13646 ARMTargetLowering::ConstraintType
13647 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
13648   if (Constraint.size() == 1) {
13649     switch (Constraint[0]) {
13650     default:  break;
13651     case 'l': return C_RegisterClass;
13652     case 'w': return C_RegisterClass;
13653     case 'h': return C_RegisterClass;
13654     case 'x': return C_RegisterClass;
13655     case 't': return C_RegisterClass;
13656     case 'j': return C_Other; // Constant for movw.
13657       // An address with a single base register. Due to the way we
13658       // currently handle addresses it is the same as an 'r' memory constraint.
13659     case 'Q': return C_Memory;
13660     }
13661   } else if (Constraint.size() == 2) {
13662     switch (Constraint[0]) {
13663     default: break;
13664     // All 'U+' constraints are addresses.
13665     case 'U': return C_Memory;
13666     }
13667   }
13668   return TargetLowering::getConstraintType(Constraint);
13669 }
13670 
13671 /// Examine constraint type and operand type and determine a weight value.
13672 /// This object must already have been set up with the operand type
13673 /// and the current alternative constraint selected.
13674 TargetLowering::ConstraintWeight
13675 ARMTargetLowering::getSingleConstraintMatchWeight(
13676     AsmOperandInfo &info, const char *constraint) const {
13677   ConstraintWeight weight = CW_Invalid;
13678   Value *CallOperandVal = info.CallOperandVal;
13679     // If we don't have a value, we can't do a match,
13680     // but allow it at the lowest weight.
13681   if (!CallOperandVal)
13682     return CW_Default;
13683   Type *type = CallOperandVal->getType();
13684   // Look at the constraint type.
13685   switch (*constraint) {
13686   default:
13687     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13688     break;
13689   case 'l':
13690     if (type->isIntegerTy()) {
13691       if (Subtarget->isThumb())
13692         weight = CW_SpecificReg;
13693       else
13694         weight = CW_Register;
13695     }
13696     break;
13697   case 'w':
13698     if (type->isFloatingPointTy())
13699       weight = CW_Register;
13700     break;
13701   }
13702   return weight;
13703 }
13704 
13705 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
13706 
13707 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
13708     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
13709   if (Constraint.size() == 1) {
13710     // GCC ARM Constraint Letters
13711     switch (Constraint[0]) {
13712     case 'l': // Low regs or general regs.
13713       if (Subtarget->isThumb())
13714         return RCPair(0U, &ARM::tGPRRegClass);
13715       return RCPair(0U, &ARM::GPRRegClass);
13716     case 'h': // High regs or no regs.
13717       if (Subtarget->isThumb())
13718         return RCPair(0U, &ARM::hGPRRegClass);
13719       break;
13720     case 'r':
13721       if (Subtarget->isThumb1Only())
13722         return RCPair(0U, &ARM::tGPRRegClass);
13723       return RCPair(0U, &ARM::GPRRegClass);
13724     case 'w':
13725       if (VT == MVT::Other)
13726         break;
13727       if (VT == MVT::f32)
13728         return RCPair(0U, &ARM::SPRRegClass);
13729       if (VT.getSizeInBits() == 64)
13730         return RCPair(0U, &ARM::DPRRegClass);
13731       if (VT.getSizeInBits() == 128)
13732         return RCPair(0U, &ARM::QPRRegClass);
13733       break;
13734     case 'x':
13735       if (VT == MVT::Other)
13736         break;
13737       if (VT == MVT::f32)
13738         return RCPair(0U, &ARM::SPR_8RegClass);
13739       if (VT.getSizeInBits() == 64)
13740         return RCPair(0U, &ARM::DPR_8RegClass);
13741       if (VT.getSizeInBits() == 128)
13742         return RCPair(0U, &ARM::QPR_8RegClass);
13743       break;
13744     case 't':
13745       if (VT == MVT::Other)
13746         break;
13747       if (VT == MVT::f32 || VT == MVT::i32)
13748         return RCPair(0U, &ARM::SPRRegClass);
13749       if (VT.getSizeInBits() == 64)
13750         return RCPair(0U, &ARM::DPR_VFP2RegClass);
13751       if (VT.getSizeInBits() == 128)
13752         return RCPair(0U, &ARM::QPR_VFP2RegClass);
13753       break;
13754     }
13755   }
13756   if (StringRef("{cc}").equals_lower(Constraint))
13757     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
13758 
13759   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13760 }
13761 
13762 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13763 /// vector.  If it is invalid, don't add anything to Ops.
13764 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13765                                                      std::string &Constraint,
13766                                                      std::vector<SDValue>&Ops,
13767                                                      SelectionDAG &DAG) const {
13768   SDValue Result;
13769 
13770   // Currently only support length 1 constraints.
13771   if (Constraint.length() != 1) return;
13772 
13773   char ConstraintLetter = Constraint[0];
13774   switch (ConstraintLetter) {
13775   default: break;
13776   case 'j':
13777   case 'I': case 'J': case 'K': case 'L':
13778   case 'M': case 'N': case 'O':
13779     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
13780     if (!C)
13781       return;
13782 
13783     int64_t CVal64 = C->getSExtValue();
13784     int CVal = (int) CVal64;
13785     // None of these constraints allow values larger than 32 bits.  Check
13786     // that the value fits in an int.
13787     if (CVal != CVal64)
13788       return;
13789 
13790     switch (ConstraintLetter) {
13791       case 'j':
13792         // Constant suitable for movw, must be between 0 and
13793         // 65535.
13794         if (Subtarget->hasV6T2Ops())
13795           if (CVal >= 0 && CVal <= 65535)
13796             break;
13797         return;
13798       case 'I':
13799         if (Subtarget->isThumb1Only()) {
13800           // This must be a constant between 0 and 255, for ADD
13801           // immediates.
13802           if (CVal >= 0 && CVal <= 255)
13803             break;
13804         } else if (Subtarget->isThumb2()) {
13805           // A constant that can be used as an immediate value in a
13806           // data-processing instruction.
13807           if (ARM_AM::getT2SOImmVal(CVal) != -1)
13808             break;
13809         } else {
13810           // A constant that can be used as an immediate value in a
13811           // data-processing instruction.
13812           if (ARM_AM::getSOImmVal(CVal) != -1)
13813             break;
13814         }
13815         return;
13816 
13817       case 'J':
13818         if (Subtarget->isThumb1Only()) {
13819           // This must be a constant between -255 and -1, for negated ADD
13820           // immediates. This can be used in GCC with an "n" modifier that
13821           // prints the negated value, for use with SUB instructions. It is
13822           // not useful otherwise but is implemented for compatibility.
13823           if (CVal >= -255 && CVal <= -1)
13824             break;
13825         } else {
13826           // This must be a constant between -4095 and 4095. It is not clear
13827           // what this constraint is intended for. Implemented for
13828           // compatibility with GCC.
13829           if (CVal >= -4095 && CVal <= 4095)
13830             break;
13831         }
13832         return;
13833 
13834       case 'K':
13835         if (Subtarget->isThumb1Only()) {
13836           // A 32-bit value where only one byte has a nonzero value. Exclude
13837           // zero to match GCC. This constraint is used by GCC internally for
13838           // constants that can be loaded with a move/shift combination.
13839           // It is not useful otherwise but is implemented for compatibility.
13840           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
13841             break;
13842         } else if (Subtarget->isThumb2()) {
13843           // A constant whose bitwise inverse can be used as an immediate
13844           // value in a data-processing instruction. This can be used in GCC
13845           // with a "B" modifier that prints the inverted value, for use with
13846           // BIC and MVN instructions. It is not useful otherwise but is
13847           // implemented for compatibility.
13848           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
13849             break;
13850         } else {
13851           // A constant whose bitwise inverse can be used as an immediate
13852           // value in a data-processing instruction. This can be used in GCC
13853           // with a "B" modifier that prints the inverted value, for use with
13854           // BIC and MVN instructions. It is not useful otherwise but is
13855           // implemented for compatibility.
13856           if (ARM_AM::getSOImmVal(~CVal) != -1)
13857             break;
13858         }
13859         return;
13860 
13861       case 'L':
13862         if (Subtarget->isThumb1Only()) {
13863           // This must be a constant between -7 and 7,
13864           // for 3-operand ADD/SUB immediate instructions.
13865           if (CVal >= -7 && CVal < 7)
13866             break;
13867         } else if (Subtarget->isThumb2()) {
13868           // A constant whose negation can be used as an immediate value in a
13869           // data-processing instruction. This can be used in GCC with an "n"
13870           // modifier that prints the negated value, for use with SUB
13871           // instructions. It is not useful otherwise but is implemented for
13872           // compatibility.
13873           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
13874             break;
13875         } else {
13876           // A constant whose negation can be used as an immediate value in a
13877           // data-processing instruction. This can be used in GCC with an "n"
13878           // modifier that prints the negated value, for use with SUB
13879           // instructions. It is not useful otherwise but is implemented for
13880           // compatibility.
13881           if (ARM_AM::getSOImmVal(-CVal) != -1)
13882             break;
13883         }
13884         return;
13885 
13886       case 'M':
13887         if (Subtarget->isThumb1Only()) {
13888           // This must be a multiple of 4 between 0 and 1020, for
13889           // ADD sp + immediate.
13890           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
13891             break;
13892         } else {
13893           // A power of two or a constant between 0 and 32.  This is used in
13894           // GCC for the shift amount on shifted register operands, but it is
13895           // useful in general for any shift amounts.
13896           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
13897             break;
13898         }
13899         return;
13900 
13901       case 'N':
13902         if (Subtarget->isThumb()) {  // FIXME thumb2
13903           // This must be a constant between 0 and 31, for shift amounts.
13904           if (CVal >= 0 && CVal <= 31)
13905             break;
13906         }
13907         return;
13908 
13909       case 'O':
13910         if (Subtarget->isThumb()) {  // FIXME thumb2
13911           // This must be a multiple of 4 between -508 and 508, for
13912           // ADD/SUB sp = sp + immediate.
13913           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
13914             break;
13915         }
13916         return;
13917     }
13918     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
13919     break;
13920   }
13921 
13922   if (Result.getNode()) {
13923     Ops.push_back(Result);
13924     return;
13925   }
13926   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13927 }
13928 
13929 static RTLIB::Libcall getDivRemLibcall(
13930     const SDNode *N, MVT::SimpleValueType SVT) {
13931   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13932           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13933          "Unhandled Opcode in getDivRemLibcall");
13934   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13935                   N->getOpcode() == ISD::SREM;
13936   RTLIB::Libcall LC;
13937   switch (SVT) {
13938   default: llvm_unreachable("Unexpected request for libcall!");
13939   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
13940   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
13941   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
13942   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
13943   }
13944   return LC;
13945 }
13946 
13947 static TargetLowering::ArgListTy getDivRemArgList(
13948     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
13949   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13950           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13951          "Unhandled Opcode in getDivRemArgList");
13952   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13953                   N->getOpcode() == ISD::SREM;
13954   TargetLowering::ArgListTy Args;
13955   TargetLowering::ArgListEntry Entry;
13956   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13957     EVT ArgVT = N->getOperand(i).getValueType();
13958     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
13959     Entry.Node = N->getOperand(i);
13960     Entry.Ty = ArgTy;
13961     Entry.IsSExt = isSigned;
13962     Entry.IsZExt = !isSigned;
13963     Args.push_back(Entry);
13964   }
13965   if (Subtarget->isTargetWindows() && Args.size() >= 2)
13966     std::swap(Args[0], Args[1]);
13967   return Args;
13968 }
13969 
13970 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
13971   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
13972           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
13973           Subtarget->isTargetWindows()) &&
13974          "Register-based DivRem lowering only");
13975   unsigned Opcode = Op->getOpcode();
13976   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
13977          "Invalid opcode for Div/Rem lowering");
13978   bool isSigned = (Opcode == ISD::SDIVREM);
13979   EVT VT = Op->getValueType(0);
13980   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
13981   SDLoc dl(Op);
13982 
13983   // If the target has hardware divide, use divide + multiply + subtract:
13984   //     div = a / b
13985   //     rem = a - b * div
13986   //     return {div, rem}
13987   // This should be lowered into UDIV/SDIV + MLS later on.
13988   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
13989                                         : Subtarget->hasDivideInARMMode();
13990   if (hasDivide && Op->getValueType(0).isSimple() &&
13991       Op->getSimpleValueType(0) == MVT::i32) {
13992     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
13993     const SDValue Dividend = Op->getOperand(0);
13994     const SDValue Divisor = Op->getOperand(1);
13995     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
13996     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
13997     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13998 
13999     SDValue Values[2] = {Div, Rem};
14000     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
14001   }
14002 
14003   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
14004                                        VT.getSimpleVT().SimpleTy);
14005   SDValue InChain = DAG.getEntryNode();
14006 
14007   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
14008                                                     DAG.getContext(),
14009                                                     Subtarget);
14010 
14011   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
14012                                          getPointerTy(DAG.getDataLayout()));
14013 
14014   Type *RetTy = StructType::get(Ty, Ty);
14015 
14016   if (Subtarget->isTargetWindows())
14017     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
14018 
14019   TargetLowering::CallLoweringInfo CLI(DAG);
14020   CLI.setDebugLoc(dl).setChain(InChain)
14021     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
14022     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
14023 
14024   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
14025   return CallInfo.first;
14026 }
14027 
14028 // Lowers REM using divmod helpers
14029 // see RTABI section 4.2/4.3
14030 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
14031   // Build return types (div and rem)
14032   std::vector<Type*> RetTyParams;
14033   Type *RetTyElement;
14034 
14035   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
14036   default: llvm_unreachable("Unexpected request for libcall!");
14037   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
14038   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
14039   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
14040   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
14041   }
14042 
14043   RetTyParams.push_back(RetTyElement);
14044   RetTyParams.push_back(RetTyElement);
14045   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
14046   Type *RetTy = StructType::get(*DAG.getContext(), ret);
14047 
14048   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
14049                                                              SimpleTy);
14050   SDValue InChain = DAG.getEntryNode();
14051   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
14052                                                     Subtarget);
14053   bool isSigned = N->getOpcode() == ISD::SREM;
14054   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
14055                                          getPointerTy(DAG.getDataLayout()));
14056 
14057   if (Subtarget->isTargetWindows())
14058     InChain = WinDBZCheckDenominator(DAG, N, InChain);
14059 
14060   // Lower call
14061   CallLoweringInfo CLI(DAG);
14062   CLI.setChain(InChain)
14063      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
14064      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
14065   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
14066 
14067   // Return second (rem) result operand (first contains div)
14068   SDNode *ResNode = CallResult.first.getNode();
14069   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
14070   return ResNode->getOperand(1);
14071 }
14072 
14073 SDValue
14074 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
14075   assert(Subtarget->isTargetWindows() && "unsupported target platform");
14076   SDLoc DL(Op);
14077 
14078   // Get the inputs.
14079   SDValue Chain = Op.getOperand(0);
14080   SDValue Size  = Op.getOperand(1);
14081 
14082   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
14083           "no-stack-arg-probe")) {
14084     unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14085     SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
14086     Chain = SP.getValue(1);
14087     SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
14088     if (Align)
14089       SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
14090                        DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
14091     Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
14092     SDValue Ops[2] = { SP, Chain };
14093     return DAG.getMergeValues(Ops, DL);
14094   }
14095 
14096   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
14097                               DAG.getConstant(2, DL, MVT::i32));
14098 
14099   SDValue Flag;
14100   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
14101   Flag = Chain.getValue(1);
14102 
14103   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14104   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
14105 
14106   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
14107   Chain = NewSP.getValue(1);
14108 
14109   SDValue Ops[2] = { NewSP, Chain };
14110   return DAG.getMergeValues(Ops, DL);
14111 }
14112 
14113 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
14114   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
14115          "Unexpected type for custom-lowering FP_EXTEND");
14116 
14117   RTLIB::Libcall LC;
14118   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
14119 
14120   SDValue SrcVal = Op.getOperand(0);
14121   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
14122                      SDLoc(Op)).first;
14123 }
14124 
14125 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
14126   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
14127          Subtarget->isFPOnlySP() &&
14128          "Unexpected type for custom-lowering FP_ROUND");
14129 
14130   RTLIB::Libcall LC;
14131   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
14132 
14133   SDValue SrcVal = Op.getOperand(0);
14134   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
14135                      SDLoc(Op)).first;
14136 }
14137 
14138 bool
14139 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14140   // The ARM target isn't yet aware of offsets.
14141   return false;
14142 }
14143 
14144 bool ARM::isBitFieldInvertedMask(unsigned v) {
14145   if (v == 0xffffffff)
14146     return false;
14147 
14148   // there can be 1's on either or both "outsides", all the "inside"
14149   // bits must be 0's
14150   return isShiftedMask_32(~v);
14151 }
14152 
14153 /// isFPImmLegal - Returns true if the target can instruction select the
14154 /// specified FP immediate natively. If false, the legalizer will
14155 /// materialize the FP immediate as a load from a constant pool.
14156 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
14157   if (!Subtarget->hasVFP3())
14158     return false;
14159   if (VT == MVT::f16 && Subtarget->hasFullFP16())
14160     return ARM_AM::getFP16Imm(Imm) != -1;
14161   if (VT == MVT::f32)
14162     return ARM_AM::getFP32Imm(Imm) != -1;
14163   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
14164     return ARM_AM::getFP64Imm(Imm) != -1;
14165   return false;
14166 }
14167 
14168 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
14169 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
14170 /// specified in the intrinsic calls.
14171 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14172                                            const CallInst &I,
14173                                            MachineFunction &MF,
14174                                            unsigned Intrinsic) const {
14175   switch (Intrinsic) {
14176   case Intrinsic::arm_neon_vld1:
14177   case Intrinsic::arm_neon_vld2:
14178   case Intrinsic::arm_neon_vld3:
14179   case Intrinsic::arm_neon_vld4:
14180   case Intrinsic::arm_neon_vld2lane:
14181   case Intrinsic::arm_neon_vld3lane:
14182   case Intrinsic::arm_neon_vld4lane:
14183   case Intrinsic::arm_neon_vld2dup:
14184   case Intrinsic::arm_neon_vld3dup:
14185   case Intrinsic::arm_neon_vld4dup: {
14186     Info.opc = ISD::INTRINSIC_W_CHAIN;
14187     // Conservatively set memVT to the entire set of vectors loaded.
14188     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14189     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
14190     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14191     Info.ptrVal = I.getArgOperand(0);
14192     Info.offset = 0;
14193     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
14194     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
14195     // volatile loads with NEON intrinsics not supported
14196     Info.flags = MachineMemOperand::MOLoad;
14197     return true;
14198   }
14199   case Intrinsic::arm_neon_vld1x2:
14200   case Intrinsic::arm_neon_vld1x3:
14201   case Intrinsic::arm_neon_vld1x4: {
14202     Info.opc = ISD::INTRINSIC_W_CHAIN;
14203     // Conservatively set memVT to the entire set of vectors loaded.
14204     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14205     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
14206     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14207     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
14208     Info.offset = 0;
14209     Info.align = 0;
14210     // volatile loads with NEON intrinsics not supported
14211     Info.flags = MachineMemOperand::MOLoad;
14212     return true;
14213   }
14214   case Intrinsic::arm_neon_vst1:
14215   case Intrinsic::arm_neon_vst2:
14216   case Intrinsic::arm_neon_vst3:
14217   case Intrinsic::arm_neon_vst4:
14218   case Intrinsic::arm_neon_vst2lane:
14219   case Intrinsic::arm_neon_vst3lane:
14220   case Intrinsic::arm_neon_vst4lane: {
14221     Info.opc = ISD::INTRINSIC_VOID;
14222     // Conservatively set memVT to the entire set of vectors stored.
14223     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14224     unsigned NumElts = 0;
14225     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
14226       Type *ArgTy = I.getArgOperand(ArgI)->getType();
14227       if (!ArgTy->isVectorTy())
14228         break;
14229       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
14230     }
14231     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14232     Info.ptrVal = I.getArgOperand(0);
14233     Info.offset = 0;
14234     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
14235     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
14236     // volatile stores with NEON intrinsics not supported
14237     Info.flags = MachineMemOperand::MOStore;
14238     return true;
14239   }
14240   case Intrinsic::arm_neon_vst1x2:
14241   case Intrinsic::arm_neon_vst1x3:
14242   case Intrinsic::arm_neon_vst1x4: {
14243     Info.opc = ISD::INTRINSIC_VOID;
14244     // Conservatively set memVT to the entire set of vectors stored.
14245     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14246     unsigned NumElts = 0;
14247     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
14248       Type *ArgTy = I.getArgOperand(ArgI)->getType();
14249       if (!ArgTy->isVectorTy())
14250         break;
14251       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
14252     }
14253     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14254     Info.ptrVal = I.getArgOperand(0);
14255     Info.offset = 0;
14256     Info.align = 0;
14257     // volatile stores with NEON intrinsics not supported
14258     Info.flags = MachineMemOperand::MOStore;
14259     return true;
14260   }
14261   case Intrinsic::arm_ldaex:
14262   case Intrinsic::arm_ldrex: {
14263     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14264     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
14265     Info.opc = ISD::INTRINSIC_W_CHAIN;
14266     Info.memVT = MVT::getVT(PtrTy->getElementType());
14267     Info.ptrVal = I.getArgOperand(0);
14268     Info.offset = 0;
14269     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
14270     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
14271     return true;
14272   }
14273   case Intrinsic::arm_stlex:
14274   case Intrinsic::arm_strex: {
14275     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14276     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
14277     Info.opc = ISD::INTRINSIC_W_CHAIN;
14278     Info.memVT = MVT::getVT(PtrTy->getElementType());
14279     Info.ptrVal = I.getArgOperand(1);
14280     Info.offset = 0;
14281     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
14282     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
14283     return true;
14284   }
14285   case Intrinsic::arm_stlexd:
14286   case Intrinsic::arm_strexd:
14287     Info.opc = ISD::INTRINSIC_W_CHAIN;
14288     Info.memVT = MVT::i64;
14289     Info.ptrVal = I.getArgOperand(2);
14290     Info.offset = 0;
14291     Info.align = 8;
14292     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
14293     return true;
14294 
14295   case Intrinsic::arm_ldaexd:
14296   case Intrinsic::arm_ldrexd:
14297     Info.opc = ISD::INTRINSIC_W_CHAIN;
14298     Info.memVT = MVT::i64;
14299     Info.ptrVal = I.getArgOperand(0);
14300     Info.offset = 0;
14301     Info.align = 8;
14302     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
14303     return true;
14304 
14305   default:
14306     break;
14307   }
14308 
14309   return false;
14310 }
14311 
14312 /// Returns true if it is beneficial to convert a load of a constant
14313 /// to just the constant itself.
14314 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
14315                                                           Type *Ty) const {
14316   assert(Ty->isIntegerTy());
14317 
14318   unsigned Bits = Ty->getPrimitiveSizeInBits();
14319   if (Bits == 0 || Bits > 32)
14320     return false;
14321   return true;
14322 }
14323 
14324 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
14325                                                 unsigned Index) const {
14326   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
14327     return false;
14328 
14329   return (Index == 0 || Index == ResVT.getVectorNumElements());
14330 }
14331 
14332 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
14333                                         ARM_MB::MemBOpt Domain) const {
14334   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14335 
14336   // First, if the target has no DMB, see what fallback we can use.
14337   if (!Subtarget->hasDataBarrier()) {
14338     // Some ARMv6 cpus can support data barriers with an mcr instruction.
14339     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
14340     // here.
14341     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
14342       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
14343       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
14344                         Builder.getInt32(0), Builder.getInt32(7),
14345                         Builder.getInt32(10), Builder.getInt32(5)};
14346       return Builder.CreateCall(MCR, args);
14347     } else {
14348       // Instead of using barriers, atomic accesses on these subtargets use
14349       // libcalls.
14350       llvm_unreachable("makeDMB on a target so old that it has no barriers");
14351     }
14352   } else {
14353     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
14354     // Only a full system barrier exists in the M-class architectures.
14355     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
14356     Constant *CDomain = Builder.getInt32(Domain);
14357     return Builder.CreateCall(DMB, CDomain);
14358   }
14359 }
14360 
14361 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
14362 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
14363                                                  Instruction *Inst,
14364                                                  AtomicOrdering Ord) const {
14365   switch (Ord) {
14366   case AtomicOrdering::NotAtomic:
14367   case AtomicOrdering::Unordered:
14368     llvm_unreachable("Invalid fence: unordered/non-atomic");
14369   case AtomicOrdering::Monotonic:
14370   case AtomicOrdering::Acquire:
14371     return nullptr; // Nothing to do
14372   case AtomicOrdering::SequentiallyConsistent:
14373     if (!Inst->hasAtomicStore())
14374       return nullptr; // Nothing to do
14375     LLVM_FALLTHROUGH;
14376   case AtomicOrdering::Release:
14377   case AtomicOrdering::AcquireRelease:
14378     if (Subtarget->preferISHSTBarriers())
14379       return makeDMB(Builder, ARM_MB::ISHST);
14380     // FIXME: add a comment with a link to documentation justifying this.
14381     else
14382       return makeDMB(Builder, ARM_MB::ISH);
14383   }
14384   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
14385 }
14386 
14387 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
14388                                                   Instruction *Inst,
14389                                                   AtomicOrdering Ord) const {
14390   switch (Ord) {
14391   case AtomicOrdering::NotAtomic:
14392   case AtomicOrdering::Unordered:
14393     llvm_unreachable("Invalid fence: unordered/not-atomic");
14394   case AtomicOrdering::Monotonic:
14395   case AtomicOrdering::Release:
14396     return nullptr; // Nothing to do
14397   case AtomicOrdering::Acquire:
14398   case AtomicOrdering::AcquireRelease:
14399   case AtomicOrdering::SequentiallyConsistent:
14400     return makeDMB(Builder, ARM_MB::ISH);
14401   }
14402   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
14403 }
14404 
14405 // Loads and stores less than 64-bits are already atomic; ones above that
14406 // are doomed anyway, so defer to the default libcall and blame the OS when
14407 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
14408 // anything for those.
14409 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
14410   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
14411   return (Size == 64) && !Subtarget->isMClass();
14412 }
14413 
14414 // Loads and stores less than 64-bits are already atomic; ones above that
14415 // are doomed anyway, so defer to the default libcall and blame the OS when
14416 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
14417 // anything for those.
14418 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
14419 // guarantee, see DDI0406C ARM architecture reference manual,
14420 // sections A8.8.72-74 LDRD)
14421 TargetLowering::AtomicExpansionKind
14422 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
14423   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
14424   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
14425                                                   : AtomicExpansionKind::None;
14426 }
14427 
14428 // For the real atomic operations, we have ldrex/strex up to 32 bits,
14429 // and up to 64 bits on the non-M profiles
14430 TargetLowering::AtomicExpansionKind
14431 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
14432   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
14433   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
14434   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
14435              ? AtomicExpansionKind::LLSC
14436              : AtomicExpansionKind::None;
14437 }
14438 
14439 TargetLowering::AtomicExpansionKind
14440 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
14441   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
14442   // implement cmpxchg without spilling. If the address being exchanged is also
14443   // on the stack and close enough to the spill slot, this can lead to a
14444   // situation where the monitor always gets cleared and the atomic operation
14445   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
14446   bool HasAtomicCmpXchg =
14447       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
14448   if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
14449     return AtomicExpansionKind::LLSC;
14450   return AtomicExpansionKind::None;
14451 }
14452 
14453 bool ARMTargetLowering::shouldInsertFencesForAtomic(
14454     const Instruction *I) const {
14455   return InsertFencesForAtomic;
14456 }
14457 
14458 // This has so far only been implemented for MachO.
14459 bool ARMTargetLowering::useLoadStackGuardNode() const {
14460   return Subtarget->isTargetMachO();
14461 }
14462 
14463 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
14464                                                   unsigned &Cost) const {
14465   // If we do not have NEON, vector types are not natively supported.
14466   if (!Subtarget->hasNEON())
14467     return false;
14468 
14469   // Floating point values and vector values map to the same register file.
14470   // Therefore, although we could do a store extract of a vector type, this is
14471   // better to leave at float as we have more freedom in the addressing mode for
14472   // those.
14473   if (VectorTy->isFPOrFPVectorTy())
14474     return false;
14475 
14476   // If the index is unknown at compile time, this is very expensive to lower
14477   // and it is not possible to combine the store with the extract.
14478   if (!isa<ConstantInt>(Idx))
14479     return false;
14480 
14481   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
14482   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
14483   // We can do a store + vector extract on any vector that fits perfectly in a D
14484   // or Q register.
14485   if (BitWidth == 64 || BitWidth == 128) {
14486     Cost = 0;
14487     return true;
14488   }
14489   return false;
14490 }
14491 
14492 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
14493   return Subtarget->hasV6T2Ops();
14494 }
14495 
14496 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
14497   return Subtarget->hasV6T2Ops();
14498 }
14499 
14500 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
14501                                          AtomicOrdering Ord) const {
14502   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14503   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
14504   bool IsAcquire = isAcquireOrStronger(Ord);
14505 
14506   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
14507   // intrinsic must return {i32, i32} and we have to recombine them into a
14508   // single i64 here.
14509   if (ValTy->getPrimitiveSizeInBits() == 64) {
14510     Intrinsic::ID Int =
14511         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
14512     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
14513 
14514     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14515     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
14516 
14517     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
14518     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
14519     if (!Subtarget->isLittle())
14520       std::swap (Lo, Hi);
14521     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
14522     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
14523     return Builder.CreateOr(
14524         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
14525   }
14526 
14527   Type *Tys[] = { Addr->getType() };
14528   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
14529   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
14530 
14531   return Builder.CreateTruncOrBitCast(
14532       Builder.CreateCall(Ldrex, Addr),
14533       cast<PointerType>(Addr->getType())->getElementType());
14534 }
14535 
14536 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
14537     IRBuilder<> &Builder) const {
14538   if (!Subtarget->hasV7Ops())
14539     return;
14540   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14541   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
14542 }
14543 
14544 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
14545                                                Value *Addr,
14546                                                AtomicOrdering Ord) const {
14547   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14548   bool IsRelease = isReleaseOrStronger(Ord);
14549 
14550   // Since the intrinsics must have legal type, the i64 intrinsics take two
14551   // parameters: "i32, i32". We must marshal Val into the appropriate form
14552   // before the call.
14553   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
14554     Intrinsic::ID Int =
14555         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
14556     Function *Strex = Intrinsic::getDeclaration(M, Int);
14557     Type *Int32Ty = Type::getInt32Ty(M->getContext());
14558 
14559     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
14560     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
14561     if (!Subtarget->isLittle())
14562       std::swap(Lo, Hi);
14563     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14564     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
14565   }
14566 
14567   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
14568   Type *Tys[] = { Addr->getType() };
14569   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
14570 
14571   return Builder.CreateCall(
14572       Strex, {Builder.CreateZExtOrBitCast(
14573                   Val, Strex->getFunctionType()->getParamType(0)),
14574               Addr});
14575 }
14576 
14577 
14578 bool ARMTargetLowering::alignLoopsWithOptSize() const {
14579   return Subtarget->isMClass();
14580 }
14581 
14582 /// A helper function for determining the number of interleaved accesses we
14583 /// will generate when lowering accesses of the given type.
14584 unsigned
14585 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
14586                                              const DataLayout &DL) const {
14587   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
14588 }
14589 
14590 bool ARMTargetLowering::isLegalInterleavedAccessType(
14591     VectorType *VecTy, const DataLayout &DL) const {
14592 
14593   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
14594   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
14595 
14596   // Ensure the vector doesn't have f16 elements. Even though we could do an
14597   // i16 vldN, we can't hold the f16 vectors and will end up converting via
14598   // f32.
14599   if (VecTy->getElementType()->isHalfTy())
14600     return false;
14601 
14602   // Ensure the number of vector elements is greater than 1.
14603   if (VecTy->getNumElements() < 2)
14604     return false;
14605 
14606   // Ensure the element type is legal.
14607   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
14608     return false;
14609 
14610   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
14611   // 128 will be split into multiple interleaved accesses.
14612   return VecSize == 64 || VecSize % 128 == 0;
14613 }
14614 
14615 /// Lower an interleaved load into a vldN intrinsic.
14616 ///
14617 /// E.g. Lower an interleaved load (Factor = 2):
14618 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
14619 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
14620 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
14621 ///
14622 ///      Into:
14623 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
14624 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
14625 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
14626 bool ARMTargetLowering::lowerInterleavedLoad(
14627     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
14628     ArrayRef<unsigned> Indices, unsigned Factor) const {
14629   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14630          "Invalid interleave factor");
14631   assert(!Shuffles.empty() && "Empty shufflevector input");
14632   assert(Shuffles.size() == Indices.size() &&
14633          "Unmatched number of shufflevectors and indices");
14634 
14635   VectorType *VecTy = Shuffles[0]->getType();
14636   Type *EltTy = VecTy->getVectorElementType();
14637 
14638   const DataLayout &DL = LI->getModule()->getDataLayout();
14639 
14640   // Skip if we do not have NEON and skip illegal vector types. We can
14641   // "legalize" wide vector types into multiple interleaved accesses as long as
14642   // the vector types are divisible by 128.
14643   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
14644     return false;
14645 
14646   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
14647 
14648   // A pointer vector can not be the return type of the ldN intrinsics. Need to
14649   // load integer vectors first and then convert to pointer vectors.
14650   if (EltTy->isPointerTy())
14651     VecTy =
14652         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
14653 
14654   IRBuilder<> Builder(LI);
14655 
14656   // The base address of the load.
14657   Value *BaseAddr = LI->getPointerOperand();
14658 
14659   if (NumLoads > 1) {
14660     // If we're going to generate more than one load, reset the sub-vector type
14661     // to something legal.
14662     VecTy = VectorType::get(VecTy->getVectorElementType(),
14663                             VecTy->getVectorNumElements() / NumLoads);
14664 
14665     // We will compute the pointer operand of each load from the original base
14666     // address using GEPs. Cast the base address to a pointer to the scalar
14667     // element type.
14668     BaseAddr = Builder.CreateBitCast(
14669         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
14670                       LI->getPointerAddressSpace()));
14671   }
14672 
14673   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
14674 
14675   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
14676   Type *Tys[] = {VecTy, Int8Ptr};
14677   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
14678                                             Intrinsic::arm_neon_vld3,
14679                                             Intrinsic::arm_neon_vld4};
14680   Function *VldnFunc =
14681       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
14682 
14683   // Holds sub-vectors extracted from the load intrinsic return values. The
14684   // sub-vectors are associated with the shufflevector instructions they will
14685   // replace.
14686   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
14687 
14688   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
14689     // If we're generating more than one load, compute the base address of
14690     // subsequent loads as an offset from the previous.
14691     if (LoadCount > 0)
14692       BaseAddr = Builder.CreateConstGEP1_32(
14693           BaseAddr, VecTy->getVectorNumElements() * Factor);
14694 
14695     SmallVector<Value *, 2> Ops;
14696     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14697     Ops.push_back(Builder.getInt32(LI->getAlignment()));
14698 
14699     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
14700 
14701     // Replace uses of each shufflevector with the corresponding vector loaded
14702     // by ldN.
14703     for (unsigned i = 0; i < Shuffles.size(); i++) {
14704       ShuffleVectorInst *SV = Shuffles[i];
14705       unsigned Index = Indices[i];
14706 
14707       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
14708 
14709       // Convert the integer vector to pointer vector if the element is pointer.
14710       if (EltTy->isPointerTy())
14711         SubVec = Builder.CreateIntToPtr(
14712             SubVec, VectorType::get(SV->getType()->getVectorElementType(),
14713                                     VecTy->getVectorNumElements()));
14714 
14715       SubVecs[SV].push_back(SubVec);
14716     }
14717   }
14718 
14719   // Replace uses of the shufflevector instructions with the sub-vectors
14720   // returned by the load intrinsic. If a shufflevector instruction is
14721   // associated with more than one sub-vector, those sub-vectors will be
14722   // concatenated into a single wide vector.
14723   for (ShuffleVectorInst *SVI : Shuffles) {
14724     auto &SubVec = SubVecs[SVI];
14725     auto *WideVec =
14726         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
14727     SVI->replaceAllUsesWith(WideVec);
14728   }
14729 
14730   return true;
14731 }
14732 
14733 /// Lower an interleaved store into a vstN intrinsic.
14734 ///
14735 /// E.g. Lower an interleaved store (Factor = 3):
14736 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
14737 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
14738 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
14739 ///
14740 ///      Into:
14741 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
14742 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
14743 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
14744 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14745 ///
14746 /// Note that the new shufflevectors will be removed and we'll only generate one
14747 /// vst3 instruction in CodeGen.
14748 ///
14749 /// Example for a more general valid mask (Factor 3). Lower:
14750 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
14751 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
14752 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
14753 ///
14754 ///      Into:
14755 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
14756 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
14757 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
14758 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14759 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
14760                                               ShuffleVectorInst *SVI,
14761                                               unsigned Factor) const {
14762   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14763          "Invalid interleave factor");
14764 
14765   VectorType *VecTy = SVI->getType();
14766   assert(VecTy->getVectorNumElements() % Factor == 0 &&
14767          "Invalid interleaved store");
14768 
14769   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
14770   Type *EltTy = VecTy->getVectorElementType();
14771   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
14772 
14773   const DataLayout &DL = SI->getModule()->getDataLayout();
14774 
14775   // Skip if we do not have NEON and skip illegal vector types. We can
14776   // "legalize" wide vector types into multiple interleaved accesses as long as
14777   // the vector types are divisible by 128.
14778   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
14779     return false;
14780 
14781   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
14782 
14783   Value *Op0 = SVI->getOperand(0);
14784   Value *Op1 = SVI->getOperand(1);
14785   IRBuilder<> Builder(SI);
14786 
14787   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
14788   // vectors to integer vectors.
14789   if (EltTy->isPointerTy()) {
14790     Type *IntTy = DL.getIntPtrType(EltTy);
14791 
14792     // Convert to the corresponding integer vector.
14793     Type *IntVecTy =
14794         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
14795     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
14796     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
14797 
14798     SubVecTy = VectorType::get(IntTy, LaneLen);
14799   }
14800 
14801   // The base address of the store.
14802   Value *BaseAddr = SI->getPointerOperand();
14803 
14804   if (NumStores > 1) {
14805     // If we're going to generate more than one store, reset the lane length
14806     // and sub-vector type to something legal.
14807     LaneLen /= NumStores;
14808     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
14809 
14810     // We will compute the pointer operand of each store from the original base
14811     // address using GEPs. Cast the base address to a pointer to the scalar
14812     // element type.
14813     BaseAddr = Builder.CreateBitCast(
14814         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
14815                       SI->getPointerAddressSpace()));
14816   }
14817 
14818   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
14819 
14820   auto Mask = SVI->getShuffleMask();
14821 
14822   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
14823   Type *Tys[] = {Int8Ptr, SubVecTy};
14824   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
14825                                              Intrinsic::arm_neon_vst3,
14826                                              Intrinsic::arm_neon_vst4};
14827 
14828   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
14829     // If we generating more than one store, we compute the base address of
14830     // subsequent stores as an offset from the previous.
14831     if (StoreCount > 0)
14832       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
14833 
14834     SmallVector<Value *, 6> Ops;
14835     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14836 
14837     Function *VstNFunc =
14838         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
14839 
14840     // Split the shufflevector operands into sub vectors for the new vstN call.
14841     for (unsigned i = 0; i < Factor; i++) {
14842       unsigned IdxI = StoreCount * LaneLen * Factor + i;
14843       if (Mask[IdxI] >= 0) {
14844         Ops.push_back(Builder.CreateShuffleVector(
14845             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
14846       } else {
14847         unsigned StartMask = 0;
14848         for (unsigned j = 1; j < LaneLen; j++) {
14849           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
14850           if (Mask[IdxJ * Factor + IdxI] >= 0) {
14851             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
14852             break;
14853           }
14854         }
14855         // Note: If all elements in a chunk are undefs, StartMask=0!
14856         // Note: Filling undef gaps with random elements is ok, since
14857         // those elements were being written anyway (with undefs).
14858         // In the case of all undefs we're defaulting to using elems from 0
14859         // Note: StartMask cannot be negative, it's checked in
14860         // isReInterleaveMask
14861         Ops.push_back(Builder.CreateShuffleVector(
14862             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
14863       }
14864     }
14865 
14866     Ops.push_back(Builder.getInt32(SI->getAlignment()));
14867     Builder.CreateCall(VstNFunc, Ops);
14868   }
14869   return true;
14870 }
14871 
14872 enum HABaseType {
14873   HA_UNKNOWN = 0,
14874   HA_FLOAT,
14875   HA_DOUBLE,
14876   HA_VECT64,
14877   HA_VECT128
14878 };
14879 
14880 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
14881                                    uint64_t &Members) {
14882   if (auto *ST = dyn_cast<StructType>(Ty)) {
14883     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
14884       uint64_t SubMembers = 0;
14885       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
14886         return false;
14887       Members += SubMembers;
14888     }
14889   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
14890     uint64_t SubMembers = 0;
14891     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
14892       return false;
14893     Members += SubMembers * AT->getNumElements();
14894   } else if (Ty->isFloatTy()) {
14895     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
14896       return false;
14897     Members = 1;
14898     Base = HA_FLOAT;
14899   } else if (Ty->isDoubleTy()) {
14900     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
14901       return false;
14902     Members = 1;
14903     Base = HA_DOUBLE;
14904   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
14905     Members = 1;
14906     switch (Base) {
14907     case HA_FLOAT:
14908     case HA_DOUBLE:
14909       return false;
14910     case HA_VECT64:
14911       return VT->getBitWidth() == 64;
14912     case HA_VECT128:
14913       return VT->getBitWidth() == 128;
14914     case HA_UNKNOWN:
14915       switch (VT->getBitWidth()) {
14916       case 64:
14917         Base = HA_VECT64;
14918         return true;
14919       case 128:
14920         Base = HA_VECT128;
14921         return true;
14922       default:
14923         return false;
14924       }
14925     }
14926   }
14927 
14928   return (Members > 0 && Members <= 4);
14929 }
14930 
14931 /// Return the correct alignment for the current calling convention.
14932 unsigned
14933 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
14934                                                  DataLayout DL) const {
14935   if (!ArgTy->isVectorTy())
14936     return DL.getABITypeAlignment(ArgTy);
14937 
14938   // Avoid over-aligning vector parameters. It would require realigning the
14939   // stack and waste space for no real benefit.
14940   return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment());
14941 }
14942 
14943 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
14944 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
14945 /// passing according to AAPCS rules.
14946 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
14947     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
14948   if (getEffectiveCallingConv(CallConv, isVarArg) !=
14949       CallingConv::ARM_AAPCS_VFP)
14950     return false;
14951 
14952   HABaseType Base = HA_UNKNOWN;
14953   uint64_t Members = 0;
14954   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
14955   LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
14956 
14957   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
14958   return IsHA || IsIntArray;
14959 }
14960 
14961 unsigned ARMTargetLowering::getExceptionPointerRegister(
14962     const Constant *PersonalityFn) const {
14963   // Platforms which do not use SjLj EH may return values in these registers
14964   // via the personality function.
14965   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
14966 }
14967 
14968 unsigned ARMTargetLowering::getExceptionSelectorRegister(
14969     const Constant *PersonalityFn) const {
14970   // Platforms which do not use SjLj EH may return values in these registers
14971   // via the personality function.
14972   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
14973 }
14974 
14975 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14976   // Update IsSplitCSR in ARMFunctionInfo.
14977   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
14978   AFI->setIsSplitCSR(true);
14979 }
14980 
14981 void ARMTargetLowering::insertCopiesSplitCSR(
14982     MachineBasicBlock *Entry,
14983     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14984   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
14985   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14986   if (!IStart)
14987     return;
14988 
14989   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
14990   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14991   MachineBasicBlock::iterator MBBI = Entry->begin();
14992   for (const MCPhysReg *I = IStart; *I; ++I) {
14993     const TargetRegisterClass *RC = nullptr;
14994     if (ARM::GPRRegClass.contains(*I))
14995       RC = &ARM::GPRRegClass;
14996     else if (ARM::DPRRegClass.contains(*I))
14997       RC = &ARM::DPRRegClass;
14998     else
14999       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15000 
15001     unsigned NewVR = MRI->createVirtualRegister(RC);
15002     // Create copy from CSR to a virtual register.
15003     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15004     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15005     // nounwind. If we want to generalize this later, we may need to emit
15006     // CFI pseudo-instructions.
15007     assert(Entry->getParent()->getFunction().hasFnAttribute(
15008                Attribute::NoUnwind) &&
15009            "Function should be nounwind in insertCopiesSplitCSR!");
15010     Entry->addLiveIn(*I);
15011     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15012         .addReg(*I);
15013 
15014     // Insert the copy-back instructions right before the terminator.
15015     for (auto *Exit : Exits)
15016       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15017               TII->get(TargetOpcode::COPY), *I)
15018           .addReg(NewVR);
15019   }
15020 }
15021 
15022 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
15023   MF.getFrameInfo().computeMaxCallFrameSize(MF);
15024   TargetLoweringBase::finalizeLowering(MF);
15025 }
15026