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   case ARMISD::SUBS:          return "ARMISD::SUBS";
1286 
1287   case ARMISD::SSAT:          return "ARMISD::SSAT";
1288   case ARMISD::USAT:          return "ARMISD::USAT";
1289 
1290   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1291   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1292   case ARMISD::RRX:           return "ARMISD::RRX";
1293 
1294   case ARMISD::ADDC:          return "ARMISD::ADDC";
1295   case ARMISD::ADDE:          return "ARMISD::ADDE";
1296   case ARMISD::SUBC:          return "ARMISD::SUBC";
1297   case ARMISD::SUBE:          return "ARMISD::SUBE";
1298 
1299   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1300   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1301   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
1302   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
1303   case ARMISD::VMOVSR:        return "ARMISD::VMOVSR";
1304 
1305   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1306   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1307   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1308 
1309   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1310 
1311   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1312 
1313   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1314 
1315   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1316 
1317   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1318 
1319   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1320   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1321 
1322   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1323   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1324   case ARMISD::VCGE:          return "ARMISD::VCGE";
1325   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1326   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1327   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1328   case ARMISD::VCGT:          return "ARMISD::VCGT";
1329   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1330   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1331   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1332   case ARMISD::VTST:          return "ARMISD::VTST";
1333 
1334   case ARMISD::VSHL:          return "ARMISD::VSHL";
1335   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1336   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1337   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1338   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1339   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1340   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1341   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1342   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1343   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1344   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1345   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1346   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1347   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1348   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1349   case ARMISD::VSLI:          return "ARMISD::VSLI";
1350   case ARMISD::VSRI:          return "ARMISD::VSRI";
1351   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1352   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1353   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1354   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1355   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1356   case ARMISD::VDUP:          return "ARMISD::VDUP";
1357   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1358   case ARMISD::VEXT:          return "ARMISD::VEXT";
1359   case ARMISD::VREV64:        return "ARMISD::VREV64";
1360   case ARMISD::VREV32:        return "ARMISD::VREV32";
1361   case ARMISD::VREV16:        return "ARMISD::VREV16";
1362   case ARMISD::VZIP:          return "ARMISD::VZIP";
1363   case ARMISD::VUZP:          return "ARMISD::VUZP";
1364   case ARMISD::VTRN:          return "ARMISD::VTRN";
1365   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1366   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1367   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1368   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1369   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1370   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1371   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1372   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1373   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1374   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1375   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1376   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1377   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1378   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1379   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1380   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1381   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1382   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1383   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1384   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1385   case ARMISD::BFI:           return "ARMISD::BFI";
1386   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1387   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1388   case ARMISD::VBSL:          return "ARMISD::VBSL";
1389   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1390   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1391   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1392   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1393   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1394   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1395   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1396   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1397   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1398   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1399   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1400   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1401   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1402   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1403   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1404   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1405   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1406   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1407   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1408   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1409   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1410   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1411   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1412   }
1413   return nullptr;
1414 }
1415 
1416 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1417                                           EVT VT) const {
1418   if (!VT.isVector())
1419     return getPointerTy(DL);
1420   return VT.changeVectorElementTypeToInteger();
1421 }
1422 
1423 /// getRegClassFor - Return the register class that should be used for the
1424 /// specified value type.
1425 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1426   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1427   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1428   // load / store 4 to 8 consecutive D registers.
1429   if (Subtarget->hasNEON()) {
1430     if (VT == MVT::v4i64)
1431       return &ARM::QQPRRegClass;
1432     if (VT == MVT::v8i64)
1433       return &ARM::QQQQPRRegClass;
1434   }
1435   return TargetLowering::getRegClassFor(VT);
1436 }
1437 
1438 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1439 // source/dest is aligned and the copy size is large enough. We therefore want
1440 // to align such objects passed to memory intrinsics.
1441 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1442                                                unsigned &PrefAlign) const {
1443   if (!isa<MemIntrinsic>(CI))
1444     return false;
1445   MinSize = 8;
1446   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1447   // cycle faster than 4-byte aligned LDM.
1448   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1449   return true;
1450 }
1451 
1452 // Create a fast isel object.
1453 FastISel *
1454 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1455                                   const TargetLibraryInfo *libInfo) const {
1456   return ARM::createFastISel(funcInfo, libInfo);
1457 }
1458 
1459 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1460   unsigned NumVals = N->getNumValues();
1461   if (!NumVals)
1462     return Sched::RegPressure;
1463 
1464   for (unsigned i = 0; i != NumVals; ++i) {
1465     EVT VT = N->getValueType(i);
1466     if (VT == MVT::Glue || VT == MVT::Other)
1467       continue;
1468     if (VT.isFloatingPoint() || VT.isVector())
1469       return Sched::ILP;
1470   }
1471 
1472   if (!N->isMachineOpcode())
1473     return Sched::RegPressure;
1474 
1475   // Load are scheduled for latency even if there instruction itinerary
1476   // is not available.
1477   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1478   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1479 
1480   if (MCID.getNumDefs() == 0)
1481     return Sched::RegPressure;
1482   if (!Itins->isEmpty() &&
1483       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1484     return Sched::ILP;
1485 
1486   return Sched::RegPressure;
1487 }
1488 
1489 //===----------------------------------------------------------------------===//
1490 // Lowering Code
1491 //===----------------------------------------------------------------------===//
1492 
1493 static bool isSRL16(const SDValue &Op) {
1494   if (Op.getOpcode() != ISD::SRL)
1495     return false;
1496   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1497     return Const->getZExtValue() == 16;
1498   return false;
1499 }
1500 
1501 static bool isSRA16(const SDValue &Op) {
1502   if (Op.getOpcode() != ISD::SRA)
1503     return false;
1504   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1505     return Const->getZExtValue() == 16;
1506   return false;
1507 }
1508 
1509 static bool isSHL16(const SDValue &Op) {
1510   if (Op.getOpcode() != ISD::SHL)
1511     return false;
1512   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1513     return Const->getZExtValue() == 16;
1514   return false;
1515 }
1516 
1517 // Check for a signed 16-bit value. We special case SRA because it makes it
1518 // more simple when also looking for SRAs that aren't sign extending a
1519 // smaller value. Without the check, we'd need to take extra care with
1520 // checking order for some operations.
1521 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1522   if (isSRA16(Op))
1523     return isSHL16(Op.getOperand(0));
1524   return DAG.ComputeNumSignBits(Op) == 17;
1525 }
1526 
1527 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1528 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1529   switch (CC) {
1530   default: llvm_unreachable("Unknown condition code!");
1531   case ISD::SETNE:  return ARMCC::NE;
1532   case ISD::SETEQ:  return ARMCC::EQ;
1533   case ISD::SETGT:  return ARMCC::GT;
1534   case ISD::SETGE:  return ARMCC::GE;
1535   case ISD::SETLT:  return ARMCC::LT;
1536   case ISD::SETLE:  return ARMCC::LE;
1537   case ISD::SETUGT: return ARMCC::HI;
1538   case ISD::SETUGE: return ARMCC::HS;
1539   case ISD::SETULT: return ARMCC::LO;
1540   case ISD::SETULE: return ARMCC::LS;
1541   }
1542 }
1543 
1544 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1545 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1546                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1547   CondCode2 = ARMCC::AL;
1548   InvalidOnQNaN = true;
1549   switch (CC) {
1550   default: llvm_unreachable("Unknown FP condition!");
1551   case ISD::SETEQ:
1552   case ISD::SETOEQ:
1553     CondCode = ARMCC::EQ;
1554     InvalidOnQNaN = false;
1555     break;
1556   case ISD::SETGT:
1557   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1558   case ISD::SETGE:
1559   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1560   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1561   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1562   case ISD::SETONE:
1563     CondCode = ARMCC::MI;
1564     CondCode2 = ARMCC::GT;
1565     InvalidOnQNaN = false;
1566     break;
1567   case ISD::SETO:   CondCode = ARMCC::VC; break;
1568   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1569   case ISD::SETUEQ:
1570     CondCode = ARMCC::EQ;
1571     CondCode2 = ARMCC::VS;
1572     InvalidOnQNaN = false;
1573     break;
1574   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1575   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1576   case ISD::SETLT:
1577   case ISD::SETULT: CondCode = ARMCC::LT; break;
1578   case ISD::SETLE:
1579   case ISD::SETULE: CondCode = ARMCC::LE; break;
1580   case ISD::SETNE:
1581   case ISD::SETUNE:
1582     CondCode = ARMCC::NE;
1583     InvalidOnQNaN = false;
1584     break;
1585   }
1586 }
1587 
1588 //===----------------------------------------------------------------------===//
1589 //                      Calling Convention Implementation
1590 //===----------------------------------------------------------------------===//
1591 
1592 #include "ARMGenCallingConv.inc"
1593 
1594 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1595 /// account presence of floating point hardware and calling convention
1596 /// limitations, such as support for variadic functions.
1597 CallingConv::ID
1598 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1599                                            bool isVarArg) const {
1600   switch (CC) {
1601   default:
1602     report_fatal_error("Unsupported calling convention");
1603   case CallingConv::ARM_AAPCS:
1604   case CallingConv::ARM_APCS:
1605   case CallingConv::GHC:
1606     return CC;
1607   case CallingConv::PreserveMost:
1608     return CallingConv::PreserveMost;
1609   case CallingConv::ARM_AAPCS_VFP:
1610   case CallingConv::Swift:
1611     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1612   case CallingConv::C:
1613     if (!Subtarget->isAAPCS_ABI())
1614       return CallingConv::ARM_APCS;
1615     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1616              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1617              !isVarArg)
1618       return CallingConv::ARM_AAPCS_VFP;
1619     else
1620       return CallingConv::ARM_AAPCS;
1621   case CallingConv::Fast:
1622   case CallingConv::CXX_FAST_TLS:
1623     if (!Subtarget->isAAPCS_ABI()) {
1624       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1625         return CallingConv::Fast;
1626       return CallingConv::ARM_APCS;
1627     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1628       return CallingConv::ARM_AAPCS_VFP;
1629     else
1630       return CallingConv::ARM_AAPCS;
1631   }
1632 }
1633 
1634 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1635                                                  bool isVarArg) const {
1636   return CCAssignFnForNode(CC, false, isVarArg);
1637 }
1638 
1639 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1640                                                    bool isVarArg) const {
1641   return CCAssignFnForNode(CC, true, isVarArg);
1642 }
1643 
1644 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1645 /// CallingConvention.
1646 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1647                                                  bool Return,
1648                                                  bool isVarArg) const {
1649   switch (getEffectiveCallingConv(CC, isVarArg)) {
1650   default:
1651     report_fatal_error("Unsupported calling convention");
1652   case CallingConv::ARM_APCS:
1653     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1654   case CallingConv::ARM_AAPCS:
1655     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1656   case CallingConv::ARM_AAPCS_VFP:
1657     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1658   case CallingConv::Fast:
1659     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1660   case CallingConv::GHC:
1661     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1662   case CallingConv::PreserveMost:
1663     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1664   }
1665 }
1666 
1667 /// LowerCallResult - Lower the result values of a call into the
1668 /// appropriate copies out of appropriate physical registers.
1669 SDValue ARMTargetLowering::LowerCallResult(
1670     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1671     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1672     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1673     SDValue ThisVal) const {
1674   // Assign locations to each value returned by this call.
1675   SmallVector<CCValAssign, 16> RVLocs;
1676   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1677                  *DAG.getContext());
1678   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1679 
1680   // Copy all of the result registers out of their specified physreg.
1681   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1682     CCValAssign VA = RVLocs[i];
1683 
1684     // Pass 'this' value directly from the argument to return value, to avoid
1685     // reg unit interference
1686     if (i == 0 && isThisReturn) {
1687       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1688              "unexpected return calling convention register assignment");
1689       InVals.push_back(ThisVal);
1690       continue;
1691     }
1692 
1693     SDValue Val;
1694     if (VA.needsCustom()) {
1695       // Handle f64 or half of a v2f64.
1696       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1697                                       InFlag);
1698       Chain = Lo.getValue(1);
1699       InFlag = Lo.getValue(2);
1700       VA = RVLocs[++i]; // skip ahead to next loc
1701       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1702                                       InFlag);
1703       Chain = Hi.getValue(1);
1704       InFlag = Hi.getValue(2);
1705       if (!Subtarget->isLittle())
1706         std::swap (Lo, Hi);
1707       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1708 
1709       if (VA.getLocVT() == MVT::v2f64) {
1710         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1711         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1712                           DAG.getConstant(0, dl, MVT::i32));
1713 
1714         VA = RVLocs[++i]; // skip ahead to next loc
1715         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1716         Chain = Lo.getValue(1);
1717         InFlag = Lo.getValue(2);
1718         VA = RVLocs[++i]; // skip ahead to next loc
1719         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1720         Chain = Hi.getValue(1);
1721         InFlag = Hi.getValue(2);
1722         if (!Subtarget->isLittle())
1723           std::swap (Lo, Hi);
1724         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1725         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1726                           DAG.getConstant(1, dl, MVT::i32));
1727       }
1728     } else {
1729       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1730                                InFlag);
1731       Chain = Val.getValue(1);
1732       InFlag = Val.getValue(2);
1733     }
1734 
1735     switch (VA.getLocInfo()) {
1736     default: llvm_unreachable("Unknown loc info!");
1737     case CCValAssign::Full: break;
1738     case CCValAssign::BCvt:
1739       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1740       break;
1741     }
1742 
1743     InVals.push_back(Val);
1744   }
1745 
1746   return Chain;
1747 }
1748 
1749 /// LowerMemOpCallTo - Store the argument to the stack.
1750 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1751                                             SDValue Arg, const SDLoc &dl,
1752                                             SelectionDAG &DAG,
1753                                             const CCValAssign &VA,
1754                                             ISD::ArgFlagsTy Flags) const {
1755   unsigned LocMemOffset = VA.getLocMemOffset();
1756   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1757   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1758                        StackPtr, PtrOff);
1759   return DAG.getStore(
1760       Chain, dl, Arg, PtrOff,
1761       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1762 }
1763 
1764 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1765                                          SDValue Chain, SDValue &Arg,
1766                                          RegsToPassVector &RegsToPass,
1767                                          CCValAssign &VA, CCValAssign &NextVA,
1768                                          SDValue &StackPtr,
1769                                          SmallVectorImpl<SDValue> &MemOpChains,
1770                                          ISD::ArgFlagsTy Flags) const {
1771   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1772                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1773   unsigned id = Subtarget->isLittle() ? 0 : 1;
1774   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1775 
1776   if (NextVA.isRegLoc())
1777     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1778   else {
1779     assert(NextVA.isMemLoc());
1780     if (!StackPtr.getNode())
1781       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1782                                     getPointerTy(DAG.getDataLayout()));
1783 
1784     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1785                                            dl, DAG, NextVA,
1786                                            Flags));
1787   }
1788 }
1789 
1790 /// LowerCall - Lowering a call into a callseq_start <-
1791 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1792 /// nodes.
1793 SDValue
1794 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1795                              SmallVectorImpl<SDValue> &InVals) const {
1796   SelectionDAG &DAG                     = CLI.DAG;
1797   SDLoc &dl                             = CLI.DL;
1798   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1799   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1800   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1801   SDValue Chain                         = CLI.Chain;
1802   SDValue Callee                        = CLI.Callee;
1803   bool &isTailCall                      = CLI.IsTailCall;
1804   CallingConv::ID CallConv              = CLI.CallConv;
1805   bool doesNotRet                       = CLI.DoesNotReturn;
1806   bool isVarArg                         = CLI.IsVarArg;
1807 
1808   MachineFunction &MF = DAG.getMachineFunction();
1809   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1810   bool isThisReturn   = false;
1811   bool isSibCall      = false;
1812   auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
1813 
1814   // Disable tail calls if they're not supported.
1815   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1816     isTailCall = false;
1817 
1818   if (isTailCall) {
1819     // Check if it's really possible to do a tail call.
1820     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1821                     isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(),
1822                                                    Outs, OutVals, Ins, DAG);
1823     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1824       report_fatal_error("failed to perform tail call elimination on a call "
1825                          "site marked musttail");
1826     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1827     // detected sibcalls.
1828     if (isTailCall) {
1829       ++NumTailCalls;
1830       isSibCall = true;
1831     }
1832   }
1833 
1834   // Analyze operands of the call, assigning locations to each operand.
1835   SmallVector<CCValAssign, 16> ArgLocs;
1836   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1837                  *DAG.getContext());
1838   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1839 
1840   // Get a count of how many bytes are to be pushed on the stack.
1841   unsigned NumBytes = CCInfo.getNextStackOffset();
1842 
1843   // For tail calls, memory operands are available in our caller's stack.
1844   if (isSibCall)
1845     NumBytes = 0;
1846 
1847   // Adjust the stack pointer for the new arguments...
1848   // These operations are automatically eliminated by the prolog/epilog pass
1849   if (!isSibCall)
1850     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1851 
1852   SDValue StackPtr =
1853       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1854 
1855   RegsToPassVector RegsToPass;
1856   SmallVector<SDValue, 8> MemOpChains;
1857 
1858   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1859   // of tail call optimization, arguments are handled later.
1860   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1861        i != e;
1862        ++i, ++realArgIdx) {
1863     CCValAssign &VA = ArgLocs[i];
1864     SDValue Arg = OutVals[realArgIdx];
1865     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1866     bool isByVal = Flags.isByVal();
1867 
1868     // Promote the value if needed.
1869     switch (VA.getLocInfo()) {
1870     default: llvm_unreachable("Unknown loc info!");
1871     case CCValAssign::Full: break;
1872     case CCValAssign::SExt:
1873       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1874       break;
1875     case CCValAssign::ZExt:
1876       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1877       break;
1878     case CCValAssign::AExt:
1879       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1880       break;
1881     case CCValAssign::BCvt:
1882       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1883       break;
1884     }
1885 
1886     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1887     if (VA.needsCustom()) {
1888       if (VA.getLocVT() == MVT::v2f64) {
1889         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1890                                   DAG.getConstant(0, dl, MVT::i32));
1891         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1892                                   DAG.getConstant(1, dl, MVT::i32));
1893 
1894         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1895                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1896 
1897         VA = ArgLocs[++i]; // skip ahead to next loc
1898         if (VA.isRegLoc()) {
1899           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1900                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1901         } else {
1902           assert(VA.isMemLoc());
1903 
1904           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1905                                                  dl, DAG, VA, Flags));
1906         }
1907       } else {
1908         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1909                          StackPtr, MemOpChains, Flags);
1910       }
1911     } else if (VA.isRegLoc()) {
1912       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1913           Outs[0].VT == MVT::i32) {
1914         assert(VA.getLocVT() == MVT::i32 &&
1915                "unexpected calling convention register assignment");
1916         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1917                "unexpected use of 'returned'");
1918         isThisReturn = true;
1919       }
1920       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1921     } else if (isByVal) {
1922       assert(VA.isMemLoc());
1923       unsigned offset = 0;
1924 
1925       // True if this byval aggregate will be split between registers
1926       // and memory.
1927       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1928       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1929 
1930       if (CurByValIdx < ByValArgsCount) {
1931 
1932         unsigned RegBegin, RegEnd;
1933         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1934 
1935         EVT PtrVT =
1936             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1937         unsigned int i, j;
1938         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1939           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1940           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1941           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1942                                      MachinePointerInfo(),
1943                                      DAG.InferPtrAlignment(AddArg));
1944           MemOpChains.push_back(Load.getValue(1));
1945           RegsToPass.push_back(std::make_pair(j, Load));
1946         }
1947 
1948         // If parameter size outsides register area, "offset" value
1949         // helps us to calculate stack slot for remained part properly.
1950         offset = RegEnd - RegBegin;
1951 
1952         CCInfo.nextInRegsParam();
1953       }
1954 
1955       if (Flags.getByValSize() > 4*offset) {
1956         auto PtrVT = getPointerTy(DAG.getDataLayout());
1957         unsigned LocMemOffset = VA.getLocMemOffset();
1958         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1959         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1960         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1961         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1962         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1963                                            MVT::i32);
1964         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1965                                             MVT::i32);
1966 
1967         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1968         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1969         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1970                                           Ops));
1971       }
1972     } else if (!isSibCall) {
1973       assert(VA.isMemLoc());
1974 
1975       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1976                                              dl, DAG, VA, Flags));
1977     }
1978   }
1979 
1980   if (!MemOpChains.empty())
1981     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1982 
1983   // Build a sequence of copy-to-reg nodes chained together with token chain
1984   // and flag operands which copy the outgoing args into the appropriate regs.
1985   SDValue InFlag;
1986   // Tail call byval lowering might overwrite argument registers so in case of
1987   // tail call optimization the copies to registers are lowered later.
1988   if (!isTailCall)
1989     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1990       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1991                                RegsToPass[i].second, InFlag);
1992       InFlag = Chain.getValue(1);
1993     }
1994 
1995   // For tail calls lower the arguments to the 'real' stack slot.
1996   if (isTailCall) {
1997     // Force all the incoming stack arguments to be loaded from the stack
1998     // before any new outgoing arguments are stored to the stack, because the
1999     // outgoing stack slots may alias the incoming argument stack slots, and
2000     // the alias isn't otherwise explicit. This is slightly more conservative
2001     // than necessary, because it means that each store effectively depends
2002     // on every argument instead of just those arguments it would clobber.
2003 
2004     // Do not flag preceding copytoreg stuff together with the following stuff.
2005     InFlag = SDValue();
2006     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2007       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2008                                RegsToPass[i].second, InFlag);
2009       InFlag = Chain.getValue(1);
2010     }
2011     InFlag = SDValue();
2012   }
2013 
2014   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2015   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2016   // node so that legalize doesn't hack it.
2017   bool isDirect = false;
2018 
2019   const TargetMachine &TM = getTargetMachine();
2020   const Module *Mod = MF.getFunction().getParent();
2021   const GlobalValue *GV = nullptr;
2022   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2023     GV = G->getGlobal();
2024   bool isStub =
2025       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2026 
2027   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2028   bool isLocalARMFunc = false;
2029   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2030   auto PtrVt = getPointerTy(DAG.getDataLayout());
2031 
2032   if (Subtarget->genLongCalls()) {
2033     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2034            "long-calls codegen is not position independent!");
2035     // Handle a global address or an external symbol. If it's not one of
2036     // those, the target's already in a register, so we don't need to do
2037     // anything extra.
2038     if (isa<GlobalAddressSDNode>(Callee)) {
2039       // Create a constant pool entry for the callee address
2040       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2041       ARMConstantPoolValue *CPV =
2042         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2043 
2044       // Get the address of the callee into a register
2045       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2046       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2047       Callee = DAG.getLoad(
2048           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2049           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2050     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2051       const char *Sym = S->getSymbol();
2052 
2053       // Create a constant pool entry for the callee address
2054       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2055       ARMConstantPoolValue *CPV =
2056         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2057                                       ARMPCLabelIndex, 0);
2058       // Get the address of the callee into a register
2059       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2060       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2061       Callee = DAG.getLoad(
2062           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2063           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2064     }
2065   } else if (isa<GlobalAddressSDNode>(Callee)) {
2066     // If we're optimizing for minimum size and the function is called three or
2067     // more times in this block, we can improve codesize by calling indirectly
2068     // as BLXr has a 16-bit encoding.
2069     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2070     auto *BB = CLI.CS.getParent();
2071     bool PreferIndirect =
2072         Subtarget->isThumb() && MF.getFunction().optForMinSize() &&
2073         count_if(GV->users(), [&BB](const User *U) {
2074           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2075         }) > 2;
2076 
2077     if (!PreferIndirect) {
2078       isDirect = true;
2079       bool isDef = GV->isStrongDefinitionForLinker();
2080 
2081       // ARM call to a local ARM function is predicable.
2082       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2083       // tBX takes a register source operand.
2084       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2085         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2086         Callee = DAG.getNode(
2087             ARMISD::WrapperPIC, dl, PtrVt,
2088             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2089         Callee = DAG.getLoad(
2090             PtrVt, dl, DAG.getEntryNode(), Callee,
2091             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2092             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2093                                      MachineMemOperand::MOInvariant);
2094       } else if (Subtarget->isTargetCOFF()) {
2095         assert(Subtarget->isTargetWindows() &&
2096                "Windows is the only supported COFF target");
2097         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2098                                    ? ARMII::MO_DLLIMPORT
2099                                    : ARMII::MO_NO_FLAG;
2100         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2101                                             TargetFlags);
2102         if (GV->hasDLLImportStorageClass())
2103           Callee =
2104               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2105                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2106                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2107       } else {
2108         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2109       }
2110     }
2111   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2112     isDirect = true;
2113     // tBX takes a register source operand.
2114     const char *Sym = S->getSymbol();
2115     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2116       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2117       ARMConstantPoolValue *CPV =
2118         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2119                                       ARMPCLabelIndex, 4);
2120       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2121       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2122       Callee = DAG.getLoad(
2123           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2124           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2125       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2126       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2127     } else {
2128       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2129     }
2130   }
2131 
2132   // FIXME: handle tail calls differently.
2133   unsigned CallOpc;
2134   if (Subtarget->isThumb()) {
2135     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2136       CallOpc = ARMISD::CALL_NOLINK;
2137     else
2138       CallOpc = ARMISD::CALL;
2139   } else {
2140     if (!isDirect && !Subtarget->hasV5TOps())
2141       CallOpc = ARMISD::CALL_NOLINK;
2142     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2143              // Emit regular call when code size is the priority
2144              !MF.getFunction().optForMinSize())
2145       // "mov lr, pc; b _foo" to avoid confusing the RSP
2146       CallOpc = ARMISD::CALL_NOLINK;
2147     else
2148       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2149   }
2150 
2151   std::vector<SDValue> Ops;
2152   Ops.push_back(Chain);
2153   Ops.push_back(Callee);
2154 
2155   // Add argument registers to the end of the list so that they are known live
2156   // into the call.
2157   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2158     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2159                                   RegsToPass[i].second.getValueType()));
2160 
2161   // Add a register mask operand representing the call-preserved registers.
2162   if (!isTailCall) {
2163     const uint32_t *Mask;
2164     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2165     if (isThisReturn) {
2166       // For 'this' returns, use the R0-preserving mask if applicable
2167       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2168       if (!Mask) {
2169         // Set isThisReturn to false if the calling convention is not one that
2170         // allows 'returned' to be modeled in this way, so LowerCallResult does
2171         // not try to pass 'this' straight through
2172         isThisReturn = false;
2173         Mask = ARI->getCallPreservedMask(MF, CallConv);
2174       }
2175     } else
2176       Mask = ARI->getCallPreservedMask(MF, CallConv);
2177 
2178     assert(Mask && "Missing call preserved mask for calling convention");
2179     Ops.push_back(DAG.getRegisterMask(Mask));
2180   }
2181 
2182   if (InFlag.getNode())
2183     Ops.push_back(InFlag);
2184 
2185   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2186   if (isTailCall) {
2187     MF.getFrameInfo().setHasTailCall();
2188     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2189   }
2190 
2191   // Returns a chain and a flag for retval copy to use.
2192   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2193   InFlag = Chain.getValue(1);
2194 
2195   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2196                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2197   if (!Ins.empty())
2198     InFlag = Chain.getValue(1);
2199 
2200   // Handle result values, copying them out of physregs into vregs that we
2201   // return.
2202   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2203                          InVals, isThisReturn,
2204                          isThisReturn ? OutVals[0] : SDValue());
2205 }
2206 
2207 /// HandleByVal - Every parameter *after* a byval parameter is passed
2208 /// on the stack.  Remember the next parameter register to allocate,
2209 /// and then confiscate the rest of the parameter registers to insure
2210 /// this.
2211 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2212                                     unsigned Align) const {
2213   // Byval (as with any stack) slots are always at least 4 byte aligned.
2214   Align = std::max(Align, 4U);
2215 
2216   unsigned Reg = State->AllocateReg(GPRArgRegs);
2217   if (!Reg)
2218     return;
2219 
2220   unsigned AlignInRegs = Align / 4;
2221   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2222   for (unsigned i = 0; i < Waste; ++i)
2223     Reg = State->AllocateReg(GPRArgRegs);
2224 
2225   if (!Reg)
2226     return;
2227 
2228   unsigned Excess = 4 * (ARM::R4 - Reg);
2229 
2230   // Special case when NSAA != SP and parameter size greater than size of
2231   // all remained GPR regs. In that case we can't split parameter, we must
2232   // send it to stack. We also must set NCRN to R4, so waste all
2233   // remained registers.
2234   const unsigned NSAAOffset = State->getNextStackOffset();
2235   if (NSAAOffset != 0 && Size > Excess) {
2236     while (State->AllocateReg(GPRArgRegs))
2237       ;
2238     return;
2239   }
2240 
2241   // First register for byval parameter is the first register that wasn't
2242   // allocated before this method call, so it would be "reg".
2243   // If parameter is small enough to be saved in range [reg, r4), then
2244   // the end (first after last) register would be reg + param-size-in-regs,
2245   // else parameter would be splitted between registers and stack,
2246   // end register would be r4 in this case.
2247   unsigned ByValRegBegin = Reg;
2248   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2249   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2250   // Note, first register is allocated in the beginning of function already,
2251   // allocate remained amount of registers we need.
2252   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2253     State->AllocateReg(GPRArgRegs);
2254   // A byval parameter that is split between registers and memory needs its
2255   // size truncated here.
2256   // In the case where the entire structure fits in registers, we set the
2257   // size in memory to zero.
2258   Size = std::max<int>(Size - Excess, 0);
2259 }
2260 
2261 /// MatchingStackOffset - Return true if the given stack call argument is
2262 /// already available in the same position (relatively) of the caller's
2263 /// incoming argument stack.
2264 static
2265 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2266                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2267                          const TargetInstrInfo *TII) {
2268   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2269   int FI = std::numeric_limits<int>::max();
2270   if (Arg.getOpcode() == ISD::CopyFromReg) {
2271     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2272     if (!TargetRegisterInfo::isVirtualRegister(VR))
2273       return false;
2274     MachineInstr *Def = MRI->getVRegDef(VR);
2275     if (!Def)
2276       return false;
2277     if (!Flags.isByVal()) {
2278       if (!TII->isLoadFromStackSlot(*Def, FI))
2279         return false;
2280     } else {
2281       return false;
2282     }
2283   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2284     if (Flags.isByVal())
2285       // ByVal argument is passed in as a pointer but it's now being
2286       // dereferenced. e.g.
2287       // define @foo(%struct.X* %A) {
2288       //   tail call @bar(%struct.X* byval %A)
2289       // }
2290       return false;
2291     SDValue Ptr = Ld->getBasePtr();
2292     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2293     if (!FINode)
2294       return false;
2295     FI = FINode->getIndex();
2296   } else
2297     return false;
2298 
2299   assert(FI != std::numeric_limits<int>::max());
2300   if (!MFI.isFixedObjectIndex(FI))
2301     return false;
2302   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2303 }
2304 
2305 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2306 /// for tail call optimization. Targets which want to do tail call
2307 /// optimization should implement this function.
2308 bool
2309 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2310                                                      CallingConv::ID CalleeCC,
2311                                                      bool isVarArg,
2312                                                      bool isCalleeStructRet,
2313                                                      bool isCallerStructRet,
2314                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2315                                     const SmallVectorImpl<SDValue> &OutVals,
2316                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2317                                                      SelectionDAG& DAG) const {
2318   MachineFunction &MF = DAG.getMachineFunction();
2319   const Function &CallerF = MF.getFunction();
2320   CallingConv::ID CallerCC = CallerF.getCallingConv();
2321 
2322   assert(Subtarget->supportsTailCall());
2323 
2324   // Tail calls to function pointers cannot be optimized for Thumb1 if the args
2325   // to the call take up r0-r3. The reason is that there are no legal registers
2326   // left to hold the pointer to the function to be called.
2327   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2328       !isa<GlobalAddressSDNode>(Callee.getNode()))
2329       return false;
2330 
2331   // Look for obvious safe cases to perform tail call optimization that do not
2332   // require ABI changes. This is what gcc calls sibcall.
2333 
2334   // Exception-handling functions need a special set of instructions to indicate
2335   // a return to the hardware. Tail-calling another function would probably
2336   // break this.
2337   if (CallerF.hasFnAttribute("interrupt"))
2338     return false;
2339 
2340   // Also avoid sibcall optimization if either caller or callee uses struct
2341   // return semantics.
2342   if (isCalleeStructRet || isCallerStructRet)
2343     return false;
2344 
2345   // Externally-defined functions with weak linkage should not be
2346   // tail-called on ARM when the OS does not support dynamic
2347   // pre-emption of symbols, as the AAELF spec requires normal calls
2348   // to undefined weak functions to be replaced with a NOP or jump to the
2349   // next instruction. The behaviour of branch instructions in this
2350   // situation (as used for tail calls) is implementation-defined, so we
2351   // cannot rely on the linker replacing the tail call with a return.
2352   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2353     const GlobalValue *GV = G->getGlobal();
2354     const Triple &TT = getTargetMachine().getTargetTriple();
2355     if (GV->hasExternalWeakLinkage() &&
2356         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2357       return false;
2358   }
2359 
2360   // Check that the call results are passed in the same way.
2361   LLVMContext &C = *DAG.getContext();
2362   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2363                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2364                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2365     return false;
2366   // The callee has to preserve all registers the caller needs to preserve.
2367   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2368   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2369   if (CalleeCC != CallerCC) {
2370     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2371     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2372       return false;
2373   }
2374 
2375   // If Caller's vararg or byval argument has been split between registers and
2376   // stack, do not perform tail call, since part of the argument is in caller's
2377   // local frame.
2378   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2379   if (AFI_Caller->getArgRegsSaveSize())
2380     return false;
2381 
2382   // If the callee takes no arguments then go on to check the results of the
2383   // call.
2384   if (!Outs.empty()) {
2385     // Check if stack adjustment is needed. For now, do not do this if any
2386     // argument is passed on the stack.
2387     SmallVector<CCValAssign, 16> ArgLocs;
2388     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2389     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2390     if (CCInfo.getNextStackOffset()) {
2391       // Check if the arguments are already laid out in the right way as
2392       // the caller's fixed stack objects.
2393       MachineFrameInfo &MFI = MF.getFrameInfo();
2394       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2395       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2396       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2397            i != e;
2398            ++i, ++realArgIdx) {
2399         CCValAssign &VA = ArgLocs[i];
2400         EVT RegVT = VA.getLocVT();
2401         SDValue Arg = OutVals[realArgIdx];
2402         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2403         if (VA.getLocInfo() == CCValAssign::Indirect)
2404           return false;
2405         if (VA.needsCustom()) {
2406           // f64 and vector types are split into multiple registers or
2407           // register/stack-slot combinations.  The types will not match
2408           // the registers; give up on memory f64 refs until we figure
2409           // out what to do about this.
2410           if (!VA.isRegLoc())
2411             return false;
2412           if (!ArgLocs[++i].isRegLoc())
2413             return false;
2414           if (RegVT == MVT::v2f64) {
2415             if (!ArgLocs[++i].isRegLoc())
2416               return false;
2417             if (!ArgLocs[++i].isRegLoc())
2418               return false;
2419           }
2420         } else if (!VA.isRegLoc()) {
2421           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2422                                    MFI, MRI, TII))
2423             return false;
2424         }
2425       }
2426     }
2427 
2428     const MachineRegisterInfo &MRI = MF.getRegInfo();
2429     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2430       return false;
2431   }
2432 
2433   return true;
2434 }
2435 
2436 bool
2437 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2438                                   MachineFunction &MF, bool isVarArg,
2439                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2440                                   LLVMContext &Context) const {
2441   SmallVector<CCValAssign, 16> RVLocs;
2442   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2443   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2444 }
2445 
2446 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2447                                     const SDLoc &DL, SelectionDAG &DAG) {
2448   const MachineFunction &MF = DAG.getMachineFunction();
2449   const Function &F = MF.getFunction();
2450 
2451   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2452 
2453   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2454   // version of the "preferred return address". These offsets affect the return
2455   // instruction if this is a return from PL1 without hypervisor extensions.
2456   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2457   //    SWI:     0      "subs pc, lr, #0"
2458   //    ABORT:   +4     "subs pc, lr, #4"
2459   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2460   // UNDEF varies depending on where the exception came from ARM or Thumb
2461   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2462 
2463   int64_t LROffset;
2464   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2465       IntKind == "ABORT")
2466     LROffset = 4;
2467   else if (IntKind == "SWI" || IntKind == "UNDEF")
2468     LROffset = 0;
2469   else
2470     report_fatal_error("Unsupported interrupt attribute. If present, value "
2471                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2472 
2473   RetOps.insert(RetOps.begin() + 1,
2474                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2475 
2476   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2477 }
2478 
2479 SDValue
2480 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2481                                bool isVarArg,
2482                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2483                                const SmallVectorImpl<SDValue> &OutVals,
2484                                const SDLoc &dl, SelectionDAG &DAG) const {
2485   // CCValAssign - represent the assignment of the return value to a location.
2486   SmallVector<CCValAssign, 16> RVLocs;
2487 
2488   // CCState - Info about the registers and stack slots.
2489   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2490                  *DAG.getContext());
2491 
2492   // Analyze outgoing return values.
2493   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2494 
2495   SDValue Flag;
2496   SmallVector<SDValue, 4> RetOps;
2497   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2498   bool isLittleEndian = Subtarget->isLittle();
2499 
2500   MachineFunction &MF = DAG.getMachineFunction();
2501   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2502   AFI->setReturnRegsCount(RVLocs.size());
2503 
2504   // Copy the result values into the output registers.
2505   for (unsigned i = 0, realRVLocIdx = 0;
2506        i != RVLocs.size();
2507        ++i, ++realRVLocIdx) {
2508     CCValAssign &VA = RVLocs[i];
2509     assert(VA.isRegLoc() && "Can only return in registers!");
2510 
2511     SDValue Arg = OutVals[realRVLocIdx];
2512     bool ReturnF16 = false;
2513 
2514     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2515       // Half-precision return values can be returned like this:
2516       //
2517       // t11 f16 = fadd ...
2518       // t12: i16 = bitcast t11
2519       //   t13: i32 = zero_extend t12
2520       // t14: f32 = bitcast t13  <~~~~~~~ Arg
2521       //
2522       // to avoid code generation for bitcasts, we simply set Arg to the node
2523       // that produces the f16 value, t11 in this case.
2524       //
2525       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2526         SDValue ZE = Arg.getOperand(0);
2527         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2528           SDValue BC = ZE.getOperand(0);
2529           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2530             Arg = BC.getOperand(0);
2531             ReturnF16 = true;
2532           }
2533         }
2534       }
2535     }
2536 
2537     switch (VA.getLocInfo()) {
2538     default: llvm_unreachable("Unknown loc info!");
2539     case CCValAssign::Full: break;
2540     case CCValAssign::BCvt:
2541       if (!ReturnF16)
2542         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2543       break;
2544     }
2545 
2546     if (VA.needsCustom()) {
2547       if (VA.getLocVT() == MVT::v2f64) {
2548         // Extract the first half and return it in two registers.
2549         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2550                                    DAG.getConstant(0, dl, MVT::i32));
2551         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2552                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2553 
2554         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2555                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2556                                  Flag);
2557         Flag = Chain.getValue(1);
2558         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2559         VA = RVLocs[++i]; // skip ahead to next loc
2560         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2561                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2562                                  Flag);
2563         Flag = Chain.getValue(1);
2564         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2565         VA = RVLocs[++i]; // skip ahead to next loc
2566 
2567         // Extract the 2nd half and fall through to handle it as an f64 value.
2568         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2569                           DAG.getConstant(1, dl, MVT::i32));
2570       }
2571       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2572       // available.
2573       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2574                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2575       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2576                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2577                                Flag);
2578       Flag = Chain.getValue(1);
2579       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2580       VA = RVLocs[++i]; // skip ahead to next loc
2581       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2582                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2583                                Flag);
2584     } else
2585       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2586 
2587     // Guarantee that all emitted copies are
2588     // stuck together, avoiding something bad.
2589     Flag = Chain.getValue(1);
2590     RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2591                                      ReturnF16 ? MVT::f16 : VA.getLocVT()));
2592   }
2593   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2594   const MCPhysReg *I =
2595       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2596   if (I) {
2597     for (; *I; ++I) {
2598       if (ARM::GPRRegClass.contains(*I))
2599         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2600       else if (ARM::DPRRegClass.contains(*I))
2601         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2602       else
2603         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2604     }
2605   }
2606 
2607   // Update chain and glue.
2608   RetOps[0] = Chain;
2609   if (Flag.getNode())
2610     RetOps.push_back(Flag);
2611 
2612   // CPUs which aren't M-class use a special sequence to return from
2613   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2614   // though we use "subs pc, lr, #N").
2615   //
2616   // M-class CPUs actually use a normal return sequence with a special
2617   // (hardware-provided) value in LR, so the normal code path works.
2618   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2619       !Subtarget->isMClass()) {
2620     if (Subtarget->isThumb1Only())
2621       report_fatal_error("interrupt attribute is not supported in Thumb1");
2622     return LowerInterruptReturn(RetOps, dl, DAG);
2623   }
2624 
2625   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2626 }
2627 
2628 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2629   if (N->getNumValues() != 1)
2630     return false;
2631   if (!N->hasNUsesOfValue(1, 0))
2632     return false;
2633 
2634   SDValue TCChain = Chain;
2635   SDNode *Copy = *N->use_begin();
2636   if (Copy->getOpcode() == ISD::CopyToReg) {
2637     // If the copy has a glue operand, we conservatively assume it isn't safe to
2638     // perform a tail call.
2639     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2640       return false;
2641     TCChain = Copy->getOperand(0);
2642   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2643     SDNode *VMov = Copy;
2644     // f64 returned in a pair of GPRs.
2645     SmallPtrSet<SDNode*, 2> Copies;
2646     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2647          UI != UE; ++UI) {
2648       if (UI->getOpcode() != ISD::CopyToReg)
2649         return false;
2650       Copies.insert(*UI);
2651     }
2652     if (Copies.size() > 2)
2653       return false;
2654 
2655     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2656          UI != UE; ++UI) {
2657       SDValue UseChain = UI->getOperand(0);
2658       if (Copies.count(UseChain.getNode()))
2659         // Second CopyToReg
2660         Copy = *UI;
2661       else {
2662         // We are at the top of this chain.
2663         // If the copy has a glue operand, we conservatively assume it
2664         // isn't safe to perform a tail call.
2665         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2666           return false;
2667         // First CopyToReg
2668         TCChain = UseChain;
2669       }
2670     }
2671   } else if (Copy->getOpcode() == ISD::BITCAST) {
2672     // f32 returned in a single GPR.
2673     if (!Copy->hasOneUse())
2674       return false;
2675     Copy = *Copy->use_begin();
2676     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2677       return false;
2678     // If the copy has a glue operand, we conservatively assume it isn't safe to
2679     // perform a tail call.
2680     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2681       return false;
2682     TCChain = Copy->getOperand(0);
2683   } else {
2684     return false;
2685   }
2686 
2687   bool HasRet = false;
2688   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2689        UI != UE; ++UI) {
2690     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2691         UI->getOpcode() != ARMISD::INTRET_FLAG)
2692       return false;
2693     HasRet = true;
2694   }
2695 
2696   if (!HasRet)
2697     return false;
2698 
2699   Chain = TCChain;
2700   return true;
2701 }
2702 
2703 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2704   if (!Subtarget->supportsTailCall())
2705     return false;
2706 
2707   auto Attr =
2708       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2709   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2710     return false;
2711 
2712   return true;
2713 }
2714 
2715 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2716 // and pass the lower and high parts through.
2717 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2718   SDLoc DL(Op);
2719   SDValue WriteValue = Op->getOperand(2);
2720 
2721   // This function is only supposed to be called for i64 type argument.
2722   assert(WriteValue.getValueType() == MVT::i64
2723           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2724 
2725   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2726                            DAG.getConstant(0, DL, MVT::i32));
2727   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2728                            DAG.getConstant(1, DL, MVT::i32));
2729   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2730   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2731 }
2732 
2733 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2734 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2735 // one of the above mentioned nodes. It has to be wrapped because otherwise
2736 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2737 // be used to form addressing mode. These wrapped nodes will be selected
2738 // into MOVi.
2739 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2740                                              SelectionDAG &DAG) const {
2741   EVT PtrVT = Op.getValueType();
2742   // FIXME there is no actual debug info here
2743   SDLoc dl(Op);
2744   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2745   SDValue Res;
2746 
2747   // When generating execute-only code Constant Pools must be promoted to the
2748   // global data section. It's a bit ugly that we can't share them across basic
2749   // blocks, but this way we guarantee that execute-only behaves correct with
2750   // position-independent addressing modes.
2751   if (Subtarget->genExecuteOnly()) {
2752     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2753     auto T = const_cast<Type*>(CP->getType());
2754     auto C = const_cast<Constant*>(CP->getConstVal());
2755     auto M = const_cast<Module*>(DAG.getMachineFunction().
2756                                  getFunction().getParent());
2757     auto GV = new GlobalVariable(
2758                     *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2759                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2760                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2761                     Twine(AFI->createPICLabelUId())
2762                   );
2763     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2764                                             dl, PtrVT);
2765     return LowerGlobalAddress(GA, DAG);
2766   }
2767 
2768   if (CP->isMachineConstantPoolEntry())
2769     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2770                                     CP->getAlignment());
2771   else
2772     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2773                                     CP->getAlignment());
2774   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2775 }
2776 
2777 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2778   return MachineJumpTableInfo::EK_Inline;
2779 }
2780 
2781 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2782                                              SelectionDAG &DAG) const {
2783   MachineFunction &MF = DAG.getMachineFunction();
2784   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2785   unsigned ARMPCLabelIndex = 0;
2786   SDLoc DL(Op);
2787   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2788   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2789   SDValue CPAddr;
2790   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2791   if (!IsPositionIndependent) {
2792     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2793   } else {
2794     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2795     ARMPCLabelIndex = AFI->createPICLabelUId();
2796     ARMConstantPoolValue *CPV =
2797       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2798                                       ARMCP::CPBlockAddress, PCAdj);
2799     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2800   }
2801   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2802   SDValue Result = DAG.getLoad(
2803       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2804       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2805   if (!IsPositionIndependent)
2806     return Result;
2807   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2808   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2809 }
2810 
2811 /// Convert a TLS address reference into the correct sequence of loads
2812 /// and calls to compute the variable's address for Darwin, and return an
2813 /// SDValue containing the final node.
2814 
2815 /// Darwin only has one TLS scheme which must be capable of dealing with the
2816 /// fully general situation, in the worst case. This means:
2817 ///     + "extern __thread" declaration.
2818 ///     + Defined in a possibly unknown dynamic library.
2819 ///
2820 /// The general system is that each __thread variable has a [3 x i32] descriptor
2821 /// which contains information used by the runtime to calculate the address. The
2822 /// only part of this the compiler needs to know about is the first word, which
2823 /// contains a function pointer that must be called with the address of the
2824 /// entire descriptor in "r0".
2825 ///
2826 /// Since this descriptor may be in a different unit, in general access must
2827 /// proceed along the usual ARM rules. A common sequence to produce is:
2828 ///
2829 ///     movw rT1, :lower16:_var$non_lazy_ptr
2830 ///     movt rT1, :upper16:_var$non_lazy_ptr
2831 ///     ldr r0, [rT1]
2832 ///     ldr rT2, [r0]
2833 ///     blx rT2
2834 ///     [...address now in r0...]
2835 SDValue
2836 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2837                                                SelectionDAG &DAG) const {
2838   assert(Subtarget->isTargetDarwin() &&
2839          "This function expects a Darwin target");
2840   SDLoc DL(Op);
2841 
2842   // First step is to get the address of the actua global symbol. This is where
2843   // the TLS descriptor lives.
2844   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2845 
2846   // The first entry in the descriptor is a function pointer that we must call
2847   // to obtain the address of the variable.
2848   SDValue Chain = DAG.getEntryNode();
2849   SDValue FuncTLVGet = DAG.getLoad(
2850       MVT::i32, DL, Chain, DescAddr,
2851       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2852       /* Alignment = */ 4,
2853       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2854           MachineMemOperand::MOInvariant);
2855   Chain = FuncTLVGet.getValue(1);
2856 
2857   MachineFunction &F = DAG.getMachineFunction();
2858   MachineFrameInfo &MFI = F.getFrameInfo();
2859   MFI.setAdjustsStack(true);
2860 
2861   // TLS calls preserve all registers except those that absolutely must be
2862   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2863   // silly).
2864   auto TRI =
2865       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
2866   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2867   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2868 
2869   // Finally, we can make the call. This is just a degenerate version of a
2870   // normal AArch64 call node: r0 takes the address of the descriptor, and
2871   // returns the address of the variable in this thread.
2872   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2873   Chain =
2874       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2875                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2876                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2877   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2878 }
2879 
2880 SDValue
2881 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2882                                                 SelectionDAG &DAG) const {
2883   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2884 
2885   SDValue Chain = DAG.getEntryNode();
2886   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2887   SDLoc DL(Op);
2888 
2889   // Load the current TEB (thread environment block)
2890   SDValue Ops[] = {Chain,
2891                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2892                    DAG.getConstant(15, DL, MVT::i32),
2893                    DAG.getConstant(0, DL, MVT::i32),
2894                    DAG.getConstant(13, DL, MVT::i32),
2895                    DAG.getConstant(0, DL, MVT::i32),
2896                    DAG.getConstant(2, DL, MVT::i32)};
2897   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2898                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2899 
2900   SDValue TEB = CurrentTEB.getValue(0);
2901   Chain = CurrentTEB.getValue(1);
2902 
2903   // Load the ThreadLocalStoragePointer from the TEB
2904   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2905   SDValue TLSArray =
2906       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2907   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2908 
2909   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2910   // offset into the TLSArray.
2911 
2912   // Load the TLS index from the C runtime
2913   SDValue TLSIndex =
2914       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2915   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2916   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2917 
2918   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2919                               DAG.getConstant(2, DL, MVT::i32));
2920   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2921                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2922                             MachinePointerInfo());
2923 
2924   // Get the offset of the start of the .tls section (section base)
2925   const auto *GA = cast<GlobalAddressSDNode>(Op);
2926   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2927   SDValue Offset = DAG.getLoad(
2928       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2929                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2930       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2931 
2932   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2933 }
2934 
2935 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2936 SDValue
2937 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2938                                                  SelectionDAG &DAG) const {
2939   SDLoc dl(GA);
2940   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2941   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2942   MachineFunction &MF = DAG.getMachineFunction();
2943   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2944   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2945   ARMConstantPoolValue *CPV =
2946     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2947                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2948   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2949   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2950   Argument = DAG.getLoad(
2951       PtrVT, dl, DAG.getEntryNode(), Argument,
2952       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2953   SDValue Chain = Argument.getValue(1);
2954 
2955   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2956   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2957 
2958   // call __tls_get_addr.
2959   ArgListTy Args;
2960   ArgListEntry Entry;
2961   Entry.Node = Argument;
2962   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2963   Args.push_back(Entry);
2964 
2965   // FIXME: is there useful debug info available here?
2966   TargetLowering::CallLoweringInfo CLI(DAG);
2967   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2968       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2969       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2970 
2971   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2972   return CallResult.first;
2973 }
2974 
2975 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2976 // "local exec" model.
2977 SDValue
2978 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2979                                         SelectionDAG &DAG,
2980                                         TLSModel::Model model) const {
2981   const GlobalValue *GV = GA->getGlobal();
2982   SDLoc dl(GA);
2983   SDValue Offset;
2984   SDValue Chain = DAG.getEntryNode();
2985   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2986   // Get the Thread Pointer
2987   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2988 
2989   if (model == TLSModel::InitialExec) {
2990     MachineFunction &MF = DAG.getMachineFunction();
2991     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2992     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2993     // Initial exec model.
2994     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2995     ARMConstantPoolValue *CPV =
2996       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2997                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2998                                       true);
2999     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3000     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3001     Offset = DAG.getLoad(
3002         PtrVT, dl, Chain, Offset,
3003         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3004     Chain = Offset.getValue(1);
3005 
3006     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3007     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3008 
3009     Offset = DAG.getLoad(
3010         PtrVT, dl, Chain, Offset,
3011         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3012   } else {
3013     // local exec model
3014     assert(model == TLSModel::LocalExec);
3015     ARMConstantPoolValue *CPV =
3016       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3017     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3018     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3019     Offset = DAG.getLoad(
3020         PtrVT, dl, Chain, Offset,
3021         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3022   }
3023 
3024   // The address of the thread local variable is the add of the thread
3025   // pointer with the offset of the variable.
3026   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3027 }
3028 
3029 SDValue
3030 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3031   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3032   if (DAG.getTarget().useEmulatedTLS())
3033     return LowerToTLSEmulatedModel(GA, DAG);
3034 
3035   if (Subtarget->isTargetDarwin())
3036     return LowerGlobalTLSAddressDarwin(Op, DAG);
3037 
3038   if (Subtarget->isTargetWindows())
3039     return LowerGlobalTLSAddressWindows(Op, DAG);
3040 
3041   // TODO: implement the "local dynamic" model
3042   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3043   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3044 
3045   switch (model) {
3046     case TLSModel::GeneralDynamic:
3047     case TLSModel::LocalDynamic:
3048       return LowerToTLSGeneralDynamicModel(GA, DAG);
3049     case TLSModel::InitialExec:
3050     case TLSModel::LocalExec:
3051       return LowerToTLSExecModels(GA, DAG, model);
3052   }
3053   llvm_unreachable("bogus TLS model");
3054 }
3055 
3056 /// Return true if all users of V are within function F, looking through
3057 /// ConstantExprs.
3058 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3059   SmallVector<const User*,4> Worklist;
3060   for (auto *U : V->users())
3061     Worklist.push_back(U);
3062   while (!Worklist.empty()) {
3063     auto *U = Worklist.pop_back_val();
3064     if (isa<ConstantExpr>(U)) {
3065       for (auto *UU : U->users())
3066         Worklist.push_back(UU);
3067       continue;
3068     }
3069 
3070     auto *I = dyn_cast<Instruction>(U);
3071     if (!I || I->getParent()->getParent() != F)
3072       return false;
3073   }
3074   return true;
3075 }
3076 
3077 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3078                                      const GlobalValue *GV, SelectionDAG &DAG,
3079                                      EVT PtrVT, const SDLoc &dl) {
3080   // If we're creating a pool entry for a constant global with unnamed address,
3081   // and the global is small enough, we can emit it inline into the constant pool
3082   // to save ourselves an indirection.
3083   //
3084   // This is a win if the constant is only used in one function (so it doesn't
3085   // need to be duplicated) or duplicating the constant wouldn't increase code
3086   // size (implying the constant is no larger than 4 bytes).
3087   const Function &F = DAG.getMachineFunction().getFunction();
3088 
3089   // We rely on this decision to inline being idemopotent and unrelated to the
3090   // use-site. We know that if we inline a variable at one use site, we'll
3091   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3092   // doesn't know about this optimization, so bail out if it's enabled else
3093   // we could decide to inline here (and thus never emit the GV) but require
3094   // the GV from fast-isel generated code.
3095   if (!EnableConstpoolPromotion ||
3096       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3097       return SDValue();
3098 
3099   auto *GVar = dyn_cast<GlobalVariable>(GV);
3100   if (!GVar || !GVar->hasInitializer() ||
3101       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3102       !GVar->hasLocalLinkage())
3103     return SDValue();
3104 
3105   // If we inline a value that contains relocations, we move the relocations
3106   // from .data to .text. This is not allowed in position-independent code.
3107   auto *Init = GVar->getInitializer();
3108   if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3109       Init->needsRelocation())
3110     return SDValue();
3111 
3112   // The constant islands pass can only really deal with alignment requests
3113   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3114   // any type wanting greater alignment requirements than 4 bytes. We also
3115   // can only promote constants that are multiples of 4 bytes in size or
3116   // are paddable to a multiple of 4. Currently we only try and pad constants
3117   // that are strings for simplicity.
3118   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3119   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3120   unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3121   unsigned RequiredPadding = 4 - (Size % 4);
3122   bool PaddingPossible =
3123     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3124   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3125       Size == 0)
3126     return SDValue();
3127 
3128   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3129   MachineFunction &MF = DAG.getMachineFunction();
3130   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3131 
3132   // We can't bloat the constant pool too much, else the ConstantIslands pass
3133   // may fail to converge. If we haven't promoted this global yet (it may have
3134   // multiple uses), and promoting it would increase the constant pool size (Sz
3135   // > 4), ensure we have space to do so up to MaxTotal.
3136   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3137     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3138         ConstpoolPromotionMaxTotal)
3139       return SDValue();
3140 
3141   // This is only valid if all users are in a single function; we can't clone
3142   // the constant in general. The LLVM IR unnamed_addr allows merging
3143   // constants, but not cloning them.
3144   //
3145   // We could potentially allow cloning if we could prove all uses of the
3146   // constant in the current function don't care about the address, like
3147   // printf format strings. But that isn't implemented for now.
3148   if (!allUsersAreInFunction(GVar, &F))
3149     return SDValue();
3150 
3151   // We're going to inline this global. Pad it out if needed.
3152   if (RequiredPadding != 4) {
3153     StringRef S = CDAInit->getAsString();
3154 
3155     SmallVector<uint8_t,16> V(S.size());
3156     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3157     while (RequiredPadding--)
3158       V.push_back(0);
3159     Init = ConstantDataArray::get(*DAG.getContext(), V);
3160   }
3161 
3162   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3163   SDValue CPAddr =
3164     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3165   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3166     AFI->markGlobalAsPromotedToConstantPool(GVar);
3167     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3168                                       PaddedSize - 4);
3169   }
3170   ++NumConstpoolPromoted;
3171   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3172 }
3173 
3174 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3175   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3176     if (!(GV = GA->getBaseObject()))
3177       return false;
3178   if (const auto *V = dyn_cast<GlobalVariable>(GV))
3179     return V->isConstant();
3180   return isa<Function>(GV);
3181 }
3182 
3183 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3184                                               SelectionDAG &DAG) const {
3185   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3186   default: llvm_unreachable("unknown object format");
3187   case Triple::COFF:
3188     return LowerGlobalAddressWindows(Op, DAG);
3189   case Triple::ELF:
3190     return LowerGlobalAddressELF(Op, DAG);
3191   case Triple::MachO:
3192     return LowerGlobalAddressDarwin(Op, DAG);
3193   }
3194 }
3195 
3196 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3197                                                  SelectionDAG &DAG) const {
3198   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3199   SDLoc dl(Op);
3200   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3201   const TargetMachine &TM = getTargetMachine();
3202   bool IsRO = isReadOnly(GV);
3203 
3204   // promoteToConstantPool only if not generating XO text section
3205   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3206     if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3207       return V;
3208 
3209   if (isPositionIndependent()) {
3210     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3211     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3212                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3213     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3214     if (UseGOT_PREL)
3215       Result =
3216           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3217                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3218     return Result;
3219   } else if (Subtarget->isROPI() && IsRO) {
3220     // PC-relative.
3221     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3222     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3223     return Result;
3224   } else if (Subtarget->isRWPI() && !IsRO) {
3225     // SB-relative.
3226     SDValue RelAddr;
3227     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3228       ++NumMovwMovt;
3229       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3230       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3231     } else { // use literal pool for address constant
3232       ARMConstantPoolValue *CPV =
3233         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3234       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3235       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3236       RelAddr = DAG.getLoad(
3237           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3238           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3239     }
3240     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3241     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3242     return Result;
3243   }
3244 
3245   // If we have T2 ops, we can materialize the address directly via movt/movw
3246   // pair. This is always cheaper.
3247   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3248     ++NumMovwMovt;
3249     // FIXME: Once remat is capable of dealing with instructions with register
3250     // operands, expand this into two nodes.
3251     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3252                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3253   } else {
3254     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3255     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3256     return DAG.getLoad(
3257         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3258         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3259   }
3260 }
3261 
3262 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3263                                                     SelectionDAG &DAG) const {
3264   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3265          "ROPI/RWPI not currently supported for Darwin");
3266   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3267   SDLoc dl(Op);
3268   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3269 
3270   if (Subtarget->useMovt(DAG.getMachineFunction()))
3271     ++NumMovwMovt;
3272 
3273   // FIXME: Once remat is capable of dealing with instructions with register
3274   // operands, expand this into multiple nodes
3275   unsigned Wrapper =
3276       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3277 
3278   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3279   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3280 
3281   if (Subtarget->isGVIndirectSymbol(GV))
3282     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3283                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3284   return Result;
3285 }
3286 
3287 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3288                                                      SelectionDAG &DAG) const {
3289   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3290   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3291          "Windows on ARM expects to use movw/movt");
3292   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3293          "ROPI/RWPI not currently supported for Windows");
3294 
3295   const TargetMachine &TM = getTargetMachine();
3296   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3297   ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3298   if (GV->hasDLLImportStorageClass())
3299     TargetFlags = ARMII::MO_DLLIMPORT;
3300   else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3301     TargetFlags = ARMII::MO_COFFSTUB;
3302   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3303   SDValue Result;
3304   SDLoc DL(Op);
3305 
3306   ++NumMovwMovt;
3307 
3308   // FIXME: Once remat is capable of dealing with instructions with register
3309   // operands, expand this into two nodes.
3310   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3311                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3312                                                   TargetFlags));
3313   if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3314     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3315                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3316   return Result;
3317 }
3318 
3319 SDValue
3320 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3321   SDLoc dl(Op);
3322   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3323   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3324                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3325                      Op.getOperand(1), Val);
3326 }
3327 
3328 SDValue
3329 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3330   SDLoc dl(Op);
3331   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3332                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3333 }
3334 
3335 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3336                                                       SelectionDAG &DAG) const {
3337   SDLoc dl(Op);
3338   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3339                      Op.getOperand(0));
3340 }
3341 
3342 SDValue
3343 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3344                                           const ARMSubtarget *Subtarget) const {
3345   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3346   SDLoc dl(Op);
3347   switch (IntNo) {
3348   default: return SDValue();    // Don't custom lower most intrinsics.
3349   case Intrinsic::thread_pointer: {
3350     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3351     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3352   }
3353   case Intrinsic::eh_sjlj_lsda: {
3354     MachineFunction &MF = DAG.getMachineFunction();
3355     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3356     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3357     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3358     SDValue CPAddr;
3359     bool IsPositionIndependent = isPositionIndependent();
3360     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3361     ARMConstantPoolValue *CPV =
3362       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3363                                       ARMCP::CPLSDA, PCAdj);
3364     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3365     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3366     SDValue Result = DAG.getLoad(
3367         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3368         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3369 
3370     if (IsPositionIndependent) {
3371       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3372       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3373     }
3374     return Result;
3375   }
3376   case Intrinsic::arm_neon_vabs:
3377     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3378                         Op.getOperand(1));
3379   case Intrinsic::arm_neon_vmulls:
3380   case Intrinsic::arm_neon_vmullu: {
3381     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3382       ? ARMISD::VMULLs : ARMISD::VMULLu;
3383     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3384                        Op.getOperand(1), Op.getOperand(2));
3385   }
3386   case Intrinsic::arm_neon_vminnm:
3387   case Intrinsic::arm_neon_vmaxnm: {
3388     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3389       ? ISD::FMINNUM : ISD::FMAXNUM;
3390     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3391                        Op.getOperand(1), Op.getOperand(2));
3392   }
3393   case Intrinsic::arm_neon_vminu:
3394   case Intrinsic::arm_neon_vmaxu: {
3395     if (Op.getValueType().isFloatingPoint())
3396       return SDValue();
3397     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3398       ? ISD::UMIN : ISD::UMAX;
3399     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3400                          Op.getOperand(1), Op.getOperand(2));
3401   }
3402   case Intrinsic::arm_neon_vmins:
3403   case Intrinsic::arm_neon_vmaxs: {
3404     // v{min,max}s is overloaded between signed integers and floats.
3405     if (!Op.getValueType().isFloatingPoint()) {
3406       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3407         ? ISD::SMIN : ISD::SMAX;
3408       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3409                          Op.getOperand(1), Op.getOperand(2));
3410     }
3411     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3412       ? ISD::FMINIMUM : ISD::FMAXIMUM;
3413     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3414                        Op.getOperand(1), Op.getOperand(2));
3415   }
3416   case Intrinsic::arm_neon_vtbl1:
3417     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3418                        Op.getOperand(1), Op.getOperand(2));
3419   case Intrinsic::arm_neon_vtbl2:
3420     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3421                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3422   }
3423 }
3424 
3425 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3426                                  const ARMSubtarget *Subtarget) {
3427   SDLoc dl(Op);
3428   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3429   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3430   if (SSID == SyncScope::SingleThread)
3431     return Op;
3432 
3433   if (!Subtarget->hasDataBarrier()) {
3434     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3435     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3436     // here.
3437     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3438            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3439     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3440                        DAG.getConstant(0, dl, MVT::i32));
3441   }
3442 
3443   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3444   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3445   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3446   if (Subtarget->isMClass()) {
3447     // Only a full system barrier exists in the M-class architectures.
3448     Domain = ARM_MB::SY;
3449   } else if (Subtarget->preferISHSTBarriers() &&
3450              Ord == AtomicOrdering::Release) {
3451     // Swift happens to implement ISHST barriers in a way that's compatible with
3452     // Release semantics but weaker than ISH so we'd be fools not to use
3453     // it. Beware: other processors probably don't!
3454     Domain = ARM_MB::ISHST;
3455   }
3456 
3457   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3458                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3459                      DAG.getConstant(Domain, dl, MVT::i32));
3460 }
3461 
3462 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3463                              const ARMSubtarget *Subtarget) {
3464   // ARM pre v5TE and Thumb1 does not have preload instructions.
3465   if (!(Subtarget->isThumb2() ||
3466         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3467     // Just preserve the chain.
3468     return Op.getOperand(0);
3469 
3470   SDLoc dl(Op);
3471   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3472   if (!isRead &&
3473       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3474     // ARMv7 with MP extension has PLDW.
3475     return Op.getOperand(0);
3476 
3477   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3478   if (Subtarget->isThumb()) {
3479     // Invert the bits.
3480     isRead = ~isRead & 1;
3481     isData = ~isData & 1;
3482   }
3483 
3484   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3485                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3486                      DAG.getConstant(isData, dl, MVT::i32));
3487 }
3488 
3489 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3490   MachineFunction &MF = DAG.getMachineFunction();
3491   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3492 
3493   // vastart just stores the address of the VarArgsFrameIndex slot into the
3494   // memory location argument.
3495   SDLoc dl(Op);
3496   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3497   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3498   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3499   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3500                       MachinePointerInfo(SV));
3501 }
3502 
3503 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3504                                                 CCValAssign &NextVA,
3505                                                 SDValue &Root,
3506                                                 SelectionDAG &DAG,
3507                                                 const SDLoc &dl) const {
3508   MachineFunction &MF = DAG.getMachineFunction();
3509   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3510 
3511   const TargetRegisterClass *RC;
3512   if (AFI->isThumb1OnlyFunction())
3513     RC = &ARM::tGPRRegClass;
3514   else
3515     RC = &ARM::GPRRegClass;
3516 
3517   // Transform the arguments stored in physical registers into virtual ones.
3518   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3519   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3520 
3521   SDValue ArgValue2;
3522   if (NextVA.isMemLoc()) {
3523     MachineFrameInfo &MFI = MF.getFrameInfo();
3524     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3525 
3526     // Create load node to retrieve arguments from the stack.
3527     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3528     ArgValue2 = DAG.getLoad(
3529         MVT::i32, dl, Root, FIN,
3530         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3531   } else {
3532     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3533     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3534   }
3535   if (!Subtarget->isLittle())
3536     std::swap (ArgValue, ArgValue2);
3537   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3538 }
3539 
3540 // The remaining GPRs hold either the beginning of variable-argument
3541 // data, or the beginning of an aggregate passed by value (usually
3542 // byval).  Either way, we allocate stack slots adjacent to the data
3543 // provided by our caller, and store the unallocated registers there.
3544 // If this is a variadic function, the va_list pointer will begin with
3545 // these values; otherwise, this reassembles a (byval) structure that
3546 // was split between registers and memory.
3547 // Return: The frame index registers were stored into.
3548 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3549                                       const SDLoc &dl, SDValue &Chain,
3550                                       const Value *OrigArg,
3551                                       unsigned InRegsParamRecordIdx,
3552                                       int ArgOffset, unsigned ArgSize) const {
3553   // Currently, two use-cases possible:
3554   // Case #1. Non-var-args function, and we meet first byval parameter.
3555   //          Setup first unallocated register as first byval register;
3556   //          eat all remained registers
3557   //          (these two actions are performed by HandleByVal method).
3558   //          Then, here, we initialize stack frame with
3559   //          "store-reg" instructions.
3560   // Case #2. Var-args function, that doesn't contain byval parameters.
3561   //          The same: eat all remained unallocated registers,
3562   //          initialize stack frame.
3563 
3564   MachineFunction &MF = DAG.getMachineFunction();
3565   MachineFrameInfo &MFI = MF.getFrameInfo();
3566   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3567   unsigned RBegin, REnd;
3568   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3569     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3570   } else {
3571     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3572     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3573     REnd = ARM::R4;
3574   }
3575 
3576   if (REnd != RBegin)
3577     ArgOffset = -4 * (ARM::R4 - RBegin);
3578 
3579   auto PtrVT = getPointerTy(DAG.getDataLayout());
3580   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3581   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3582 
3583   SmallVector<SDValue, 4> MemOps;
3584   const TargetRegisterClass *RC =
3585       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3586 
3587   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3588     unsigned VReg = MF.addLiveIn(Reg, RC);
3589     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3590     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3591                                  MachinePointerInfo(OrigArg, 4 * i));
3592     MemOps.push_back(Store);
3593     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3594   }
3595 
3596   if (!MemOps.empty())
3597     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3598   return FrameIndex;
3599 }
3600 
3601 // Setup stack frame, the va_list pointer will start from.
3602 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3603                                              const SDLoc &dl, SDValue &Chain,
3604                                              unsigned ArgOffset,
3605                                              unsigned TotalArgRegsSaveSize,
3606                                              bool ForceMutable) const {
3607   MachineFunction &MF = DAG.getMachineFunction();
3608   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3609 
3610   // Try to store any remaining integer argument regs
3611   // to their spots on the stack so that they may be loaded by dereferencing
3612   // the result of va_next.
3613   // If there is no regs to be stored, just point address after last
3614   // argument passed via stack.
3615   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3616                                   CCInfo.getInRegsParamsCount(),
3617                                   CCInfo.getNextStackOffset(), 4);
3618   AFI->setVarArgsFrameIndex(FrameIndex);
3619 }
3620 
3621 SDValue ARMTargetLowering::LowerFormalArguments(
3622     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3623     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3624     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3625   MachineFunction &MF = DAG.getMachineFunction();
3626   MachineFrameInfo &MFI = MF.getFrameInfo();
3627 
3628   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3629 
3630   // Assign locations to all of the incoming arguments.
3631   SmallVector<CCValAssign, 16> ArgLocs;
3632   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3633                  *DAG.getContext());
3634   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3635 
3636   SmallVector<SDValue, 16> ArgValues;
3637   SDValue ArgValue;
3638   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3639   unsigned CurArgIdx = 0;
3640 
3641   // Initially ArgRegsSaveSize is zero.
3642   // Then we increase this value each time we meet byval parameter.
3643   // We also increase this value in case of varargs function.
3644   AFI->setArgRegsSaveSize(0);
3645 
3646   // Calculate the amount of stack space that we need to allocate to store
3647   // byval and variadic arguments that are passed in registers.
3648   // We need to know this before we allocate the first byval or variadic
3649   // argument, as they will be allocated a stack slot below the CFA (Canonical
3650   // Frame Address, the stack pointer at entry to the function).
3651   unsigned ArgRegBegin = ARM::R4;
3652   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3653     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3654       break;
3655 
3656     CCValAssign &VA = ArgLocs[i];
3657     unsigned Index = VA.getValNo();
3658     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3659     if (!Flags.isByVal())
3660       continue;
3661 
3662     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3663     unsigned RBegin, REnd;
3664     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3665     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3666 
3667     CCInfo.nextInRegsParam();
3668   }
3669   CCInfo.rewindByValRegsInfo();
3670 
3671   int lastInsIndex = -1;
3672   if (isVarArg && MFI.hasVAStart()) {
3673     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3674     if (RegIdx != array_lengthof(GPRArgRegs))
3675       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3676   }
3677 
3678   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3679   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3680   auto PtrVT = getPointerTy(DAG.getDataLayout());
3681 
3682   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3683     CCValAssign &VA = ArgLocs[i];
3684     if (Ins[VA.getValNo()].isOrigArg()) {
3685       std::advance(CurOrigArg,
3686                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3687       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3688     }
3689     // Arguments stored in registers.
3690     if (VA.isRegLoc()) {
3691       EVT RegVT = VA.getLocVT();
3692 
3693       if (VA.needsCustom()) {
3694         // f64 and vector types are split up into multiple registers or
3695         // combinations of registers and stack slots.
3696         if (VA.getLocVT() == MVT::v2f64) {
3697           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3698                                                    Chain, DAG, dl);
3699           VA = ArgLocs[++i]; // skip ahead to next loc
3700           SDValue ArgValue2;
3701           if (VA.isMemLoc()) {
3702             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3703             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3704             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3705                                     MachinePointerInfo::getFixedStack(
3706                                         DAG.getMachineFunction(), FI));
3707           } else {
3708             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3709                                              Chain, DAG, dl);
3710           }
3711           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3712           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3713                                  ArgValue, ArgValue1,
3714                                  DAG.getIntPtrConstant(0, dl));
3715           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3716                                  ArgValue, ArgValue2,
3717                                  DAG.getIntPtrConstant(1, dl));
3718         } else
3719           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3720       } else {
3721         const TargetRegisterClass *RC;
3722 
3723 
3724         if (RegVT == MVT::f16)
3725           RC = &ARM::HPRRegClass;
3726         else if (RegVT == MVT::f32)
3727           RC = &ARM::SPRRegClass;
3728         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3729           RC = &ARM::DPRRegClass;
3730         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3731           RC = &ARM::QPRRegClass;
3732         else if (RegVT == MVT::i32)
3733           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3734                                            : &ARM::GPRRegClass;
3735         else
3736           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3737 
3738         // Transform the arguments in physical registers into virtual ones.
3739         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3740         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3741       }
3742 
3743       // If this is an 8 or 16-bit value, it is really passed promoted
3744       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3745       // truncate to the right size.
3746       switch (VA.getLocInfo()) {
3747       default: llvm_unreachable("Unknown loc info!");
3748       case CCValAssign::Full: break;
3749       case CCValAssign::BCvt:
3750         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3751         break;
3752       case CCValAssign::SExt:
3753         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3754                                DAG.getValueType(VA.getValVT()));
3755         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3756         break;
3757       case CCValAssign::ZExt:
3758         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3759                                DAG.getValueType(VA.getValVT()));
3760         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3761         break;
3762       }
3763 
3764       InVals.push_back(ArgValue);
3765     } else { // VA.isRegLoc()
3766       // sanity check
3767       assert(VA.isMemLoc());
3768       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3769 
3770       int index = VA.getValNo();
3771 
3772       // Some Ins[] entries become multiple ArgLoc[] entries.
3773       // Process them only once.
3774       if (index != lastInsIndex)
3775         {
3776           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3777           // FIXME: For now, all byval parameter objects are marked mutable.
3778           // This can be changed with more analysis.
3779           // In case of tail call optimization mark all arguments mutable.
3780           // Since they could be overwritten by lowering of arguments in case of
3781           // a tail call.
3782           if (Flags.isByVal()) {
3783             assert(Ins[index].isOrigArg() &&
3784                    "Byval arguments cannot be implicit");
3785             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3786 
3787             int FrameIndex = StoreByValRegs(
3788                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3789                 VA.getLocMemOffset(), Flags.getByValSize());
3790             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3791             CCInfo.nextInRegsParam();
3792           } else {
3793             unsigned FIOffset = VA.getLocMemOffset();
3794             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3795                                            FIOffset, true);
3796 
3797             // Create load nodes to retrieve arguments from the stack.
3798             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3799             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3800                                          MachinePointerInfo::getFixedStack(
3801                                              DAG.getMachineFunction(), FI)));
3802           }
3803           lastInsIndex = index;
3804         }
3805     }
3806   }
3807 
3808   // varargs
3809   if (isVarArg && MFI.hasVAStart())
3810     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3811                          CCInfo.getNextStackOffset(),
3812                          TotalArgRegsSaveSize);
3813 
3814   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3815 
3816   return Chain;
3817 }
3818 
3819 /// isFloatingPointZero - Return true if this is +0.0.
3820 static bool isFloatingPointZero(SDValue Op) {
3821   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3822     return CFP->getValueAPF().isPosZero();
3823   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3824     // Maybe this has already been legalized into the constant pool?
3825     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3826       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3827       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3828         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3829           return CFP->getValueAPF().isPosZero();
3830     }
3831   } else if (Op->getOpcode() == ISD::BITCAST &&
3832              Op->getValueType(0) == MVT::f64) {
3833     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3834     // created by LowerConstantFP().
3835     SDValue BitcastOp = Op->getOperand(0);
3836     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3837         isNullConstant(BitcastOp->getOperand(0)))
3838       return true;
3839   }
3840   return false;
3841 }
3842 
3843 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3844 /// the given operands.
3845 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3846                                      SDValue &ARMcc, SelectionDAG &DAG,
3847                                      const SDLoc &dl) const {
3848   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3849     unsigned C = RHSC->getZExtValue();
3850     if (!isLegalICmpImmediate((int32_t)C)) {
3851       // Constant does not fit, try adjusting it by one.
3852       switch (CC) {
3853       default: break;
3854       case ISD::SETLT:
3855       case ISD::SETGE:
3856         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3857           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3858           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3859         }
3860         break;
3861       case ISD::SETULT:
3862       case ISD::SETUGE:
3863         if (C != 0 && isLegalICmpImmediate(C-1)) {
3864           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3865           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3866         }
3867         break;
3868       case ISD::SETLE:
3869       case ISD::SETGT:
3870         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3871           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3872           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3873         }
3874         break;
3875       case ISD::SETULE:
3876       case ISD::SETUGT:
3877         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3878           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3879           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3880         }
3881         break;
3882       }
3883     }
3884   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
3885              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
3886     // In ARM and Thumb-2, the compare instructions can shift their second
3887     // operand.
3888     CC = ISD::getSetCCSwappedOperands(CC);
3889     std::swap(LHS, RHS);
3890   }
3891 
3892   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3893   ARMISD::NodeType CompareType;
3894   switch (CondCode) {
3895   default:
3896     CompareType = ARMISD::CMP;
3897     break;
3898   case ARMCC::EQ:
3899   case ARMCC::NE:
3900     // Uses only Z Flag
3901     CompareType = ARMISD::CMPZ;
3902     break;
3903   }
3904   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3905   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3906 }
3907 
3908 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3909 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3910                                      SelectionDAG &DAG, const SDLoc &dl,
3911                                      bool InvalidOnQNaN) const {
3912   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3913   SDValue Cmp;
3914   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3915   if (!isFloatingPointZero(RHS))
3916     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3917   else
3918     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3919   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3920 }
3921 
3922 /// duplicateCmp - Glue values can have only one use, so this function
3923 /// duplicates a comparison node.
3924 SDValue
3925 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3926   unsigned Opc = Cmp.getOpcode();
3927   SDLoc DL(Cmp);
3928   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3929     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3930 
3931   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3932   Cmp = Cmp.getOperand(0);
3933   Opc = Cmp.getOpcode();
3934   if (Opc == ARMISD::CMPFP)
3935     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3936                       Cmp.getOperand(1), Cmp.getOperand(2));
3937   else {
3938     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3939     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3940                       Cmp.getOperand(1));
3941   }
3942   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3943 }
3944 
3945 // This function returns three things: the arithmetic computation itself
3946 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
3947 // comparison and the condition code define the case in which the arithmetic
3948 // computation *does not* overflow.
3949 std::pair<SDValue, SDValue>
3950 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3951                                  SDValue &ARMcc) const {
3952   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3953 
3954   SDValue Value, OverflowCmp;
3955   SDValue LHS = Op.getOperand(0);
3956   SDValue RHS = Op.getOperand(1);
3957   SDLoc dl(Op);
3958 
3959   // FIXME: We are currently always generating CMPs because we don't support
3960   // generating CMN through the backend. This is not as good as the natural
3961   // CMP case because it causes a register dependency and cannot be folded
3962   // later.
3963 
3964   switch (Op.getOpcode()) {
3965   default:
3966     llvm_unreachable("Unknown overflow instruction!");
3967   case ISD::SADDO:
3968     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3969     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3970     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3971     break;
3972   case ISD::UADDO:
3973     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3974     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
3975     // We do not use it in the USUBO case as Value may not be used.
3976     Value = DAG.getNode(ARMISD::ADDC, dl,
3977                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
3978                 .getValue(0);
3979     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3980     break;
3981   case ISD::SSUBO:
3982     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3983     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3984     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3985     break;
3986   case ISD::USUBO:
3987     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3988     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3989     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3990     break;
3991   case ISD::UMULO:
3992     // We generate a UMUL_LOHI and then check if the high word is 0.
3993     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
3994     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
3995                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
3996                         LHS, RHS);
3997     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
3998                               DAG.getConstant(0, dl, MVT::i32));
3999     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4000     break;
4001   case ISD::SMULO:
4002     // We generate a SMUL_LOHI and then check if all the bits of the high word
4003     // are the same as the sign bit of the low word.
4004     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4005     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4006                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4007                         LHS, RHS);
4008     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4009                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4010                                           Value.getValue(0),
4011                                           DAG.getConstant(31, dl, MVT::i32)));
4012     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4013     break;
4014   } // switch (...)
4015 
4016   return std::make_pair(Value, OverflowCmp);
4017 }
4018 
4019 SDValue
4020 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4021   // Let legalize expand this if it isn't a legal type yet.
4022   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4023     return SDValue();
4024 
4025   SDValue Value, OverflowCmp;
4026   SDValue ARMcc;
4027   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4028   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4029   SDLoc dl(Op);
4030   // We use 0 and 1 as false and true values.
4031   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4032   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4033   EVT VT = Op.getValueType();
4034 
4035   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4036                                  ARMcc, CCR, OverflowCmp);
4037 
4038   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4039   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4040 }
4041 
4042 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4043                                               SelectionDAG &DAG) {
4044   SDLoc DL(BoolCarry);
4045   EVT CarryVT = BoolCarry.getValueType();
4046 
4047   // This converts the boolean value carry into the carry flag by doing
4048   // ARMISD::SUBC Carry, 1
4049   SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4050                               DAG.getVTList(CarryVT, MVT::i32),
4051                               BoolCarry, DAG.getConstant(1, DL, CarryVT));
4052   return Carry.getValue(1);
4053 }
4054 
4055 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4056                                               SelectionDAG &DAG) {
4057   SDLoc DL(Flags);
4058 
4059   // Now convert the carry flag into a boolean carry. We do this
4060   // using ARMISD:ADDE 0, 0, Carry
4061   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4062                      DAG.getConstant(0, DL, MVT::i32),
4063                      DAG.getConstant(0, DL, MVT::i32), Flags);
4064 }
4065 
4066 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4067                                              SelectionDAG &DAG) const {
4068   // Let legalize expand this if it isn't a legal type yet.
4069   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4070     return SDValue();
4071 
4072   SDValue LHS = Op.getOperand(0);
4073   SDValue RHS = Op.getOperand(1);
4074   SDLoc dl(Op);
4075 
4076   EVT VT = Op.getValueType();
4077   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4078   SDValue Value;
4079   SDValue Overflow;
4080   switch (Op.getOpcode()) {
4081   default:
4082     llvm_unreachable("Unknown overflow instruction!");
4083   case ISD::UADDO:
4084     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4085     // Convert the carry flag into a boolean value.
4086     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4087     break;
4088   case ISD::USUBO: {
4089     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4090     // Convert the carry flag into a boolean value.
4091     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4092     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4093     // value. So compute 1 - C.
4094     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4095                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4096     break;
4097   }
4098   }
4099 
4100   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4101 }
4102 
4103 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4104   SDValue Cond = Op.getOperand(0);
4105   SDValue SelectTrue = Op.getOperand(1);
4106   SDValue SelectFalse = Op.getOperand(2);
4107   SDLoc dl(Op);
4108   unsigned Opc = Cond.getOpcode();
4109 
4110   if (Cond.getResNo() == 1 &&
4111       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4112        Opc == ISD::USUBO)) {
4113     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4114       return SDValue();
4115 
4116     SDValue Value, OverflowCmp;
4117     SDValue ARMcc;
4118     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4119     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4120     EVT VT = Op.getValueType();
4121 
4122     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4123                    OverflowCmp, DAG);
4124   }
4125 
4126   // Convert:
4127   //
4128   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4129   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4130   //
4131   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4132     const ConstantSDNode *CMOVTrue =
4133       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4134     const ConstantSDNode *CMOVFalse =
4135       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4136 
4137     if (CMOVTrue && CMOVFalse) {
4138       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4139       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4140 
4141       SDValue True;
4142       SDValue False;
4143       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4144         True = SelectTrue;
4145         False = SelectFalse;
4146       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4147         True = SelectFalse;
4148         False = SelectTrue;
4149       }
4150 
4151       if (True.getNode() && False.getNode()) {
4152         EVT VT = Op.getValueType();
4153         SDValue ARMcc = Cond.getOperand(2);
4154         SDValue CCR = Cond.getOperand(3);
4155         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4156         assert(True.getValueType() == VT);
4157         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4158       }
4159     }
4160   }
4161 
4162   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4163   // undefined bits before doing a full-word comparison with zero.
4164   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4165                      DAG.getConstant(1, dl, Cond.getValueType()));
4166 
4167   return DAG.getSelectCC(dl, Cond,
4168                          DAG.getConstant(0, dl, Cond.getValueType()),
4169                          SelectTrue, SelectFalse, ISD::SETNE);
4170 }
4171 
4172 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4173                                  bool &swpCmpOps, bool &swpVselOps) {
4174   // Start by selecting the GE condition code for opcodes that return true for
4175   // 'equality'
4176   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4177       CC == ISD::SETULE)
4178     CondCode = ARMCC::GE;
4179 
4180   // and GT for opcodes that return false for 'equality'.
4181   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4182            CC == ISD::SETULT)
4183     CondCode = ARMCC::GT;
4184 
4185   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4186   // to swap the compare operands.
4187   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4188       CC == ISD::SETULT)
4189     swpCmpOps = true;
4190 
4191   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4192   // If we have an unordered opcode, we need to swap the operands to the VSEL
4193   // instruction (effectively negating the condition).
4194   //
4195   // This also has the effect of swapping which one of 'less' or 'greater'
4196   // returns true, so we also swap the compare operands. It also switches
4197   // whether we return true for 'equality', so we compensate by picking the
4198   // opposite condition code to our original choice.
4199   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4200       CC == ISD::SETUGT) {
4201     swpCmpOps = !swpCmpOps;
4202     swpVselOps = !swpVselOps;
4203     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4204   }
4205 
4206   // 'ordered' is 'anything but unordered', so use the VS condition code and
4207   // swap the VSEL operands.
4208   if (CC == ISD::SETO) {
4209     CondCode = ARMCC::VS;
4210     swpVselOps = true;
4211   }
4212 
4213   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4214   // code and swap the VSEL operands.
4215   if (CC == ISD::SETUNE) {
4216     CondCode = ARMCC::EQ;
4217     swpVselOps = true;
4218   }
4219 }
4220 
4221 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4222                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4223                                    SDValue Cmp, SelectionDAG &DAG) const {
4224   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4225     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4226                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4227     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4228                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4229 
4230     SDValue TrueLow = TrueVal.getValue(0);
4231     SDValue TrueHigh = TrueVal.getValue(1);
4232     SDValue FalseLow = FalseVal.getValue(0);
4233     SDValue FalseHigh = FalseVal.getValue(1);
4234 
4235     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4236                               ARMcc, CCR, Cmp);
4237     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4238                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4239 
4240     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4241   } else {
4242     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4243                        Cmp);
4244   }
4245 }
4246 
4247 static bool isGTorGE(ISD::CondCode CC) {
4248   return CC == ISD::SETGT || CC == ISD::SETGE;
4249 }
4250 
4251 static bool isLTorLE(ISD::CondCode CC) {
4252   return CC == ISD::SETLT || CC == ISD::SETLE;
4253 }
4254 
4255 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4256 // All of these conditions (and their <= and >= counterparts) will do:
4257 //          x < k ? k : x
4258 //          x > k ? x : k
4259 //          k < x ? x : k
4260 //          k > x ? k : x
4261 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4262                             const SDValue TrueVal, const SDValue FalseVal,
4263                             const ISD::CondCode CC, const SDValue K) {
4264   return (isGTorGE(CC) &&
4265           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4266          (isLTorLE(CC) &&
4267           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4268 }
4269 
4270 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4271 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4272                             const SDValue TrueVal, const SDValue FalseVal,
4273                             const ISD::CondCode CC, const SDValue K) {
4274   return (isGTorGE(CC) &&
4275           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4276          (isLTorLE(CC) &&
4277           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4278 }
4279 
4280 // Check if two chained conditionals could be converted into SSAT or USAT.
4281 //
4282 // SSAT can replace a set of two conditional selectors that bound a number to an
4283 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4284 //
4285 //     x < -k ? -k : (x > k ? k : x)
4286 //     x < -k ? -k : (x < k ? x : k)
4287 //     x > -k ? (x > k ? k : x) : -k
4288 //     x < k ? (x < -k ? -k : x) : k
4289 //     etc.
4290 //
4291 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4292 // a power of 2.
4293 //
4294 // It returns true if the conversion can be done, false otherwise.
4295 // Additionally, the variable is returned in parameter V, the constant in K and
4296 // usat is set to true if the conditional represents an unsigned saturation
4297 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4298                                     uint64_t &K, bool &usat) {
4299   SDValue LHS1 = Op.getOperand(0);
4300   SDValue RHS1 = Op.getOperand(1);
4301   SDValue TrueVal1 = Op.getOperand(2);
4302   SDValue FalseVal1 = Op.getOperand(3);
4303   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4304 
4305   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4306   if (Op2.getOpcode() != ISD::SELECT_CC)
4307     return false;
4308 
4309   SDValue LHS2 = Op2.getOperand(0);
4310   SDValue RHS2 = Op2.getOperand(1);
4311   SDValue TrueVal2 = Op2.getOperand(2);
4312   SDValue FalseVal2 = Op2.getOperand(3);
4313   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4314 
4315   // Find out which are the constants and which are the variables
4316   // in each conditional
4317   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4318                                                         ? &RHS1
4319                                                         : nullptr;
4320   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4321                                                         ? &RHS2
4322                                                         : nullptr;
4323   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4324   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4325   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4326   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4327 
4328   // We must detect cases where the original operations worked with 16- or
4329   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4330   // must work with sign-extended values but the select operations return
4331   // the original non-extended value.
4332   SDValue V2TmpReg = V2Tmp;
4333   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4334     V2TmpReg = V2Tmp->getOperand(0);
4335 
4336   // Check that the registers and the constants have the correct values
4337   // in both conditionals
4338   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4339       V2TmpReg != V2)
4340     return false;
4341 
4342   // Figure out which conditional is saturating the lower/upper bound.
4343   const SDValue *LowerCheckOp =
4344       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4345           ? &Op
4346           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4347                 ? &Op2
4348                 : nullptr;
4349   const SDValue *UpperCheckOp =
4350       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4351           ? &Op
4352           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4353                 ? &Op2
4354                 : nullptr;
4355 
4356   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4357     return false;
4358 
4359   // Check that the constant in the lower-bound check is
4360   // the opposite of the constant in the upper-bound check
4361   // in 1's complement.
4362   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4363   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4364   int64_t PosVal = std::max(Val1, Val2);
4365   int64_t NegVal = std::min(Val1, Val2);
4366 
4367   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4368        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4369       isPowerOf2_64(PosVal + 1)) {
4370 
4371     // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4372     if (Val1 == ~Val2)
4373       usat = false;
4374     else if (NegVal == 0)
4375       usat = true;
4376     else
4377       return false;
4378 
4379     V = V2;
4380     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4381 
4382     return true;
4383   }
4384 
4385   return false;
4386 }
4387 
4388 // Check if a condition of the type x < k ? k : x can be converted into a
4389 // bit operation instead of conditional moves.
4390 // Currently this is allowed given:
4391 // - The conditions and values match up
4392 // - k is 0 or -1 (all ones)
4393 // This function will not check the last condition, thats up to the caller
4394 // It returns true if the transformation can be made, and in such case
4395 // returns x in V, and k in SatK.
4396 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4397                                          SDValue &SatK)
4398 {
4399   SDValue LHS = Op.getOperand(0);
4400   SDValue RHS = Op.getOperand(1);
4401   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4402   SDValue TrueVal = Op.getOperand(2);
4403   SDValue FalseVal = Op.getOperand(3);
4404 
4405   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4406                                                ? &RHS
4407                                                : nullptr;
4408 
4409   // No constant operation in comparison, early out
4410   if (!K)
4411     return false;
4412 
4413   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4414   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4415   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4416 
4417   // If the constant on left and right side, or variable on left and right,
4418   // does not match, early out
4419   if (*K != KTmp || V != VTmp)
4420     return false;
4421 
4422   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4423     SatK = *K;
4424     return true;
4425   }
4426 
4427   return false;
4428 }
4429 
4430 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4431   EVT VT = Op.getValueType();
4432   SDLoc dl(Op);
4433 
4434   // Try to convert two saturating conditional selects into a single SSAT
4435   SDValue SatValue;
4436   uint64_t SatConstant;
4437   bool SatUSat;
4438   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4439       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4440     if (SatUSat)
4441       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4442                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4443     else
4444       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4445                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4446   }
4447 
4448   // Try to convert expressions of the form x < k ? k : x (and similar forms)
4449   // into more efficient bit operations, which is possible when k is 0 or -1
4450   // On ARM and Thumb-2 which have flexible operand 2 this will result in
4451   // single instructions. On Thumb the shift and the bit operation will be two
4452   // instructions.
4453   // Only allow this transformation on full-width (32-bit) operations
4454   SDValue LowerSatConstant;
4455   if (VT == MVT::i32 &&
4456       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4457     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4458                                  DAG.getConstant(31, dl, VT));
4459     if (isNullConstant(LowerSatConstant)) {
4460       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4461                                       DAG.getAllOnesConstant(dl, VT));
4462       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4463     } else if (isAllOnesConstant(LowerSatConstant))
4464       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4465   }
4466 
4467   SDValue LHS = Op.getOperand(0);
4468   SDValue RHS = Op.getOperand(1);
4469   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4470   SDValue TrueVal = Op.getOperand(2);
4471   SDValue FalseVal = Op.getOperand(3);
4472 
4473   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4474     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4475                                                     dl);
4476 
4477     // If softenSetCCOperands only returned one value, we should compare it to
4478     // zero.
4479     if (!RHS.getNode()) {
4480       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4481       CC = ISD::SETNE;
4482     }
4483   }
4484 
4485   if (LHS.getValueType() == MVT::i32) {
4486     // Try to generate VSEL on ARMv8.
4487     // The VSEL instruction can't use all the usual ARM condition
4488     // codes: it only has two bits to select the condition code, so it's
4489     // constrained to use only GE, GT, VS and EQ.
4490     //
4491     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4492     // swap the operands of the previous compare instruction (effectively
4493     // inverting the compare condition, swapping 'less' and 'greater') and
4494     // sometimes need to swap the operands to the VSEL (which inverts the
4495     // condition in the sense of firing whenever the previous condition didn't)
4496     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4497                                     TrueVal.getValueType() == MVT::f64)) {
4498       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4499       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4500           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4501         CC = ISD::getSetCCInverse(CC, true);
4502         std::swap(TrueVal, FalseVal);
4503       }
4504     }
4505 
4506     SDValue ARMcc;
4507     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4508     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4509     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4510   }
4511 
4512   ARMCC::CondCodes CondCode, CondCode2;
4513   bool InvalidOnQNaN;
4514   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4515 
4516   // Normalize the fp compare. If RHS is zero we keep it there so we match
4517   // CMPFPw0 instead of CMPFP.
4518   if (Subtarget->hasFPARMv8() && !isFloatingPointZero(RHS) &&
4519      (TrueVal.getValueType() == MVT::f16 ||
4520       TrueVal.getValueType() == MVT::f32 ||
4521       TrueVal.getValueType() == MVT::f64)) {
4522     bool swpCmpOps = false;
4523     bool swpVselOps = false;
4524     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4525 
4526     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4527         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4528       if (swpCmpOps)
4529         std::swap(LHS, RHS);
4530       if (swpVselOps)
4531         std::swap(TrueVal, FalseVal);
4532     }
4533   }
4534 
4535   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4536   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4537   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4538   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4539   if (CondCode2 != ARMCC::AL) {
4540     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4541     // FIXME: Needs another CMP because flag can have but one use.
4542     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4543     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4544   }
4545   return Result;
4546 }
4547 
4548 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4549 /// to morph to an integer compare sequence.
4550 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4551                            const ARMSubtarget *Subtarget) {
4552   SDNode *N = Op.getNode();
4553   if (!N->hasOneUse())
4554     // Otherwise it requires moving the value from fp to integer registers.
4555     return false;
4556   if (!N->getNumValues())
4557     return false;
4558   EVT VT = Op.getValueType();
4559   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4560     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4561     // vmrs are very slow, e.g. cortex-a8.
4562     return false;
4563 
4564   if (isFloatingPointZero(Op)) {
4565     SeenZero = true;
4566     return true;
4567   }
4568   return ISD::isNormalLoad(N);
4569 }
4570 
4571 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4572   if (isFloatingPointZero(Op))
4573     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4574 
4575   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4576     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4577                        Ld->getPointerInfo(), Ld->getAlignment(),
4578                        Ld->getMemOperand()->getFlags());
4579 
4580   llvm_unreachable("Unknown VFP cmp argument!");
4581 }
4582 
4583 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4584                            SDValue &RetVal1, SDValue &RetVal2) {
4585   SDLoc dl(Op);
4586 
4587   if (isFloatingPointZero(Op)) {
4588     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4589     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4590     return;
4591   }
4592 
4593   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4594     SDValue Ptr = Ld->getBasePtr();
4595     RetVal1 =
4596         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4597                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4598 
4599     EVT PtrType = Ptr.getValueType();
4600     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4601     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4602                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4603     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4604                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4605                           Ld->getMemOperand()->getFlags());
4606     return;
4607   }
4608 
4609   llvm_unreachable("Unknown VFP cmp argument!");
4610 }
4611 
4612 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4613 /// f32 and even f64 comparisons to integer ones.
4614 SDValue
4615 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4616   SDValue Chain = Op.getOperand(0);
4617   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4618   SDValue LHS = Op.getOperand(2);
4619   SDValue RHS = Op.getOperand(3);
4620   SDValue Dest = Op.getOperand(4);
4621   SDLoc dl(Op);
4622 
4623   bool LHSSeenZero = false;
4624   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4625   bool RHSSeenZero = false;
4626   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4627   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4628     // If unsafe fp math optimization is enabled and there are no other uses of
4629     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4630     // to an integer comparison.
4631     if (CC == ISD::SETOEQ)
4632       CC = ISD::SETEQ;
4633     else if (CC == ISD::SETUNE)
4634       CC = ISD::SETNE;
4635 
4636     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4637     SDValue ARMcc;
4638     if (LHS.getValueType() == MVT::f32) {
4639       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4640                         bitcastf32Toi32(LHS, DAG), Mask);
4641       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4642                         bitcastf32Toi32(RHS, DAG), Mask);
4643       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4644       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4645       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4646                          Chain, Dest, ARMcc, CCR, Cmp);
4647     }
4648 
4649     SDValue LHS1, LHS2;
4650     SDValue RHS1, RHS2;
4651     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4652     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4653     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4654     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4655     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4656     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4657     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4658     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4659     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4660   }
4661 
4662   return SDValue();
4663 }
4664 
4665 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4666   SDValue Chain = Op.getOperand(0);
4667   SDValue Cond = Op.getOperand(1);
4668   SDValue Dest = Op.getOperand(2);
4669   SDLoc dl(Op);
4670 
4671   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4672   // instruction.
4673   unsigned Opc = Cond.getOpcode();
4674   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4675                       !Subtarget->isThumb1Only();
4676   if (Cond.getResNo() == 1 &&
4677       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4678        Opc == ISD::USUBO || OptimizeMul)) {
4679     // Only lower legal XALUO ops.
4680     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4681       return SDValue();
4682 
4683     // The actual operation with overflow check.
4684     SDValue Value, OverflowCmp;
4685     SDValue ARMcc;
4686     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4687 
4688     // Reverse the condition code.
4689     ARMCC::CondCodes CondCode =
4690         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4691     CondCode = ARMCC::getOppositeCondition(CondCode);
4692     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4693     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4694 
4695     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4696                        OverflowCmp);
4697   }
4698 
4699   return SDValue();
4700 }
4701 
4702 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4703   SDValue Chain = Op.getOperand(0);
4704   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4705   SDValue LHS = Op.getOperand(2);
4706   SDValue RHS = Op.getOperand(3);
4707   SDValue Dest = Op.getOperand(4);
4708   SDLoc dl(Op);
4709 
4710   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4711     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4712                                                     dl);
4713 
4714     // If softenSetCCOperands only returned one value, we should compare it to
4715     // zero.
4716     if (!RHS.getNode()) {
4717       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4718       CC = ISD::SETNE;
4719     }
4720   }
4721 
4722   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4723   // instruction.
4724   unsigned Opc = LHS.getOpcode();
4725   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4726                       !Subtarget->isThumb1Only();
4727   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
4728       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4729        Opc == ISD::USUBO || OptimizeMul) &&
4730       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4731     // Only lower legal XALUO ops.
4732     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4733       return SDValue();
4734 
4735     // The actual operation with overflow check.
4736     SDValue Value, OverflowCmp;
4737     SDValue ARMcc;
4738     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
4739 
4740     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
4741       // Reverse the condition code.
4742       ARMCC::CondCodes CondCode =
4743           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4744       CondCode = ARMCC::getOppositeCondition(CondCode);
4745       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4746     }
4747     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4748 
4749     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4750                        OverflowCmp);
4751   }
4752 
4753   if (LHS.getValueType() == MVT::i32) {
4754     SDValue ARMcc;
4755     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4756     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4757     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4758                        Chain, Dest, ARMcc, CCR, Cmp);
4759   }
4760 
4761   if (getTargetMachine().Options.UnsafeFPMath &&
4762       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4763        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4764     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4765       return Result;
4766   }
4767 
4768   ARMCC::CondCodes CondCode, CondCode2;
4769   bool InvalidOnQNaN;
4770   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4771 
4772   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4773   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4774   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4775   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4776   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4777   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4778   if (CondCode2 != ARMCC::AL) {
4779     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4780     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4781     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4782   }
4783   return Res;
4784 }
4785 
4786 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4787   SDValue Chain = Op.getOperand(0);
4788   SDValue Table = Op.getOperand(1);
4789   SDValue Index = Op.getOperand(2);
4790   SDLoc dl(Op);
4791 
4792   EVT PTy = getPointerTy(DAG.getDataLayout());
4793   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4794   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4795   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4796   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4797   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
4798   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4799     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4800     // which does another jump to the destination. This also makes it easier
4801     // to translate it to TBB / TBH later (Thumb2 only).
4802     // FIXME: This might not work if the function is extremely large.
4803     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4804                        Addr, Op.getOperand(2), JTI);
4805   }
4806   if (isPositionIndependent() || Subtarget->isROPI()) {
4807     Addr =
4808         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4809                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4810     Chain = Addr.getValue(1);
4811     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
4812     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4813   } else {
4814     Addr =
4815         DAG.getLoad(PTy, dl, Chain, Addr,
4816                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4817     Chain = Addr.getValue(1);
4818     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4819   }
4820 }
4821 
4822 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4823   EVT VT = Op.getValueType();
4824   SDLoc dl(Op);
4825 
4826   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4827     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4828       return Op;
4829     return DAG.UnrollVectorOp(Op.getNode());
4830   }
4831 
4832   const bool HasFullFP16 =
4833     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
4834 
4835   EVT NewTy;
4836   const EVT OpTy = Op.getOperand(0).getValueType();
4837   if (OpTy == MVT::v4f32)
4838     NewTy = MVT::v4i32;
4839   else if (OpTy == MVT::v4f16 && HasFullFP16)
4840     NewTy = MVT::v4i16;
4841   else if (OpTy == MVT::v8f16 && HasFullFP16)
4842     NewTy = MVT::v8i16;
4843   else
4844     llvm_unreachable("Invalid type for custom lowering!");
4845 
4846   if (VT != MVT::v4i16 && VT != MVT::v8i16)
4847     return DAG.UnrollVectorOp(Op.getNode());
4848 
4849   Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
4850   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4851 }
4852 
4853 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4854   EVT VT = Op.getValueType();
4855   if (VT.isVector())
4856     return LowerVectorFP_TO_INT(Op, DAG);
4857   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4858     RTLIB::Libcall LC;
4859     if (Op.getOpcode() == ISD::FP_TO_SINT)
4860       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4861                               Op.getValueType());
4862     else
4863       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4864                               Op.getValueType());
4865     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4866                        /*isSigned*/ false, SDLoc(Op)).first;
4867   }
4868 
4869   return Op;
4870 }
4871 
4872 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4873   EVT VT = Op.getValueType();
4874   SDLoc dl(Op);
4875 
4876   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4877     if (VT.getVectorElementType() == MVT::f32)
4878       return Op;
4879     return DAG.UnrollVectorOp(Op.getNode());
4880   }
4881 
4882   assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
4883           Op.getOperand(0).getValueType() == MVT::v8i16) &&
4884          "Invalid type for custom lowering!");
4885 
4886   const bool HasFullFP16 =
4887     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
4888 
4889   EVT DestVecType;
4890   if (VT == MVT::v4f32)
4891     DestVecType = MVT::v4i32;
4892   else if (VT == MVT::v4f16 && HasFullFP16)
4893     DestVecType = MVT::v4i16;
4894   else if (VT == MVT::v8f16 && HasFullFP16)
4895     DestVecType = MVT::v8i16;
4896   else
4897     return DAG.UnrollVectorOp(Op.getNode());
4898 
4899   unsigned CastOpc;
4900   unsigned Opc;
4901   switch (Op.getOpcode()) {
4902   default: llvm_unreachable("Invalid opcode!");
4903   case ISD::SINT_TO_FP:
4904     CastOpc = ISD::SIGN_EXTEND;
4905     Opc = ISD::SINT_TO_FP;
4906     break;
4907   case ISD::UINT_TO_FP:
4908     CastOpc = ISD::ZERO_EXTEND;
4909     Opc = ISD::UINT_TO_FP;
4910     break;
4911   }
4912 
4913   Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
4914   return DAG.getNode(Opc, dl, VT, Op);
4915 }
4916 
4917 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4918   EVT VT = Op.getValueType();
4919   if (VT.isVector())
4920     return LowerVectorINT_TO_FP(Op, DAG);
4921   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4922     RTLIB::Libcall LC;
4923     if (Op.getOpcode() == ISD::SINT_TO_FP)
4924       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4925                               Op.getValueType());
4926     else
4927       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4928                               Op.getValueType());
4929     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4930                        /*isSigned*/ false, SDLoc(Op)).first;
4931   }
4932 
4933   return Op;
4934 }
4935 
4936 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4937   // Implement fcopysign with a fabs and a conditional fneg.
4938   SDValue Tmp0 = Op.getOperand(0);
4939   SDValue Tmp1 = Op.getOperand(1);
4940   SDLoc dl(Op);
4941   EVT VT = Op.getValueType();
4942   EVT SrcVT = Tmp1.getValueType();
4943   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4944     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4945   bool UseNEON = !InGPR && Subtarget->hasNEON();
4946 
4947   if (UseNEON) {
4948     // Use VBSL to copy the sign bit.
4949     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4950     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4951                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4952     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4953     if (VT == MVT::f64)
4954       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4955                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4956                          DAG.getConstant(32, dl, MVT::i32));
4957     else /*if (VT == MVT::f32)*/
4958       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4959     if (SrcVT == MVT::f32) {
4960       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4961       if (VT == MVT::f64)
4962         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4963                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4964                            DAG.getConstant(32, dl, MVT::i32));
4965     } else if (VT == MVT::f32)
4966       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4967                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4968                          DAG.getConstant(32, dl, MVT::i32));
4969     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4970     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4971 
4972     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4973                                             dl, MVT::i32);
4974     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4975     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4976                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4977 
4978     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4979                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4980                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4981     if (VT == MVT::f32) {
4982       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4983       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4984                         DAG.getConstant(0, dl, MVT::i32));
4985     } else {
4986       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4987     }
4988 
4989     return Res;
4990   }
4991 
4992   // Bitcast operand 1 to i32.
4993   if (SrcVT == MVT::f64)
4994     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4995                        Tmp1).getValue(1);
4996   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4997 
4998   // Or in the signbit with integer operations.
4999   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5000   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5001   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5002   if (VT == MVT::f32) {
5003     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5004                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5005     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5006                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5007   }
5008 
5009   // f64: Or the high part with signbit and then combine two parts.
5010   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5011                      Tmp0);
5012   SDValue Lo = Tmp0.getValue(0);
5013   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5014   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5015   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5016 }
5017 
5018 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5019   MachineFunction &MF = DAG.getMachineFunction();
5020   MachineFrameInfo &MFI = MF.getFrameInfo();
5021   MFI.setReturnAddressIsTaken(true);
5022 
5023   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5024     return SDValue();
5025 
5026   EVT VT = Op.getValueType();
5027   SDLoc dl(Op);
5028   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5029   if (Depth) {
5030     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5031     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5032     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5033                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5034                        MachinePointerInfo());
5035   }
5036 
5037   // Return LR, which contains the return address. Mark it an implicit live-in.
5038   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5039   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5040 }
5041 
5042 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5043   const ARMBaseRegisterInfo &ARI =
5044     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5045   MachineFunction &MF = DAG.getMachineFunction();
5046   MachineFrameInfo &MFI = MF.getFrameInfo();
5047   MFI.setFrameAddressIsTaken(true);
5048 
5049   EVT VT = Op.getValueType();
5050   SDLoc dl(Op);  // FIXME probably not meaningful
5051   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5052   unsigned FrameReg = ARI.getFrameRegister(MF);
5053   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5054   while (Depth--)
5055     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5056                             MachinePointerInfo());
5057   return FrameAddr;
5058 }
5059 
5060 // FIXME? Maybe this could be a TableGen attribute on some registers and
5061 // this table could be generated automatically from RegInfo.
5062 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5063                                               SelectionDAG &DAG) const {
5064   unsigned Reg = StringSwitch<unsigned>(RegName)
5065                        .Case("sp", ARM::SP)
5066                        .Default(0);
5067   if (Reg)
5068     return Reg;
5069   report_fatal_error(Twine("Invalid register name \""
5070                               + StringRef(RegName)  + "\"."));
5071 }
5072 
5073 // Result is 64 bit value so split into two 32 bit values and return as a
5074 // pair of values.
5075 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5076                                 SelectionDAG &DAG) {
5077   SDLoc DL(N);
5078 
5079   // This function is only supposed to be called for i64 type destination.
5080   assert(N->getValueType(0) == MVT::i64
5081           && "ExpandREAD_REGISTER called for non-i64 type result.");
5082 
5083   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5084                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5085                              N->getOperand(0),
5086                              N->getOperand(1));
5087 
5088   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5089                     Read.getValue(1)));
5090   Results.push_back(Read.getOperand(0));
5091 }
5092 
5093 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5094 /// When \p DstVT, the destination type of \p BC, is on the vector
5095 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5096 /// it might be possible to combine them, such that everything stays on the
5097 /// vector register bank.
5098 /// \p return The node that would replace \p BT, if the combine
5099 /// is possible.
5100 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5101                                                 SelectionDAG &DAG) {
5102   SDValue Op = BC->getOperand(0);
5103   EVT DstVT = BC->getValueType(0);
5104 
5105   // The only vector instruction that can produce a scalar (remember,
5106   // since the bitcast was about to be turned into VMOVDRR, the source
5107   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5108   // Moreover, we can do this combine only if there is one use.
5109   // Finally, if the destination type is not a vector, there is not
5110   // much point on forcing everything on the vector bank.
5111   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5112       !Op.hasOneUse())
5113     return SDValue();
5114 
5115   // If the index is not constant, we will introduce an additional
5116   // multiply that will stick.
5117   // Give up in that case.
5118   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5119   if (!Index)
5120     return SDValue();
5121   unsigned DstNumElt = DstVT.getVectorNumElements();
5122 
5123   // Compute the new index.
5124   const APInt &APIntIndex = Index->getAPIntValue();
5125   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5126   NewIndex *= APIntIndex;
5127   // Check if the new constant index fits into i32.
5128   if (NewIndex.getBitWidth() > 32)
5129     return SDValue();
5130 
5131   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5132   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5133   SDLoc dl(Op);
5134   SDValue ExtractSrc = Op.getOperand(0);
5135   EVT VecVT = EVT::getVectorVT(
5136       *DAG.getContext(), DstVT.getScalarType(),
5137       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5138   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5139   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5140                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5141 }
5142 
5143 /// ExpandBITCAST - If the target supports VFP, this function is called to
5144 /// expand a bit convert where either the source or destination type is i64 to
5145 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5146 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5147 /// vectors), since the legalizer won't know what to do with that.
5148 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5149                              const ARMSubtarget *Subtarget) {
5150   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5151   SDLoc dl(N);
5152   SDValue Op = N->getOperand(0);
5153 
5154   // This function is only supposed to be called for i64 types, either as the
5155   // source or destination of the bit convert.
5156   EVT SrcVT = Op.getValueType();
5157   EVT DstVT = N->getValueType(0);
5158   const bool HasFullFP16 = Subtarget->hasFullFP16();
5159 
5160   if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5161      // FullFP16: half values are passed in S-registers, and we don't
5162      // need any of the bitcast and moves:
5163      //
5164      // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5165      //   t5: i32 = bitcast t2
5166      // t18: f16 = ARMISD::VMOVhr t5
5167      if (Op.getOpcode() != ISD::CopyFromReg ||
5168          Op.getValueType() != MVT::f32)
5169        return SDValue();
5170 
5171      auto Move = N->use_begin();
5172      if (Move->getOpcode() != ARMISD::VMOVhr)
5173        return SDValue();
5174 
5175      SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5176      SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5177      DAG.ReplaceAllUsesWith(*Move, &Copy);
5178      return Copy;
5179   }
5180 
5181   if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5182     if (!HasFullFP16)
5183       return SDValue();
5184     // SoftFP: read half-precision arguments:
5185     //
5186     // t2: i32,ch = ...
5187     //        t7: i16 = truncate t2 <~~~~ Op
5188     //      t8: f16 = bitcast t7    <~~~~ N
5189     //
5190     if (Op.getOperand(0).getValueType() == MVT::i32)
5191       return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5192                          MVT::f16, Op.getOperand(0));
5193 
5194     return SDValue();
5195   }
5196 
5197   // Half-precision return values
5198   if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5199     if (!HasFullFP16)
5200       return SDValue();
5201     //
5202     //          t11: f16 = fadd t8, t10
5203     //        t12: i16 = bitcast t11       <~~~ SDNode N
5204     //      t13: i32 = zero_extend t12
5205     //    t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5206     //  t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5207     //
5208     // transform this into:
5209     //
5210     //    t20: i32 = ARMISD::VMOVrh t11
5211     //  t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5212     //
5213     auto ZeroExtend = N->use_begin();
5214     if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5215         ZeroExtend->getValueType(0) != MVT::i32)
5216       return SDValue();
5217 
5218     auto Copy = ZeroExtend->use_begin();
5219     if (Copy->getOpcode() == ISD::CopyToReg &&
5220         Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5221       SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5222       DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5223       return Cvt;
5224     }
5225     return SDValue();
5226   }
5227 
5228   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5229     return SDValue();
5230 
5231   // Turn i64->f64 into VMOVDRR.
5232   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5233     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5234     // if we can combine the bitcast with its source.
5235     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5236       return Val;
5237 
5238     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5239                              DAG.getConstant(0, dl, MVT::i32));
5240     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5241                              DAG.getConstant(1, dl, MVT::i32));
5242     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5243                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5244   }
5245 
5246   // Turn f64->i64 into VMOVRRD.
5247   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5248     SDValue Cvt;
5249     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5250         SrcVT.getVectorNumElements() > 1)
5251       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5252                         DAG.getVTList(MVT::i32, MVT::i32),
5253                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5254     else
5255       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5256                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5257     // Merge the pieces into a single i64 value.
5258     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5259   }
5260 
5261   return SDValue();
5262 }
5263 
5264 /// getZeroVector - Returns a vector of specified type with all zero elements.
5265 /// Zero vectors are used to represent vector negation and in those cases
5266 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
5267 /// not support i64 elements, so sometimes the zero vectors will need to be
5268 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
5269 /// zero vector.
5270 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5271   assert(VT.isVector() && "Expected a vector type");
5272   // The canonical modified immediate encoding of a zero vector is....0!
5273   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5274   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5275   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5276   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5277 }
5278 
5279 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5280 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5281 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5282                                                 SelectionDAG &DAG) const {
5283   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5284   EVT VT = Op.getValueType();
5285   unsigned VTBits = VT.getSizeInBits();
5286   SDLoc dl(Op);
5287   SDValue ShOpLo = Op.getOperand(0);
5288   SDValue ShOpHi = Op.getOperand(1);
5289   SDValue ShAmt  = Op.getOperand(2);
5290   SDValue ARMcc;
5291   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5292   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5293 
5294   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5295 
5296   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5297                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5298   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5299   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5300                                    DAG.getConstant(VTBits, dl, MVT::i32));
5301   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5302   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5303   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5304   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5305                             ISD::SETGE, ARMcc, DAG, dl);
5306   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5307                            ARMcc, CCR, CmpLo);
5308 
5309   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5310   SDValue HiBigShift = Opc == ISD::SRA
5311                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5312                                          DAG.getConstant(VTBits - 1, dl, VT))
5313                            : DAG.getConstant(0, dl, VT);
5314   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5315                             ISD::SETGE, ARMcc, DAG, dl);
5316   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5317                            ARMcc, CCR, CmpHi);
5318 
5319   SDValue Ops[2] = { Lo, Hi };
5320   return DAG.getMergeValues(Ops, dl);
5321 }
5322 
5323 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5324 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5325 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5326                                                SelectionDAG &DAG) const {
5327   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5328   EVT VT = Op.getValueType();
5329   unsigned VTBits = VT.getSizeInBits();
5330   SDLoc dl(Op);
5331   SDValue ShOpLo = Op.getOperand(0);
5332   SDValue ShOpHi = Op.getOperand(1);
5333   SDValue ShAmt  = Op.getOperand(2);
5334   SDValue ARMcc;
5335   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5336 
5337   assert(Op.getOpcode() == ISD::SHL_PARTS);
5338   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5339                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5340   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5341   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5342   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5343 
5344   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5345                                    DAG.getConstant(VTBits, dl, MVT::i32));
5346   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5347   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5348                             ISD::SETGE, ARMcc, DAG, dl);
5349   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5350                            ARMcc, CCR, CmpHi);
5351 
5352   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5353                           ISD::SETGE, ARMcc, DAG, dl);
5354   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5355   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5356                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5357 
5358   SDValue Ops[2] = { Lo, Hi };
5359   return DAG.getMergeValues(Ops, dl);
5360 }
5361 
5362 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5363                                             SelectionDAG &DAG) const {
5364   // The rounding mode is in bits 23:22 of the FPSCR.
5365   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5366   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5367   // so that the shift + and get folded into a bitfield extract.
5368   SDLoc dl(Op);
5369   SDValue Ops[] = { DAG.getEntryNode(),
5370                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5371 
5372   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5373   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5374                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5375   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5376                               DAG.getConstant(22, dl, MVT::i32));
5377   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5378                      DAG.getConstant(3, dl, MVT::i32));
5379 }
5380 
5381 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5382                          const ARMSubtarget *ST) {
5383   SDLoc dl(N);
5384   EVT VT = N->getValueType(0);
5385   if (VT.isVector()) {
5386     assert(ST->hasNEON());
5387 
5388     // Compute the least significant set bit: LSB = X & -X
5389     SDValue X = N->getOperand(0);
5390     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5391     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5392 
5393     EVT ElemTy = VT.getVectorElementType();
5394 
5395     if (ElemTy == MVT::i8) {
5396       // Compute with: cttz(x) = ctpop(lsb - 1)
5397       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5398                                 DAG.getTargetConstant(1, dl, ElemTy));
5399       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5400       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5401     }
5402 
5403     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5404         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5405       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5406       unsigned NumBits = ElemTy.getSizeInBits();
5407       SDValue WidthMinus1 =
5408           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5409                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5410       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5411       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5412     }
5413 
5414     // Compute with: cttz(x) = ctpop(lsb - 1)
5415 
5416     // Compute LSB - 1.
5417     SDValue Bits;
5418     if (ElemTy == MVT::i64) {
5419       // Load constant 0xffff'ffff'ffff'ffff to register.
5420       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5421                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5422       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5423     } else {
5424       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5425                                 DAG.getTargetConstant(1, dl, ElemTy));
5426       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5427     }
5428     return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5429   }
5430 
5431   if (!ST->hasV6T2Ops())
5432     return SDValue();
5433 
5434   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5435   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5436 }
5437 
5438 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5439                           const ARMSubtarget *ST) {
5440   EVT VT = N->getValueType(0);
5441   SDLoc DL(N);
5442 
5443   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5444   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5445           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5446          "Unexpected type for custom ctpop lowering");
5447 
5448   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5449   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5450   SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5451   Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5452 
5453   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5454   unsigned EltSize = 8;
5455   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5456   while (EltSize != VT.getScalarSizeInBits()) {
5457     SmallVector<SDValue, 8> Ops;
5458     Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5459                                   TLI.getPointerTy(DAG.getDataLayout())));
5460     Ops.push_back(Res);
5461 
5462     EltSize *= 2;
5463     NumElts /= 2;
5464     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5465     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5466   }
5467 
5468   return Res;
5469 }
5470 
5471 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5472                           const ARMSubtarget *ST) {
5473   EVT VT = N->getValueType(0);
5474   SDLoc dl(N);
5475 
5476   if (!VT.isVector())
5477     return SDValue();
5478 
5479   // Lower vector shifts on NEON to use VSHL.
5480   assert(ST->hasNEON() && "unexpected vector shift");
5481 
5482   // Left shifts translate directly to the vshiftu intrinsic.
5483   if (N->getOpcode() == ISD::SHL)
5484     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5485                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5486                                        MVT::i32),
5487                        N->getOperand(0), N->getOperand(1));
5488 
5489   assert((N->getOpcode() == ISD::SRA ||
5490           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5491 
5492   // NEON uses the same intrinsics for both left and right shifts.  For
5493   // right shifts, the shift amounts are negative, so negate the vector of
5494   // shift amounts.
5495   EVT ShiftVT = N->getOperand(1).getValueType();
5496   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5497                                      getZeroVector(ShiftVT, DAG, dl),
5498                                      N->getOperand(1));
5499   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5500                              Intrinsic::arm_neon_vshifts :
5501                              Intrinsic::arm_neon_vshiftu);
5502   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5503                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5504                      N->getOperand(0), NegatedCount);
5505 }
5506 
5507 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5508                                 const ARMSubtarget *ST) {
5509   EVT VT = N->getValueType(0);
5510   SDLoc dl(N);
5511 
5512   // We can get here for a node like i32 = ISD::SHL i32, i64
5513   if (VT != MVT::i64)
5514     return SDValue();
5515 
5516   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5517          "Unknown shift to lower!");
5518 
5519   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5520   if (!isOneConstant(N->getOperand(1)))
5521     return SDValue();
5522 
5523   // If we are in thumb mode, we don't have RRX.
5524   if (ST->isThumb1Only()) return SDValue();
5525 
5526   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5527   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5528                            DAG.getConstant(0, dl, MVT::i32));
5529   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5530                            DAG.getConstant(1, dl, MVT::i32));
5531 
5532   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5533   // captures the result into a carry flag.
5534   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5535   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5536 
5537   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5538   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5539 
5540   // Merge the pieces into a single i64 value.
5541  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5542 }
5543 
5544 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5545   SDValue TmpOp0, TmpOp1;
5546   bool Invert = false;
5547   bool Swap = false;
5548   unsigned Opc = 0;
5549 
5550   SDValue Op0 = Op.getOperand(0);
5551   SDValue Op1 = Op.getOperand(1);
5552   SDValue CC = Op.getOperand(2);
5553   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5554   EVT VT = Op.getValueType();
5555   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5556   SDLoc dl(Op);
5557 
5558   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5559       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5560     // Special-case integer 64-bit equality comparisons. They aren't legal,
5561     // but they can be lowered with a few vector instructions.
5562     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5563     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5564     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5565     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5566     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5567                               DAG.getCondCode(ISD::SETEQ));
5568     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5569     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5570     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5571     if (SetCCOpcode == ISD::SETNE)
5572       Merged = DAG.getNOT(dl, Merged, CmpVT);
5573     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5574     return Merged;
5575   }
5576 
5577   if (CmpVT.getVectorElementType() == MVT::i64)
5578     // 64-bit comparisons are not legal in general.
5579     return SDValue();
5580 
5581   if (Op1.getValueType().isFloatingPoint()) {
5582     switch (SetCCOpcode) {
5583     default: llvm_unreachable("Illegal FP comparison");
5584     case ISD::SETUNE:
5585     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5586     case ISD::SETOEQ:
5587     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5588     case ISD::SETOLT:
5589     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5590     case ISD::SETOGT:
5591     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5592     case ISD::SETOLE:
5593     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5594     case ISD::SETOGE:
5595     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5596     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5597     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5598     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5599     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5600     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5601     case ISD::SETONE:
5602       // Expand this to (OLT | OGT).
5603       TmpOp0 = Op0;
5604       TmpOp1 = Op1;
5605       Opc = ISD::OR;
5606       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5607       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5608       break;
5609     case ISD::SETUO:
5610       Invert = true;
5611       LLVM_FALLTHROUGH;
5612     case ISD::SETO:
5613       // Expand this to (OLT | OGE).
5614       TmpOp0 = Op0;
5615       TmpOp1 = Op1;
5616       Opc = ISD::OR;
5617       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5618       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5619       break;
5620     }
5621   } else {
5622     // Integer comparisons.
5623     switch (SetCCOpcode) {
5624     default: llvm_unreachable("Illegal integer comparison");
5625     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5626     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5627     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
5628     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5629     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5630     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5631     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5632     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5633     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5634     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5635     }
5636 
5637     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5638     if (Opc == ARMISD::VCEQ) {
5639       SDValue AndOp;
5640       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5641         AndOp = Op0;
5642       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5643         AndOp = Op1;
5644 
5645       // Ignore bitconvert.
5646       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5647         AndOp = AndOp.getOperand(0);
5648 
5649       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5650         Opc = ARMISD::VTST;
5651         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5652         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5653         Invert = !Invert;
5654       }
5655     }
5656   }
5657 
5658   if (Swap)
5659     std::swap(Op0, Op1);
5660 
5661   // If one of the operands is a constant vector zero, attempt to fold the
5662   // comparison to a specialized compare-against-zero form.
5663   SDValue SingleOp;
5664   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5665     SingleOp = Op0;
5666   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5667     if (Opc == ARMISD::VCGE)
5668       Opc = ARMISD::VCLEZ;
5669     else if (Opc == ARMISD::VCGT)
5670       Opc = ARMISD::VCLTZ;
5671     SingleOp = Op1;
5672   }
5673 
5674   SDValue Result;
5675   if (SingleOp.getNode()) {
5676     switch (Opc) {
5677     case ARMISD::VCEQ:
5678       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5679     case ARMISD::VCGE:
5680       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5681     case ARMISD::VCLEZ:
5682       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5683     case ARMISD::VCGT:
5684       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5685     case ARMISD::VCLTZ:
5686       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5687     default:
5688       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5689     }
5690   } else {
5691      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5692   }
5693 
5694   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5695 
5696   if (Invert)
5697     Result = DAG.getNOT(dl, Result, VT);
5698 
5699   return Result;
5700 }
5701 
5702 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
5703   SDValue LHS = Op.getOperand(0);
5704   SDValue RHS = Op.getOperand(1);
5705   SDValue Carry = Op.getOperand(2);
5706   SDValue Cond = Op.getOperand(3);
5707   SDLoc DL(Op);
5708 
5709   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
5710 
5711   // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
5712   // have to invert the carry first.
5713   Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
5714                       DAG.getConstant(1, DL, MVT::i32), Carry);
5715   // This converts the boolean value carry into the carry flag.
5716   Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
5717 
5718   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5719   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5720 
5721   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5722   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5723   SDValue ARMcc = DAG.getConstant(
5724       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5725   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5726   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5727                                    Cmp.getValue(1), SDValue());
5728   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5729                      CCR, Chain.getValue(1));
5730 }
5731 
5732 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5733 /// valid vector constant for a NEON instruction with a "modified immediate"
5734 /// operand (e.g., VMOV).  If so, return the encoded value.
5735 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5736                                  unsigned SplatBitSize, SelectionDAG &DAG,
5737                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5738                                  NEONModImmType type) {
5739   unsigned OpCmode, Imm;
5740 
5741   // SplatBitSize is set to the smallest size that splats the vector, so a
5742   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5743   // immediate instructions others than VMOV do not support the 8-bit encoding
5744   // of a zero vector, and the default encoding of zero is supposed to be the
5745   // 32-bit version.
5746   if (SplatBits == 0)
5747     SplatBitSize = 32;
5748 
5749   switch (SplatBitSize) {
5750   case 8:
5751     if (type != VMOVModImm)
5752       return SDValue();
5753     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5754     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5755     OpCmode = 0xe;
5756     Imm = SplatBits;
5757     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5758     break;
5759 
5760   case 16:
5761     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5762     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5763     if ((SplatBits & ~0xff) == 0) {
5764       // Value = 0x00nn: Op=x, Cmode=100x.
5765       OpCmode = 0x8;
5766       Imm = SplatBits;
5767       break;
5768     }
5769     if ((SplatBits & ~0xff00) == 0) {
5770       // Value = 0xnn00: Op=x, Cmode=101x.
5771       OpCmode = 0xa;
5772       Imm = SplatBits >> 8;
5773       break;
5774     }
5775     return SDValue();
5776 
5777   case 32:
5778     // NEON's 32-bit VMOV supports splat values where:
5779     // * only one byte is nonzero, or
5780     // * the least significant byte is 0xff and the second byte is nonzero, or
5781     // * the least significant 2 bytes are 0xff and the third is nonzero.
5782     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5783     if ((SplatBits & ~0xff) == 0) {
5784       // Value = 0x000000nn: Op=x, Cmode=000x.
5785       OpCmode = 0;
5786       Imm = SplatBits;
5787       break;
5788     }
5789     if ((SplatBits & ~0xff00) == 0) {
5790       // Value = 0x0000nn00: Op=x, Cmode=001x.
5791       OpCmode = 0x2;
5792       Imm = SplatBits >> 8;
5793       break;
5794     }
5795     if ((SplatBits & ~0xff0000) == 0) {
5796       // Value = 0x00nn0000: Op=x, Cmode=010x.
5797       OpCmode = 0x4;
5798       Imm = SplatBits >> 16;
5799       break;
5800     }
5801     if ((SplatBits & ~0xff000000) == 0) {
5802       // Value = 0xnn000000: Op=x, Cmode=011x.
5803       OpCmode = 0x6;
5804       Imm = SplatBits >> 24;
5805       break;
5806     }
5807 
5808     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5809     if (type == OtherModImm) return SDValue();
5810 
5811     if ((SplatBits & ~0xffff) == 0 &&
5812         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5813       // Value = 0x0000nnff: Op=x, Cmode=1100.
5814       OpCmode = 0xc;
5815       Imm = SplatBits >> 8;
5816       break;
5817     }
5818 
5819     if ((SplatBits & ~0xffffff) == 0 &&
5820         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5821       // Value = 0x00nnffff: Op=x, Cmode=1101.
5822       OpCmode = 0xd;
5823       Imm = SplatBits >> 16;
5824       break;
5825     }
5826 
5827     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5828     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5829     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5830     // and fall through here to test for a valid 64-bit splat.  But, then the
5831     // caller would also need to check and handle the change in size.
5832     return SDValue();
5833 
5834   case 64: {
5835     if (type != VMOVModImm)
5836       return SDValue();
5837     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5838     uint64_t BitMask = 0xff;
5839     uint64_t Val = 0;
5840     unsigned ImmMask = 1;
5841     Imm = 0;
5842     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5843       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5844         Val |= BitMask;
5845         Imm |= ImmMask;
5846       } else if ((SplatBits & BitMask) != 0) {
5847         return SDValue();
5848       }
5849       BitMask <<= 8;
5850       ImmMask <<= 1;
5851     }
5852 
5853     if (DAG.getDataLayout().isBigEndian())
5854       // swap higher and lower 32 bit word
5855       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5856 
5857     // Op=1, Cmode=1110.
5858     OpCmode = 0x1e;
5859     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5860     break;
5861   }
5862 
5863   default:
5864     llvm_unreachable("unexpected size for isNEONModifiedImm");
5865   }
5866 
5867   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5868   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5869 }
5870 
5871 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5872                                            const ARMSubtarget *ST) const {
5873   EVT VT = Op.getValueType();
5874   bool IsDouble = (VT == MVT::f64);
5875   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5876   const APFloat &FPVal = CFP->getValueAPF();
5877 
5878   // Prevent floating-point constants from using literal loads
5879   // when execute-only is enabled.
5880   if (ST->genExecuteOnly()) {
5881     // If we can represent the constant as an immediate, don't lower it
5882     if (isFPImmLegal(FPVal, VT))
5883       return Op;
5884     // Otherwise, construct as integer, and move to float register
5885     APInt INTVal = FPVal.bitcastToAPInt();
5886     SDLoc DL(CFP);
5887     switch (VT.getSimpleVT().SimpleTy) {
5888       default:
5889         llvm_unreachable("Unknown floating point type!");
5890         break;
5891       case MVT::f64: {
5892         SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5893         SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5894         if (!ST->isLittle())
5895           std::swap(Lo, Hi);
5896         return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5897       }
5898       case MVT::f32:
5899           return DAG.getNode(ARMISD::VMOVSR, DL, VT,
5900               DAG.getConstant(INTVal, DL, MVT::i32));
5901     }
5902   }
5903 
5904   if (!ST->hasVFP3())
5905     return SDValue();
5906 
5907   // Use the default (constant pool) lowering for double constants when we have
5908   // an SP-only FPU
5909   if (IsDouble && Subtarget->isFPOnlySP())
5910     return SDValue();
5911 
5912   // Try splatting with a VMOV.f32...
5913   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5914 
5915   if (ImmVal != -1) {
5916     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5917       // We have code in place to select a valid ConstantFP already, no need to
5918       // do any mangling.
5919       return Op;
5920     }
5921 
5922     // It's a float and we are trying to use NEON operations where
5923     // possible. Lower it to a splat followed by an extract.
5924     SDLoc DL(Op);
5925     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5926     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5927                                       NewVal);
5928     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5929                        DAG.getConstant(0, DL, MVT::i32));
5930   }
5931 
5932   // The rest of our options are NEON only, make sure that's allowed before
5933   // proceeding..
5934   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5935     return SDValue();
5936 
5937   EVT VMovVT;
5938   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5939 
5940   // It wouldn't really be worth bothering for doubles except for one very
5941   // important value, which does happen to match: 0.0. So make sure we don't do
5942   // anything stupid.
5943   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5944     return SDValue();
5945 
5946   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5947   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5948                                      VMovVT, false, VMOVModImm);
5949   if (NewVal != SDValue()) {
5950     SDLoc DL(Op);
5951     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5952                                       NewVal);
5953     if (IsDouble)
5954       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5955 
5956     // It's a float: cast and extract a vector element.
5957     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5958                                        VecConstant);
5959     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5960                        DAG.getConstant(0, DL, MVT::i32));
5961   }
5962 
5963   // Finally, try a VMVN.i32
5964   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5965                              false, VMVNModImm);
5966   if (NewVal != SDValue()) {
5967     SDLoc DL(Op);
5968     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5969 
5970     if (IsDouble)
5971       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5972 
5973     // It's a float: cast and extract a vector element.
5974     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5975                                        VecConstant);
5976     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5977                        DAG.getConstant(0, DL, MVT::i32));
5978   }
5979 
5980   return SDValue();
5981 }
5982 
5983 // check if an VEXT instruction can handle the shuffle mask when the
5984 // vector sources of the shuffle are the same.
5985 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5986   unsigned NumElts = VT.getVectorNumElements();
5987 
5988   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5989   if (M[0] < 0)
5990     return false;
5991 
5992   Imm = M[0];
5993 
5994   // If this is a VEXT shuffle, the immediate value is the index of the first
5995   // element.  The other shuffle indices must be the successive elements after
5996   // the first one.
5997   unsigned ExpectedElt = Imm;
5998   for (unsigned i = 1; i < NumElts; ++i) {
5999     // Increment the expected index.  If it wraps around, just follow it
6000     // back to index zero and keep going.
6001     ++ExpectedElt;
6002     if (ExpectedElt == NumElts)
6003       ExpectedElt = 0;
6004 
6005     if (M[i] < 0) continue; // ignore UNDEF indices
6006     if (ExpectedElt != static_cast<unsigned>(M[i]))
6007       return false;
6008   }
6009 
6010   return true;
6011 }
6012 
6013 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6014                        bool &ReverseVEXT, unsigned &Imm) {
6015   unsigned NumElts = VT.getVectorNumElements();
6016   ReverseVEXT = false;
6017 
6018   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6019   if (M[0] < 0)
6020     return false;
6021 
6022   Imm = M[0];
6023 
6024   // If this is a VEXT shuffle, the immediate value is the index of the first
6025   // element.  The other shuffle indices must be the successive elements after
6026   // the first one.
6027   unsigned ExpectedElt = Imm;
6028   for (unsigned i = 1; i < NumElts; ++i) {
6029     // Increment the expected index.  If it wraps around, it may still be
6030     // a VEXT but the source vectors must be swapped.
6031     ExpectedElt += 1;
6032     if (ExpectedElt == NumElts * 2) {
6033       ExpectedElt = 0;
6034       ReverseVEXT = true;
6035     }
6036 
6037     if (M[i] < 0) continue; // ignore UNDEF indices
6038     if (ExpectedElt != static_cast<unsigned>(M[i]))
6039       return false;
6040   }
6041 
6042   // Adjust the index value if the source operands will be swapped.
6043   if (ReverseVEXT)
6044     Imm -= NumElts;
6045 
6046   return true;
6047 }
6048 
6049 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6050 /// instruction with the specified blocksize.  (The order of the elements
6051 /// within each block of the vector is reversed.)
6052 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6053   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6054          "Only possible block sizes for VREV are: 16, 32, 64");
6055 
6056   unsigned EltSz = VT.getScalarSizeInBits();
6057   if (EltSz == 64)
6058     return false;
6059 
6060   unsigned NumElts = VT.getVectorNumElements();
6061   unsigned BlockElts = M[0] + 1;
6062   // If the first shuffle index is UNDEF, be optimistic.
6063   if (M[0] < 0)
6064     BlockElts = BlockSize / EltSz;
6065 
6066   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6067     return false;
6068 
6069   for (unsigned i = 0; i < NumElts; ++i) {
6070     if (M[i] < 0) continue; // ignore UNDEF indices
6071     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6072       return false;
6073   }
6074 
6075   return true;
6076 }
6077 
6078 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6079   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6080   // range, then 0 is placed into the resulting vector. So pretty much any mask
6081   // of 8 elements can work here.
6082   return VT == MVT::v8i8 && M.size() == 8;
6083 }
6084 
6085 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6086                                unsigned Index) {
6087   if (Mask.size() == Elements * 2)
6088     return Index / Elements;
6089   return Mask[Index] == 0 ? 0 : 1;
6090 }
6091 
6092 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6093 // checking that pairs of elements in the shuffle mask represent the same index
6094 // in each vector, incrementing the expected index by 2 at each step.
6095 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6096 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6097 //  v2={e,f,g,h}
6098 // WhichResult gives the offset for each element in the mask based on which
6099 // of the two results it belongs to.
6100 //
6101 // The transpose can be represented either as:
6102 // result1 = shufflevector v1, v2, result1_shuffle_mask
6103 // result2 = shufflevector v1, v2, result2_shuffle_mask
6104 // where v1/v2 and the shuffle masks have the same number of elements
6105 // (here WhichResult (see below) indicates which result is being checked)
6106 //
6107 // or as:
6108 // results = shufflevector v1, v2, shuffle_mask
6109 // where both results are returned in one vector and the shuffle mask has twice
6110 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6111 // want to check the low half and high half of the shuffle mask as if it were
6112 // the other case
6113 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6114   unsigned EltSz = VT.getScalarSizeInBits();
6115   if (EltSz == 64)
6116     return false;
6117 
6118   unsigned NumElts = VT.getVectorNumElements();
6119   if (M.size() != NumElts && M.size() != NumElts*2)
6120     return false;
6121 
6122   // If the mask is twice as long as the input vector then we need to check the
6123   // upper and lower parts of the mask with a matching value for WhichResult
6124   // FIXME: A mask with only even values will be rejected in case the first
6125   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6126   // M[0] is used to determine WhichResult
6127   for (unsigned i = 0; i < M.size(); i += NumElts) {
6128     WhichResult = SelectPairHalf(NumElts, M, i);
6129     for (unsigned j = 0; j < NumElts; j += 2) {
6130       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6131           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6132         return false;
6133     }
6134   }
6135 
6136   if (M.size() == NumElts*2)
6137     WhichResult = 0;
6138 
6139   return true;
6140 }
6141 
6142 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6143 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6144 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6145 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6146   unsigned EltSz = VT.getScalarSizeInBits();
6147   if (EltSz == 64)
6148     return false;
6149 
6150   unsigned NumElts = VT.getVectorNumElements();
6151   if (M.size() != NumElts && M.size() != NumElts*2)
6152     return false;
6153 
6154   for (unsigned i = 0; i < M.size(); i += NumElts) {
6155     WhichResult = SelectPairHalf(NumElts, M, i);
6156     for (unsigned j = 0; j < NumElts; j += 2) {
6157       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6158           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6159         return false;
6160     }
6161   }
6162 
6163   if (M.size() == NumElts*2)
6164     WhichResult = 0;
6165 
6166   return true;
6167 }
6168 
6169 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6170 // that the mask elements are either all even and in steps of size 2 or all odd
6171 // and in steps of size 2.
6172 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6173 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6174 //  v2={e,f,g,h}
6175 // Requires similar checks to that of isVTRNMask with
6176 // respect the how results are returned.
6177 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6178   unsigned EltSz = VT.getScalarSizeInBits();
6179   if (EltSz == 64)
6180     return false;
6181 
6182   unsigned NumElts = VT.getVectorNumElements();
6183   if (M.size() != NumElts && M.size() != NumElts*2)
6184     return false;
6185 
6186   for (unsigned i = 0; i < M.size(); i += NumElts) {
6187     WhichResult = SelectPairHalf(NumElts, M, i);
6188     for (unsigned j = 0; j < NumElts; ++j) {
6189       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6190         return false;
6191     }
6192   }
6193 
6194   if (M.size() == NumElts*2)
6195     WhichResult = 0;
6196 
6197   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6198   if (VT.is64BitVector() && EltSz == 32)
6199     return false;
6200 
6201   return true;
6202 }
6203 
6204 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6205 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6206 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6207 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6208   unsigned EltSz = VT.getScalarSizeInBits();
6209   if (EltSz == 64)
6210     return false;
6211 
6212   unsigned NumElts = VT.getVectorNumElements();
6213   if (M.size() != NumElts && M.size() != NumElts*2)
6214     return false;
6215 
6216   unsigned Half = NumElts / 2;
6217   for (unsigned i = 0; i < M.size(); i += NumElts) {
6218     WhichResult = SelectPairHalf(NumElts, M, i);
6219     for (unsigned j = 0; j < NumElts; j += Half) {
6220       unsigned Idx = WhichResult;
6221       for (unsigned k = 0; k < Half; ++k) {
6222         int MIdx = M[i + j + k];
6223         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6224           return false;
6225         Idx += 2;
6226       }
6227     }
6228   }
6229 
6230   if (M.size() == NumElts*2)
6231     WhichResult = 0;
6232 
6233   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6234   if (VT.is64BitVector() && EltSz == 32)
6235     return false;
6236 
6237   return true;
6238 }
6239 
6240 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6241 // that pairs of elements of the shufflemask represent the same index in each
6242 // vector incrementing sequentially through the vectors.
6243 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6244 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6245 //  v2={e,f,g,h}
6246 // Requires similar checks to that of isVTRNMask with respect the how results
6247 // are returned.
6248 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6249   unsigned EltSz = VT.getScalarSizeInBits();
6250   if (EltSz == 64)
6251     return false;
6252 
6253   unsigned NumElts = VT.getVectorNumElements();
6254   if (M.size() != NumElts && M.size() != NumElts*2)
6255     return false;
6256 
6257   for (unsigned i = 0; i < M.size(); i += NumElts) {
6258     WhichResult = SelectPairHalf(NumElts, M, i);
6259     unsigned Idx = WhichResult * NumElts / 2;
6260     for (unsigned j = 0; j < NumElts; j += 2) {
6261       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6262           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6263         return false;
6264       Idx += 1;
6265     }
6266   }
6267 
6268   if (M.size() == NumElts*2)
6269     WhichResult = 0;
6270 
6271   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6272   if (VT.is64BitVector() && EltSz == 32)
6273     return false;
6274 
6275   return true;
6276 }
6277 
6278 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6279 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6280 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6281 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6282   unsigned EltSz = VT.getScalarSizeInBits();
6283   if (EltSz == 64)
6284     return false;
6285 
6286   unsigned NumElts = VT.getVectorNumElements();
6287   if (M.size() != NumElts && M.size() != NumElts*2)
6288     return false;
6289 
6290   for (unsigned i = 0; i < M.size(); i += NumElts) {
6291     WhichResult = SelectPairHalf(NumElts, M, i);
6292     unsigned Idx = WhichResult * NumElts / 2;
6293     for (unsigned j = 0; j < NumElts; j += 2) {
6294       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6295           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6296         return false;
6297       Idx += 1;
6298     }
6299   }
6300 
6301   if (M.size() == NumElts*2)
6302     WhichResult = 0;
6303 
6304   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6305   if (VT.is64BitVector() && EltSz == 32)
6306     return false;
6307 
6308   return true;
6309 }
6310 
6311 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6312 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6313 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6314                                            unsigned &WhichResult,
6315                                            bool &isV_UNDEF) {
6316   isV_UNDEF = false;
6317   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6318     return ARMISD::VTRN;
6319   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6320     return ARMISD::VUZP;
6321   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6322     return ARMISD::VZIP;
6323 
6324   isV_UNDEF = true;
6325   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6326     return ARMISD::VTRN;
6327   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6328     return ARMISD::VUZP;
6329   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6330     return ARMISD::VZIP;
6331 
6332   return 0;
6333 }
6334 
6335 /// \return true if this is a reverse operation on an vector.
6336 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6337   unsigned NumElts = VT.getVectorNumElements();
6338   // Make sure the mask has the right size.
6339   if (NumElts != M.size())
6340       return false;
6341 
6342   // Look for <15, ..., 3, -1, 1, 0>.
6343   for (unsigned i = 0; i != NumElts; ++i)
6344     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6345       return false;
6346 
6347   return true;
6348 }
6349 
6350 // If N is an integer constant that can be moved into a register in one
6351 // instruction, return an SDValue of such a constant (will become a MOV
6352 // instruction).  Otherwise return null.
6353 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6354                                      const ARMSubtarget *ST, const SDLoc &dl) {
6355   uint64_t Val;
6356   if (!isa<ConstantSDNode>(N))
6357     return SDValue();
6358   Val = cast<ConstantSDNode>(N)->getZExtValue();
6359 
6360   if (ST->isThumb1Only()) {
6361     if (Val <= 255 || ~Val <= 255)
6362       return DAG.getConstant(Val, dl, MVT::i32);
6363   } else {
6364     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6365       return DAG.getConstant(Val, dl, MVT::i32);
6366   }
6367   return SDValue();
6368 }
6369 
6370 // If this is a case we can't handle, return null and let the default
6371 // expansion code take care of it.
6372 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6373                                              const ARMSubtarget *ST) const {
6374   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6375   SDLoc dl(Op);
6376   EVT VT = Op.getValueType();
6377 
6378   APInt SplatBits, SplatUndef;
6379   unsigned SplatBitSize;
6380   bool HasAnyUndefs;
6381   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6382     if (SplatUndef.isAllOnesValue())
6383       return DAG.getUNDEF(VT);
6384 
6385     if (SplatBitSize <= 64) {
6386       // Check if an immediate VMOV works.
6387       EVT VmovVT;
6388       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6389                                       SplatUndef.getZExtValue(), SplatBitSize,
6390                                       DAG, dl, VmovVT, VT.is128BitVector(),
6391                                       VMOVModImm);
6392       if (Val.getNode()) {
6393         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6394         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6395       }
6396 
6397       // Try an immediate VMVN.
6398       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6399       Val = isNEONModifiedImm(NegatedImm,
6400                                       SplatUndef.getZExtValue(), SplatBitSize,
6401                                       DAG, dl, VmovVT, VT.is128BitVector(),
6402                                       VMVNModImm);
6403       if (Val.getNode()) {
6404         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6405         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6406       }
6407 
6408       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6409       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6410         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6411         if (ImmVal != -1) {
6412           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6413           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6414         }
6415       }
6416     }
6417   }
6418 
6419   // Scan through the operands to see if only one value is used.
6420   //
6421   // As an optimisation, even if more than one value is used it may be more
6422   // profitable to splat with one value then change some lanes.
6423   //
6424   // Heuristically we decide to do this if the vector has a "dominant" value,
6425   // defined as splatted to more than half of the lanes.
6426   unsigned NumElts = VT.getVectorNumElements();
6427   bool isOnlyLowElement = true;
6428   bool usesOnlyOneValue = true;
6429   bool hasDominantValue = false;
6430   bool isConstant = true;
6431 
6432   // Map of the number of times a particular SDValue appears in the
6433   // element list.
6434   DenseMap<SDValue, unsigned> ValueCounts;
6435   SDValue Value;
6436   for (unsigned i = 0; i < NumElts; ++i) {
6437     SDValue V = Op.getOperand(i);
6438     if (V.isUndef())
6439       continue;
6440     if (i > 0)
6441       isOnlyLowElement = false;
6442     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6443       isConstant = false;
6444 
6445     ValueCounts.insert(std::make_pair(V, 0));
6446     unsigned &Count = ValueCounts[V];
6447 
6448     // Is this value dominant? (takes up more than half of the lanes)
6449     if (++Count > (NumElts / 2)) {
6450       hasDominantValue = true;
6451       Value = V;
6452     }
6453   }
6454   if (ValueCounts.size() != 1)
6455     usesOnlyOneValue = false;
6456   if (!Value.getNode() && !ValueCounts.empty())
6457     Value = ValueCounts.begin()->first;
6458 
6459   if (ValueCounts.empty())
6460     return DAG.getUNDEF(VT);
6461 
6462   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6463   // Keep going if we are hitting this case.
6464   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6465     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6466 
6467   unsigned EltSize = VT.getScalarSizeInBits();
6468 
6469   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6470   // i32 and try again.
6471   if (hasDominantValue && EltSize <= 32) {
6472     if (!isConstant) {
6473       SDValue N;
6474 
6475       // If we are VDUPing a value that comes directly from a vector, that will
6476       // cause an unnecessary move to and from a GPR, where instead we could
6477       // just use VDUPLANE. We can only do this if the lane being extracted
6478       // is at a constant index, as the VDUP from lane instructions only have
6479       // constant-index forms.
6480       ConstantSDNode *constIndex;
6481       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6482           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6483         // We need to create a new undef vector to use for the VDUPLANE if the
6484         // size of the vector from which we get the value is different than the
6485         // size of the vector that we need to create. We will insert the element
6486         // such that the register coalescer will remove unnecessary copies.
6487         if (VT != Value->getOperand(0).getValueType()) {
6488           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6489                              VT.getVectorNumElements();
6490           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6491                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6492                         Value, DAG.getConstant(index, dl, MVT::i32)),
6493                            DAG.getConstant(index, dl, MVT::i32));
6494         } else
6495           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6496                         Value->getOperand(0), Value->getOperand(1));
6497       } else
6498         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6499 
6500       if (!usesOnlyOneValue) {
6501         // The dominant value was splatted as 'N', but we now have to insert
6502         // all differing elements.
6503         for (unsigned I = 0; I < NumElts; ++I) {
6504           if (Op.getOperand(I) == Value)
6505             continue;
6506           SmallVector<SDValue, 3> Ops;
6507           Ops.push_back(N);
6508           Ops.push_back(Op.getOperand(I));
6509           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6510           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6511         }
6512       }
6513       return N;
6514     }
6515     if (VT.getVectorElementType().isFloatingPoint()) {
6516       SmallVector<SDValue, 8> Ops;
6517       for (unsigned i = 0; i < NumElts; ++i)
6518         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6519                                   Op.getOperand(i)));
6520       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6521       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6522       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6523       if (Val.getNode())
6524         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6525     }
6526     if (usesOnlyOneValue) {
6527       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6528       if (isConstant && Val.getNode())
6529         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6530     }
6531   }
6532 
6533   // If all elements are constants and the case above didn't get hit, fall back
6534   // to the default expansion, which will generate a load from the constant
6535   // pool.
6536   if (isConstant)
6537     return SDValue();
6538 
6539   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6540   if (NumElts >= 4) {
6541     SDValue shuffle = ReconstructShuffle(Op, DAG);
6542     if (shuffle != SDValue())
6543       return shuffle;
6544   }
6545 
6546   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6547     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6548     // into two 64-bit vectors; we might discover a better way to lower it.
6549     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6550     EVT ExtVT = VT.getVectorElementType();
6551     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6552     SDValue Lower =
6553         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6554     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6555       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6556     SDValue Upper = DAG.getBuildVector(
6557         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6558     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6559       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6560     if (Lower && Upper)
6561       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6562   }
6563 
6564   // Vectors with 32- or 64-bit elements can be built by directly assigning
6565   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6566   // will be legalized.
6567   if (EltSize >= 32) {
6568     // Do the expansion with floating-point types, since that is what the VFP
6569     // registers are defined to use, and since i64 is not legal.
6570     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6571     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6572     SmallVector<SDValue, 8> Ops;
6573     for (unsigned i = 0; i < NumElts; ++i)
6574       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6575     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6576     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6577   }
6578 
6579   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6580   // know the default expansion would otherwise fall back on something even
6581   // worse. For a vector with one or two non-undef values, that's
6582   // scalar_to_vector for the elements followed by a shuffle (provided the
6583   // shuffle is valid for the target) and materialization element by element
6584   // on the stack followed by a load for everything else.
6585   if (!isConstant && !usesOnlyOneValue) {
6586     SDValue Vec = DAG.getUNDEF(VT);
6587     for (unsigned i = 0 ; i < NumElts; ++i) {
6588       SDValue V = Op.getOperand(i);
6589       if (V.isUndef())
6590         continue;
6591       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6592       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6593     }
6594     return Vec;
6595   }
6596 
6597   return SDValue();
6598 }
6599 
6600 // Gather data to see if the operation can be modelled as a
6601 // shuffle in combination with VEXTs.
6602 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6603                                               SelectionDAG &DAG) const {
6604   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6605   SDLoc dl(Op);
6606   EVT VT = Op.getValueType();
6607   unsigned NumElts = VT.getVectorNumElements();
6608 
6609   struct ShuffleSourceInfo {
6610     SDValue Vec;
6611     unsigned MinElt = std::numeric_limits<unsigned>::max();
6612     unsigned MaxElt = 0;
6613 
6614     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6615     // be compatible with the shuffle we intend to construct. As a result
6616     // ShuffleVec will be some sliding window into the original Vec.
6617     SDValue ShuffleVec;
6618 
6619     // Code should guarantee that element i in Vec starts at element "WindowBase
6620     // + i * WindowScale in ShuffleVec".
6621     int WindowBase = 0;
6622     int WindowScale = 1;
6623 
6624     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6625 
6626     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6627   };
6628 
6629   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6630   // node.
6631   SmallVector<ShuffleSourceInfo, 2> Sources;
6632   for (unsigned i = 0; i < NumElts; ++i) {
6633     SDValue V = Op.getOperand(i);
6634     if (V.isUndef())
6635       continue;
6636     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6637       // A shuffle can only come from building a vector from various
6638       // elements of other vectors.
6639       return SDValue();
6640     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6641       // Furthermore, shuffles require a constant mask, whereas extractelts
6642       // accept variable indices.
6643       return SDValue();
6644     }
6645 
6646     // Add this element source to the list if it's not already there.
6647     SDValue SourceVec = V.getOperand(0);
6648     auto Source = llvm::find(Sources, SourceVec);
6649     if (Source == Sources.end())
6650       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6651 
6652     // Update the minimum and maximum lane number seen.
6653     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6654     Source->MinElt = std::min(Source->MinElt, EltNo);
6655     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6656   }
6657 
6658   // Currently only do something sane when at most two source vectors
6659   // are involved.
6660   if (Sources.size() > 2)
6661     return SDValue();
6662 
6663   // Find out the smallest element size among result and two sources, and use
6664   // it as element size to build the shuffle_vector.
6665   EVT SmallestEltTy = VT.getVectorElementType();
6666   for (auto &Source : Sources) {
6667     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6668     if (SrcEltTy.bitsLT(SmallestEltTy))
6669       SmallestEltTy = SrcEltTy;
6670   }
6671   unsigned ResMultiplier =
6672       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6673   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6674   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6675 
6676   // If the source vector is too wide or too narrow, we may nevertheless be able
6677   // to construct a compatible shuffle either by concatenating it with UNDEF or
6678   // extracting a suitable range of elements.
6679   for (auto &Src : Sources) {
6680     EVT SrcVT = Src.ShuffleVec.getValueType();
6681 
6682     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6683       continue;
6684 
6685     // This stage of the search produces a source with the same element type as
6686     // the original, but with a total width matching the BUILD_VECTOR output.
6687     EVT EltVT = SrcVT.getVectorElementType();
6688     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6689     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6690 
6691     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6692       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6693         return SDValue();
6694       // We can pad out the smaller vector for free, so if it's part of a
6695       // shuffle...
6696       Src.ShuffleVec =
6697           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6698                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6699       continue;
6700     }
6701 
6702     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6703       return SDValue();
6704 
6705     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6706       // Span too large for a VEXT to cope
6707       return SDValue();
6708     }
6709 
6710     if (Src.MinElt >= NumSrcElts) {
6711       // The extraction can just take the second half
6712       Src.ShuffleVec =
6713           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6714                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6715       Src.WindowBase = -NumSrcElts;
6716     } else if (Src.MaxElt < NumSrcElts) {
6717       // The extraction can just take the first half
6718       Src.ShuffleVec =
6719           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6720                       DAG.getConstant(0, dl, MVT::i32));
6721     } else {
6722       // An actual VEXT is needed
6723       SDValue VEXTSrc1 =
6724           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6725                       DAG.getConstant(0, dl, MVT::i32));
6726       SDValue VEXTSrc2 =
6727           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6728                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6729 
6730       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6731                                    VEXTSrc2,
6732                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6733       Src.WindowBase = -Src.MinElt;
6734     }
6735   }
6736 
6737   // Another possible incompatibility occurs from the vector element types. We
6738   // can fix this by bitcasting the source vectors to the same type we intend
6739   // for the shuffle.
6740   for (auto &Src : Sources) {
6741     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6742     if (SrcEltTy == SmallestEltTy)
6743       continue;
6744     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6745     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6746     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6747     Src.WindowBase *= Src.WindowScale;
6748   }
6749 
6750   // Final sanity check before we try to actually produce a shuffle.
6751   LLVM_DEBUG(for (auto Src
6752                   : Sources)
6753                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6754 
6755   // The stars all align, our next step is to produce the mask for the shuffle.
6756   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6757   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6758   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6759     SDValue Entry = Op.getOperand(i);
6760     if (Entry.isUndef())
6761       continue;
6762 
6763     auto Src = llvm::find(Sources, Entry.getOperand(0));
6764     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6765 
6766     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6767     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6768     // segment.
6769     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6770     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6771                                VT.getScalarSizeInBits());
6772     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6773 
6774     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6775     // starting at the appropriate offset.
6776     int *LaneMask = &Mask[i * ResMultiplier];
6777 
6778     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6779     ExtractBase += NumElts * (Src - Sources.begin());
6780     for (int j = 0; j < LanesDefined; ++j)
6781       LaneMask[j] = ExtractBase + j;
6782   }
6783 
6784   // Final check before we try to produce nonsense...
6785   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6786     return SDValue();
6787 
6788   // We can't handle more than two sources. This should have already
6789   // been checked before this point.
6790   assert(Sources.size() <= 2 && "Too many sources!");
6791 
6792   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6793   for (unsigned i = 0; i < Sources.size(); ++i)
6794     ShuffleOps[i] = Sources[i].ShuffleVec;
6795 
6796   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6797                                          ShuffleOps[1], Mask);
6798   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6799 }
6800 
6801 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6802 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6803 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6804 /// are assumed to be legal.
6805 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
6806   if (VT.getVectorNumElements() == 4 &&
6807       (VT.is128BitVector() || VT.is64BitVector())) {
6808     unsigned PFIndexes[4];
6809     for (unsigned i = 0; i != 4; ++i) {
6810       if (M[i] < 0)
6811         PFIndexes[i] = 8;
6812       else
6813         PFIndexes[i] = M[i];
6814     }
6815 
6816     // Compute the index in the perfect shuffle table.
6817     unsigned PFTableIndex =
6818       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6819     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6820     unsigned Cost = (PFEntry >> 30);
6821 
6822     if (Cost <= 4)
6823       return true;
6824   }
6825 
6826   bool ReverseVEXT, isV_UNDEF;
6827   unsigned Imm, WhichResult;
6828 
6829   unsigned EltSize = VT.getScalarSizeInBits();
6830   return (EltSize >= 32 ||
6831           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6832           isVREVMask(M, VT, 64) ||
6833           isVREVMask(M, VT, 32) ||
6834           isVREVMask(M, VT, 16) ||
6835           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6836           isVTBLMask(M, VT) ||
6837           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6838           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6839 }
6840 
6841 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6842 /// the specified operations to build the shuffle.
6843 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6844                                       SDValue RHS, SelectionDAG &DAG,
6845                                       const SDLoc &dl) {
6846   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6847   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6848   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6849 
6850   enum {
6851     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6852     OP_VREV,
6853     OP_VDUP0,
6854     OP_VDUP1,
6855     OP_VDUP2,
6856     OP_VDUP3,
6857     OP_VEXT1,
6858     OP_VEXT2,
6859     OP_VEXT3,
6860     OP_VUZPL, // VUZP, left result
6861     OP_VUZPR, // VUZP, right result
6862     OP_VZIPL, // VZIP, left result
6863     OP_VZIPR, // VZIP, right result
6864     OP_VTRNL, // VTRN, left result
6865     OP_VTRNR  // VTRN, right result
6866   };
6867 
6868   if (OpNum == OP_COPY) {
6869     if (LHSID == (1*9+2)*9+3) return LHS;
6870     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6871     return RHS;
6872   }
6873 
6874   SDValue OpLHS, OpRHS;
6875   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6876   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6877   EVT VT = OpLHS.getValueType();
6878 
6879   switch (OpNum) {
6880   default: llvm_unreachable("Unknown shuffle opcode!");
6881   case OP_VREV:
6882     // VREV divides the vector in half and swaps within the half.
6883     if (VT.getVectorElementType() == MVT::i32 ||
6884         VT.getVectorElementType() == MVT::f32)
6885       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6886     // vrev <4 x i16> -> VREV32
6887     if (VT.getVectorElementType() == MVT::i16)
6888       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6889     // vrev <4 x i8> -> VREV16
6890     assert(VT.getVectorElementType() == MVT::i8);
6891     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6892   case OP_VDUP0:
6893   case OP_VDUP1:
6894   case OP_VDUP2:
6895   case OP_VDUP3:
6896     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6897                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6898   case OP_VEXT1:
6899   case OP_VEXT2:
6900   case OP_VEXT3:
6901     return DAG.getNode(ARMISD::VEXT, dl, VT,
6902                        OpLHS, OpRHS,
6903                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6904   case OP_VUZPL:
6905   case OP_VUZPR:
6906     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6907                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6908   case OP_VZIPL:
6909   case OP_VZIPR:
6910     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6911                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6912   case OP_VTRNL:
6913   case OP_VTRNR:
6914     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6915                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6916   }
6917 }
6918 
6919 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6920                                        ArrayRef<int> ShuffleMask,
6921                                        SelectionDAG &DAG) {
6922   // Check to see if we can use the VTBL instruction.
6923   SDValue V1 = Op.getOperand(0);
6924   SDValue V2 = Op.getOperand(1);
6925   SDLoc DL(Op);
6926 
6927   SmallVector<SDValue, 8> VTBLMask;
6928   for (ArrayRef<int>::iterator
6929          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6930     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6931 
6932   if (V2.getNode()->isUndef())
6933     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6934                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6935 
6936   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6937                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6938 }
6939 
6940 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6941                                                       SelectionDAG &DAG) {
6942   SDLoc DL(Op);
6943   SDValue OpLHS = Op.getOperand(0);
6944   EVT VT = OpLHS.getValueType();
6945 
6946   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6947          "Expect an v8i16/v16i8 type");
6948   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6949   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6950   // extract the first 8 bytes into the top double word and the last 8 bytes
6951   // into the bottom double word. The v8i16 case is similar.
6952   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6953   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6954                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6955 }
6956 
6957 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6958   SDValue V1 = Op.getOperand(0);
6959   SDValue V2 = Op.getOperand(1);
6960   SDLoc dl(Op);
6961   EVT VT = Op.getValueType();
6962   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6963 
6964   // Convert shuffles that are directly supported on NEON to target-specific
6965   // DAG nodes, instead of keeping them as shuffles and matching them again
6966   // during code selection.  This is more efficient and avoids the possibility
6967   // of inconsistencies between legalization and selection.
6968   // FIXME: floating-point vectors should be canonicalized to integer vectors
6969   // of the same time so that they get CSEd properly.
6970   ArrayRef<int> ShuffleMask = SVN->getMask();
6971 
6972   unsigned EltSize = VT.getScalarSizeInBits();
6973   if (EltSize <= 32) {
6974     if (SVN->isSplat()) {
6975       int Lane = SVN->getSplatIndex();
6976       // If this is undef splat, generate it via "just" vdup, if possible.
6977       if (Lane == -1) Lane = 0;
6978 
6979       // Test if V1 is a SCALAR_TO_VECTOR.
6980       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6981         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6982       }
6983       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6984       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6985       // reaches it).
6986       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6987           !isa<ConstantSDNode>(V1.getOperand(0))) {
6988         bool IsScalarToVector = true;
6989         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6990           if (!V1.getOperand(i).isUndef()) {
6991             IsScalarToVector = false;
6992             break;
6993           }
6994         if (IsScalarToVector)
6995           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6996       }
6997       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6998                          DAG.getConstant(Lane, dl, MVT::i32));
6999     }
7000 
7001     bool ReverseVEXT;
7002     unsigned Imm;
7003     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7004       if (ReverseVEXT)
7005         std::swap(V1, V2);
7006       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7007                          DAG.getConstant(Imm, dl, MVT::i32));
7008     }
7009 
7010     if (isVREVMask(ShuffleMask, VT, 64))
7011       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7012     if (isVREVMask(ShuffleMask, VT, 32))
7013       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7014     if (isVREVMask(ShuffleMask, VT, 16))
7015       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7016 
7017     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7018       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7019                          DAG.getConstant(Imm, dl, MVT::i32));
7020     }
7021 
7022     // Check for Neon shuffles that modify both input vectors in place.
7023     // If both results are used, i.e., if there are two shuffles with the same
7024     // source operands and with masks corresponding to both results of one of
7025     // these operations, DAG memoization will ensure that a single node is
7026     // used for both shuffles.
7027     unsigned WhichResult;
7028     bool isV_UNDEF;
7029     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7030             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7031       if (isV_UNDEF)
7032         V2 = V1;
7033       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7034           .getValue(WhichResult);
7035     }
7036 
7037     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7038     // shuffles that produce a result larger than their operands with:
7039     //   shuffle(concat(v1, undef), concat(v2, undef))
7040     // ->
7041     //   shuffle(concat(v1, v2), undef)
7042     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7043     //
7044     // This is useful in the general case, but there are special cases where
7045     // native shuffles produce larger results: the two-result ops.
7046     //
7047     // Look through the concat when lowering them:
7048     //   shuffle(concat(v1, v2), undef)
7049     // ->
7050     //   concat(VZIP(v1, v2):0, :1)
7051     //
7052     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7053       SDValue SubV1 = V1->getOperand(0);
7054       SDValue SubV2 = V1->getOperand(1);
7055       EVT SubVT = SubV1.getValueType();
7056 
7057       // We expect these to have been canonicalized to -1.
7058       assert(llvm::all_of(ShuffleMask, [&](int i) {
7059         return i < (int)VT.getVectorNumElements();
7060       }) && "Unexpected shuffle index into UNDEF operand!");
7061 
7062       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7063               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7064         if (isV_UNDEF)
7065           SubV2 = SubV1;
7066         assert((WhichResult == 0) &&
7067                "In-place shuffle of concat can only have one result!");
7068         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7069                                   SubV1, SubV2);
7070         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7071                            Res.getValue(1));
7072       }
7073     }
7074   }
7075 
7076   // If the shuffle is not directly supported and it has 4 elements, use
7077   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7078   unsigned NumElts = VT.getVectorNumElements();
7079   if (NumElts == 4) {
7080     unsigned PFIndexes[4];
7081     for (unsigned i = 0; i != 4; ++i) {
7082       if (ShuffleMask[i] < 0)
7083         PFIndexes[i] = 8;
7084       else
7085         PFIndexes[i] = ShuffleMask[i];
7086     }
7087 
7088     // Compute the index in the perfect shuffle table.
7089     unsigned PFTableIndex =
7090       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7091     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7092     unsigned Cost = (PFEntry >> 30);
7093 
7094     if (Cost <= 4)
7095       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7096   }
7097 
7098   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7099   if (EltSize >= 32) {
7100     // Do the expansion with floating-point types, since that is what the VFP
7101     // registers are defined to use, and since i64 is not legal.
7102     EVT EltVT = EVT::getFloatingPointVT(EltSize);
7103     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7104     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7105     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7106     SmallVector<SDValue, 8> Ops;
7107     for (unsigned i = 0; i < NumElts; ++i) {
7108       if (ShuffleMask[i] < 0)
7109         Ops.push_back(DAG.getUNDEF(EltVT));
7110       else
7111         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7112                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
7113                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7114                                                   dl, MVT::i32)));
7115     }
7116     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7117     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7118   }
7119 
7120   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7121     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7122 
7123   if (VT == MVT::v8i8)
7124     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7125       return NewOp;
7126 
7127   return SDValue();
7128 }
7129 
7130 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7131   // INSERT_VECTOR_ELT is legal only for immediate indexes.
7132   SDValue Lane = Op.getOperand(2);
7133   if (!isa<ConstantSDNode>(Lane))
7134     return SDValue();
7135 
7136   return Op;
7137 }
7138 
7139 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7140   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7141   SDValue Lane = Op.getOperand(1);
7142   if (!isa<ConstantSDNode>(Lane))
7143     return SDValue();
7144 
7145   SDValue Vec = Op.getOperand(0);
7146   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7147     SDLoc dl(Op);
7148     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7149   }
7150 
7151   return Op;
7152 }
7153 
7154 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7155   // The only time a CONCAT_VECTORS operation can have legal types is when
7156   // two 64-bit vectors are concatenated to a 128-bit vector.
7157   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
7158          "unexpected CONCAT_VECTORS");
7159   SDLoc dl(Op);
7160   SDValue Val = DAG.getUNDEF(MVT::v2f64);
7161   SDValue Op0 = Op.getOperand(0);
7162   SDValue Op1 = Op.getOperand(1);
7163   if (!Op0.isUndef())
7164     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7165                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
7166                       DAG.getIntPtrConstant(0, dl));
7167   if (!Op1.isUndef())
7168     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7169                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
7170                       DAG.getIntPtrConstant(1, dl));
7171   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
7172 }
7173 
7174 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
7175 /// element has been zero/sign-extended, depending on the isSigned parameter,
7176 /// from an integer type half its size.
7177 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
7178                                    bool isSigned) {
7179   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
7180   EVT VT = N->getValueType(0);
7181   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
7182     SDNode *BVN = N->getOperand(0).getNode();
7183     if (BVN->getValueType(0) != MVT::v4i32 ||
7184         BVN->getOpcode() != ISD::BUILD_VECTOR)
7185       return false;
7186     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7187     unsigned HiElt = 1 - LoElt;
7188     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
7189     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
7190     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
7191     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
7192     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
7193       return false;
7194     if (isSigned) {
7195       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
7196           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
7197         return true;
7198     } else {
7199       if (Hi0->isNullValue() && Hi1->isNullValue())
7200         return true;
7201     }
7202     return false;
7203   }
7204 
7205   if (N->getOpcode() != ISD::BUILD_VECTOR)
7206     return false;
7207 
7208   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
7209     SDNode *Elt = N->getOperand(i).getNode();
7210     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
7211       unsigned EltSize = VT.getScalarSizeInBits();
7212       unsigned HalfSize = EltSize / 2;
7213       if (isSigned) {
7214         if (!isIntN(HalfSize, C->getSExtValue()))
7215           return false;
7216       } else {
7217         if (!isUIntN(HalfSize, C->getZExtValue()))
7218           return false;
7219       }
7220       continue;
7221     }
7222     return false;
7223   }
7224 
7225   return true;
7226 }
7227 
7228 /// isSignExtended - Check if a node is a vector value that is sign-extended
7229 /// or a constant BUILD_VECTOR with sign-extended elements.
7230 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7231   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7232     return true;
7233   if (isExtendedBUILD_VECTOR(N, DAG, true))
7234     return true;
7235   return false;
7236 }
7237 
7238 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7239 /// or a constant BUILD_VECTOR with zero-extended elements.
7240 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7241   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7242     return true;
7243   if (isExtendedBUILD_VECTOR(N, DAG, false))
7244     return true;
7245   return false;
7246 }
7247 
7248 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7249   if (OrigVT.getSizeInBits() >= 64)
7250     return OrigVT;
7251 
7252   assert(OrigVT.isSimple() && "Expecting a simple value type");
7253 
7254   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7255   switch (OrigSimpleTy) {
7256   default: llvm_unreachable("Unexpected Vector Type");
7257   case MVT::v2i8:
7258   case MVT::v2i16:
7259      return MVT::v2i32;
7260   case MVT::v4i8:
7261     return  MVT::v4i16;
7262   }
7263 }
7264 
7265 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7266 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7267 /// We insert the required extension here to get the vector to fill a D register.
7268 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7269                                             const EVT &OrigTy,
7270                                             const EVT &ExtTy,
7271                                             unsigned ExtOpcode) {
7272   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7273   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7274   // 64-bits we need to insert a new extension so that it will be 64-bits.
7275   assert(ExtTy.is128BitVector() && "Unexpected extension size");
7276   if (OrigTy.getSizeInBits() >= 64)
7277     return N;
7278 
7279   // Must extend size to at least 64 bits to be used as an operand for VMULL.
7280   EVT NewVT = getExtensionTo64Bits(OrigTy);
7281 
7282   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7283 }
7284 
7285 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7286 /// does not do any sign/zero extension. If the original vector is less
7287 /// than 64 bits, an appropriate extension will be added after the load to
7288 /// reach a total size of 64 bits. We have to add the extension separately
7289 /// because ARM does not have a sign/zero extending load for vectors.
7290 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7291   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7292 
7293   // The load already has the right type.
7294   if (ExtendedTy == LD->getMemoryVT())
7295     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7296                        LD->getBasePtr(), LD->getPointerInfo(),
7297                        LD->getAlignment(), LD->getMemOperand()->getFlags());
7298 
7299   // We need to create a zextload/sextload. We cannot just create a load
7300   // followed by a zext/zext node because LowerMUL is also run during normal
7301   // operation legalization where we can't create illegal types.
7302   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7303                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7304                         LD->getMemoryVT(), LD->getAlignment(),
7305                         LD->getMemOperand()->getFlags());
7306 }
7307 
7308 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7309 /// extending load, or BUILD_VECTOR with extended elements, return the
7310 /// unextended value. The unextended vector should be 64 bits so that it can
7311 /// be used as an operand to a VMULL instruction. If the original vector size
7312 /// before extension is less than 64 bits we add a an extension to resize
7313 /// the vector to 64 bits.
7314 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7315   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7316     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7317                                         N->getOperand(0)->getValueType(0),
7318                                         N->getValueType(0),
7319                                         N->getOpcode());
7320 
7321   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7322     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7323            "Expected extending load");
7324 
7325     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7326     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7327     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7328     SDValue extLoad =
7329         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7330     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7331 
7332     return newLoad;
7333   }
7334 
7335   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7336   // have been legalized as a BITCAST from v4i32.
7337   if (N->getOpcode() == ISD::BITCAST) {
7338     SDNode *BVN = N->getOperand(0).getNode();
7339     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7340            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7341     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7342     return DAG.getBuildVector(
7343         MVT::v2i32, SDLoc(N),
7344         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7345   }
7346   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7347   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7348   EVT VT = N->getValueType(0);
7349   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7350   unsigned NumElts = VT.getVectorNumElements();
7351   MVT TruncVT = MVT::getIntegerVT(EltSize);
7352   SmallVector<SDValue, 8> Ops;
7353   SDLoc dl(N);
7354   for (unsigned i = 0; i != NumElts; ++i) {
7355     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7356     const APInt &CInt = C->getAPIntValue();
7357     // Element types smaller than 32 bits are not legal, so use i32 elements.
7358     // The values are implicitly truncated so sext vs. zext doesn't matter.
7359     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7360   }
7361   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7362 }
7363 
7364 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7365   unsigned Opcode = N->getOpcode();
7366   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7367     SDNode *N0 = N->getOperand(0).getNode();
7368     SDNode *N1 = N->getOperand(1).getNode();
7369     return N0->hasOneUse() && N1->hasOneUse() &&
7370       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7371   }
7372   return false;
7373 }
7374 
7375 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7376   unsigned Opcode = N->getOpcode();
7377   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7378     SDNode *N0 = N->getOperand(0).getNode();
7379     SDNode *N1 = N->getOperand(1).getNode();
7380     return N0->hasOneUse() && N1->hasOneUse() &&
7381       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7382   }
7383   return false;
7384 }
7385 
7386 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7387   // Multiplications are only custom-lowered for 128-bit vectors so that
7388   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7389   EVT VT = Op.getValueType();
7390   assert(VT.is128BitVector() && VT.isInteger() &&
7391          "unexpected type for custom-lowering ISD::MUL");
7392   SDNode *N0 = Op.getOperand(0).getNode();
7393   SDNode *N1 = Op.getOperand(1).getNode();
7394   unsigned NewOpc = 0;
7395   bool isMLA = false;
7396   bool isN0SExt = isSignExtended(N0, DAG);
7397   bool isN1SExt = isSignExtended(N1, DAG);
7398   if (isN0SExt && isN1SExt)
7399     NewOpc = ARMISD::VMULLs;
7400   else {
7401     bool isN0ZExt = isZeroExtended(N0, DAG);
7402     bool isN1ZExt = isZeroExtended(N1, DAG);
7403     if (isN0ZExt && isN1ZExt)
7404       NewOpc = ARMISD::VMULLu;
7405     else if (isN1SExt || isN1ZExt) {
7406       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7407       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7408       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7409         NewOpc = ARMISD::VMULLs;
7410         isMLA = true;
7411       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7412         NewOpc = ARMISD::VMULLu;
7413         isMLA = true;
7414       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7415         std::swap(N0, N1);
7416         NewOpc = ARMISD::VMULLu;
7417         isMLA = true;
7418       }
7419     }
7420 
7421     if (!NewOpc) {
7422       if (VT == MVT::v2i64)
7423         // Fall through to expand this.  It is not legal.
7424         return SDValue();
7425       else
7426         // Other vector multiplications are legal.
7427         return Op;
7428     }
7429   }
7430 
7431   // Legalize to a VMULL instruction.
7432   SDLoc DL(Op);
7433   SDValue Op0;
7434   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7435   if (!isMLA) {
7436     Op0 = SkipExtensionForVMULL(N0, DAG);
7437     assert(Op0.getValueType().is64BitVector() &&
7438            Op1.getValueType().is64BitVector() &&
7439            "unexpected types for extended operands to VMULL");
7440     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7441   }
7442 
7443   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7444   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7445   //   vmull q0, d4, d6
7446   //   vmlal q0, d5, d6
7447   // is faster than
7448   //   vaddl q0, d4, d5
7449   //   vmovl q1, d6
7450   //   vmul  q0, q0, q1
7451   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7452   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7453   EVT Op1VT = Op1.getValueType();
7454   return DAG.getNode(N0->getOpcode(), DL, VT,
7455                      DAG.getNode(NewOpc, DL, VT,
7456                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7457                      DAG.getNode(NewOpc, DL, VT,
7458                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7459 }
7460 
7461 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7462                               SelectionDAG &DAG) {
7463   // TODO: Should this propagate fast-math-flags?
7464 
7465   // Convert to float
7466   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7467   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7468   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7469   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7470   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7471   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7472   // Get reciprocal estimate.
7473   // float4 recip = vrecpeq_f32(yf);
7474   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7475                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7476                    Y);
7477   // Because char has a smaller range than uchar, we can actually get away
7478   // without any newton steps.  This requires that we use a weird bias
7479   // of 0xb000, however (again, this has been exhaustively tested).
7480   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7481   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7482   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7483   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7484   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7485   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7486   // Convert back to short.
7487   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7488   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7489   return X;
7490 }
7491 
7492 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7493                                SelectionDAG &DAG) {
7494   // TODO: Should this propagate fast-math-flags?
7495 
7496   SDValue N2;
7497   // Convert to float.
7498   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7499   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7500   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7501   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7502   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7503   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7504 
7505   // Use reciprocal estimate and one refinement step.
7506   // float4 recip = vrecpeq_f32(yf);
7507   // recip *= vrecpsq_f32(yf, recip);
7508   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7509                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7510                    N1);
7511   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7512                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7513                    N1, N2);
7514   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7515   // Because short has a smaller range than ushort, we can actually get away
7516   // with only a single newton step.  This requires that we use a weird bias
7517   // of 89, however (again, this has been exhaustively tested).
7518   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7519   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7520   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7521   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7522   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7523   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7524   // Convert back to integer and return.
7525   // return vmovn_s32(vcvt_s32_f32(result));
7526   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7527   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7528   return N0;
7529 }
7530 
7531 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7532   EVT VT = Op.getValueType();
7533   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7534          "unexpected type for custom-lowering ISD::SDIV");
7535 
7536   SDLoc dl(Op);
7537   SDValue N0 = Op.getOperand(0);
7538   SDValue N1 = Op.getOperand(1);
7539   SDValue N2, N3;
7540 
7541   if (VT == MVT::v8i8) {
7542     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7543     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7544 
7545     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7546                      DAG.getIntPtrConstant(4, dl));
7547     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7548                      DAG.getIntPtrConstant(4, dl));
7549     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7550                      DAG.getIntPtrConstant(0, dl));
7551     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7552                      DAG.getIntPtrConstant(0, dl));
7553 
7554     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7555     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7556 
7557     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7558     N0 = LowerCONCAT_VECTORS(N0, DAG);
7559 
7560     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7561     return N0;
7562   }
7563   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7564 }
7565 
7566 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7567   // TODO: Should this propagate fast-math-flags?
7568   EVT VT = Op.getValueType();
7569   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7570          "unexpected type for custom-lowering ISD::UDIV");
7571 
7572   SDLoc dl(Op);
7573   SDValue N0 = Op.getOperand(0);
7574   SDValue N1 = Op.getOperand(1);
7575   SDValue N2, N3;
7576 
7577   if (VT == MVT::v8i8) {
7578     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7579     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7580 
7581     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7582                      DAG.getIntPtrConstant(4, dl));
7583     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7584                      DAG.getIntPtrConstant(4, dl));
7585     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7586                      DAG.getIntPtrConstant(0, dl));
7587     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7588                      DAG.getIntPtrConstant(0, dl));
7589 
7590     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7591     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7592 
7593     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7594     N0 = LowerCONCAT_VECTORS(N0, DAG);
7595 
7596     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7597                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7598                                      MVT::i32),
7599                      N0);
7600     return N0;
7601   }
7602 
7603   // v4i16 sdiv ... Convert to float.
7604   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7605   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7606   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7607   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7608   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7609   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7610 
7611   // Use reciprocal estimate and two refinement steps.
7612   // float4 recip = vrecpeq_f32(yf);
7613   // recip *= vrecpsq_f32(yf, recip);
7614   // recip *= vrecpsq_f32(yf, recip);
7615   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7616                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7617                    BN1);
7618   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7619                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7620                    BN1, N2);
7621   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7622   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7623                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7624                    BN1, N2);
7625   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7626   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7627   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7628   // and that it will never cause us to return an answer too large).
7629   // float4 result = as_float4(as_int4(xf*recip) + 2);
7630   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7631   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7632   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7633   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7634   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7635   // Convert back to integer and return.
7636   // return vmovn_u32(vcvt_s32_f32(result));
7637   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7638   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7639   return N0;
7640 }
7641 
7642 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
7643   SDNode *N = Op.getNode();
7644   EVT VT = N->getValueType(0);
7645   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7646 
7647   SDValue Carry = Op.getOperand(2);
7648 
7649   SDLoc DL(Op);
7650 
7651   SDValue Result;
7652   if (Op.getOpcode() == ISD::ADDCARRY) {
7653     // This converts the boolean value carry into the carry flag.
7654     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7655 
7656     // Do the addition proper using the carry flag we wanted.
7657     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
7658                          Op.getOperand(1), Carry);
7659 
7660     // Now convert the carry flag into a boolean value.
7661     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7662   } else {
7663     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
7664     // have to invert the carry first.
7665     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7666                         DAG.getConstant(1, DL, MVT::i32), Carry);
7667     // This converts the boolean value carry into the carry flag.
7668     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7669 
7670     // Do the subtraction proper using the carry flag we wanted.
7671     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
7672                          Op.getOperand(1), Carry);
7673 
7674     // Now convert the carry flag into a boolean value.
7675     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7676     // But the carry returned by ARMISD::SUBE is not a borrow as expected
7677     // by ISD::SUBCARRY, so compute 1 - C.
7678     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7679                         DAG.getConstant(1, DL, MVT::i32), Carry);
7680   }
7681 
7682   // Return both values.
7683   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
7684 }
7685 
7686 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7687   assert(Subtarget->isTargetDarwin());
7688 
7689   // For iOS, we want to call an alternative entry point: __sincos_stret,
7690   // return values are passed via sret.
7691   SDLoc dl(Op);
7692   SDValue Arg = Op.getOperand(0);
7693   EVT ArgVT = Arg.getValueType();
7694   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7695   auto PtrVT = getPointerTy(DAG.getDataLayout());
7696 
7697   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7698   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7699 
7700   // Pair of floats / doubles used to pass the result.
7701   Type *RetTy = StructType::get(ArgTy, ArgTy);
7702   auto &DL = DAG.getDataLayout();
7703 
7704   ArgListTy Args;
7705   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7706   SDValue SRet;
7707   if (ShouldUseSRet) {
7708     // Create stack object for sret.
7709     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7710     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7711     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7712     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7713 
7714     ArgListEntry Entry;
7715     Entry.Node = SRet;
7716     Entry.Ty = RetTy->getPointerTo();
7717     Entry.IsSExt = false;
7718     Entry.IsZExt = false;
7719     Entry.IsSRet = true;
7720     Args.push_back(Entry);
7721     RetTy = Type::getVoidTy(*DAG.getContext());
7722   }
7723 
7724   ArgListEntry Entry;
7725   Entry.Node = Arg;
7726   Entry.Ty = ArgTy;
7727   Entry.IsSExt = false;
7728   Entry.IsZExt = false;
7729   Args.push_back(Entry);
7730 
7731   RTLIB::Libcall LC =
7732       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
7733   const char *LibcallName = getLibcallName(LC);
7734   CallingConv::ID CC = getLibcallCallingConv(LC);
7735   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7736 
7737   TargetLowering::CallLoweringInfo CLI(DAG);
7738   CLI.setDebugLoc(dl)
7739       .setChain(DAG.getEntryNode())
7740       .setCallee(CC, RetTy, Callee, std::move(Args))
7741       .setDiscardResult(ShouldUseSRet);
7742   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7743 
7744   if (!ShouldUseSRet)
7745     return CallResult.first;
7746 
7747   SDValue LoadSin =
7748       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7749 
7750   // Address of cos field.
7751   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7752                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7753   SDValue LoadCos =
7754       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7755 
7756   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7757   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7758                      LoadSin.getValue(0), LoadCos.getValue(0));
7759 }
7760 
7761 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7762                                                   bool Signed,
7763                                                   SDValue &Chain) const {
7764   EVT VT = Op.getValueType();
7765   assert((VT == MVT::i32 || VT == MVT::i64) &&
7766          "unexpected type for custom lowering DIV");
7767   SDLoc dl(Op);
7768 
7769   const auto &DL = DAG.getDataLayout();
7770   const auto &TLI = DAG.getTargetLoweringInfo();
7771 
7772   const char *Name = nullptr;
7773   if (Signed)
7774     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7775   else
7776     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7777 
7778   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7779 
7780   ARMTargetLowering::ArgListTy Args;
7781 
7782   for (auto AI : {1, 0}) {
7783     ArgListEntry Arg;
7784     Arg.Node = Op.getOperand(AI);
7785     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7786     Args.push_back(Arg);
7787   }
7788 
7789   CallLoweringInfo CLI(DAG);
7790   CLI.setDebugLoc(dl)
7791     .setChain(Chain)
7792     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7793                ES, std::move(Args));
7794 
7795   return LowerCallTo(CLI).first;
7796 }
7797 
7798 // This is a code size optimisation: return the original SDIV node to
7799 // DAGCombiner when we don't want to expand SDIV into a sequence of
7800 // instructions, and an empty node otherwise which will cause the
7801 // SDIV to be expanded in DAGCombine.
7802 SDValue
7803 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7804                                  SelectionDAG &DAG,
7805                                  SmallVectorImpl<SDNode *> &Created) const {
7806   // TODO: Support SREM
7807   if (N->getOpcode() != ISD::SDIV)
7808     return SDValue();
7809 
7810   const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
7811   const auto &MF = DAG.getMachineFunction();
7812   const bool MinSize = MF.getFunction().optForMinSize();
7813   const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
7814                                       : ST.hasDivideInARMMode();
7815 
7816   // Don't touch vector types; rewriting this may lead to scalarizing
7817   // the int divs.
7818   if (N->getOperand(0).getValueType().isVector())
7819     return SDValue();
7820 
7821   // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
7822   // hwdiv support for this to be really profitable.
7823   if (!(MinSize && HasDivide))
7824     return SDValue();
7825 
7826   // ARM mode is a bit simpler than Thumb: we can handle large power
7827   // of 2 immediates with 1 mov instruction; no further checks required,
7828   // just return the sdiv node.
7829   if (!ST.isThumb())
7830     return SDValue(N, 0);
7831 
7832   // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
7833   // and thus lose the code size benefits of a MOVS that requires only 2.
7834   // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
7835   // but as it's doing exactly this, it's not worth the trouble to get TTI.
7836   if (Divisor.sgt(128))
7837     return SDValue();
7838 
7839   return SDValue(N, 0);
7840 }
7841 
7842 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7843                                             bool Signed) const {
7844   assert(Op.getValueType() == MVT::i32 &&
7845          "unexpected type for custom lowering DIV");
7846   SDLoc dl(Op);
7847 
7848   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7849                                DAG.getEntryNode(), Op.getOperand(1));
7850 
7851   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7852 }
7853 
7854 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7855   SDLoc DL(N);
7856   SDValue Op = N->getOperand(1);
7857   if (N->getValueType(0) == MVT::i32)
7858     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7859   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7860                            DAG.getConstant(0, DL, MVT::i32));
7861   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7862                            DAG.getConstant(1, DL, MVT::i32));
7863   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7864                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7865 }
7866 
7867 void ARMTargetLowering::ExpandDIV_Windows(
7868     SDValue Op, SelectionDAG &DAG, bool Signed,
7869     SmallVectorImpl<SDValue> &Results) const {
7870   const auto &DL = DAG.getDataLayout();
7871   const auto &TLI = DAG.getTargetLoweringInfo();
7872 
7873   assert(Op.getValueType() == MVT::i64 &&
7874          "unexpected type for custom lowering DIV");
7875   SDLoc dl(Op);
7876 
7877   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7878 
7879   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7880 
7881   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7882   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7883                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7884   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7885 
7886   Results.push_back(Lower);
7887   Results.push_back(Upper);
7888 }
7889 
7890 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7891   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7892     // Acquire/Release load/store is not legal for targets without a dmb or
7893     // equivalent available.
7894     return SDValue();
7895 
7896   // Monotonic load/store is legal for all targets.
7897   return Op;
7898 }
7899 
7900 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7901                                     SmallVectorImpl<SDValue> &Results,
7902                                     SelectionDAG &DAG,
7903                                     const ARMSubtarget *Subtarget) {
7904   SDLoc DL(N);
7905   // Under Power Management extensions, the cycle-count is:
7906   //    mrc p15, #0, <Rt>, c9, c13, #0
7907   SDValue Ops[] = { N->getOperand(0), // Chain
7908                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7909                     DAG.getConstant(15, DL, MVT::i32),
7910                     DAG.getConstant(0, DL, MVT::i32),
7911                     DAG.getConstant(9, DL, MVT::i32),
7912                     DAG.getConstant(13, DL, MVT::i32),
7913                     DAG.getConstant(0, DL, MVT::i32)
7914   };
7915 
7916   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7917                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7918   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7919                                 DAG.getConstant(0, DL, MVT::i32)));
7920   Results.push_back(Cycles32.getValue(1));
7921 }
7922 
7923 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7924   SDLoc dl(V.getNode());
7925   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7926   SDValue VHi = DAG.getAnyExtOrTrunc(
7927       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7928       dl, MVT::i32);
7929   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7930   if (isBigEndian)
7931     std::swap (VLo, VHi);
7932   SDValue RegClass =
7933       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7934   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7935   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7936   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7937   return SDValue(
7938       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7939 }
7940 
7941 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7942                                        SmallVectorImpl<SDValue> & Results,
7943                                        SelectionDAG &DAG) {
7944   assert(N->getValueType(0) == MVT::i64 &&
7945          "AtomicCmpSwap on types less than 64 should be legal");
7946   SDValue Ops[] = {N->getOperand(1),
7947                    createGPRPairNode(DAG, N->getOperand(2)),
7948                    createGPRPairNode(DAG, N->getOperand(3)),
7949                    N->getOperand(0)};
7950   SDNode *CmpSwap = DAG.getMachineNode(
7951       ARM::CMP_SWAP_64, SDLoc(N),
7952       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7953 
7954   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
7955   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
7956 
7957   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7958 
7959   Results.push_back(
7960       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
7961                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7962   Results.push_back(
7963       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
7964                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7965   Results.push_back(SDValue(CmpSwap, 2));
7966 }
7967 
7968 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7969                           SelectionDAG &DAG) {
7970   const auto &TLI = DAG.getTargetLoweringInfo();
7971 
7972   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7973          "Custom lowering is MSVCRT specific!");
7974 
7975   SDLoc dl(Op);
7976   SDValue Val = Op.getOperand(0);
7977   MVT Ty = Val->getSimpleValueType(0);
7978   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7979   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7980                                          TLI.getPointerTy(DAG.getDataLayout()));
7981 
7982   TargetLowering::ArgListTy Args;
7983   TargetLowering::ArgListEntry Entry;
7984 
7985   Entry.Node = Val;
7986   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7987   Entry.IsZExt = true;
7988   Args.push_back(Entry);
7989 
7990   Entry.Node = Exponent;
7991   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7992   Entry.IsZExt = true;
7993   Args.push_back(Entry);
7994 
7995   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7996 
7997   // In the in-chain to the call is the entry node  If we are emitting a
7998   // tailcall, the chain will be mutated if the node has a non-entry input
7999   // chain.
8000   SDValue InChain = DAG.getEntryNode();
8001   SDValue TCChain = InChain;
8002 
8003   const Function &F = DAG.getMachineFunction().getFunction();
8004   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
8005               F.getReturnType() == LCRTy;
8006   if (IsTC)
8007     InChain = TCChain;
8008 
8009   TargetLowering::CallLoweringInfo CLI(DAG);
8010   CLI.setDebugLoc(dl)
8011       .setChain(InChain)
8012       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
8013       .setTailCall(IsTC);
8014   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
8015 
8016   // Return the chain (the DAG root) if it is a tail call
8017   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
8018 }
8019 
8020 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8021   LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
8022   switch (Op.getOpcode()) {
8023   default: llvm_unreachable("Don't know how to custom lower this!");
8024   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
8025   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8026   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
8027   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8028   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8029   case ISD::SELECT:        return LowerSELECT(Op, DAG);
8030   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
8031   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
8032   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
8033   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
8034   case ISD::VASTART:       return LowerVASTART(Op, DAG);
8035   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8036   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
8037   case ISD::SINT_TO_FP:
8038   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
8039   case ISD::FP_TO_SINT:
8040   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
8041   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
8042   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
8043   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
8044   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
8045   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
8046   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
8047   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
8048                                                                Subtarget);
8049   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
8050   case ISD::SHL:
8051   case ISD::SRL:
8052   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
8053   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
8054   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
8055   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
8056   case ISD::SRL_PARTS:
8057   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
8058   case ISD::CTTZ:
8059   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
8060   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
8061   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
8062   case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
8063   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
8064   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
8065   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8066   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8067   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8068   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8069   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
8070   case ISD::MUL:           return LowerMUL(Op, DAG);
8071   case ISD::SDIV:
8072     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8073       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
8074     return LowerSDIV(Op, DAG);
8075   case ISD::UDIV:
8076     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8077       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
8078     return LowerUDIV(Op, DAG);
8079   case ISD::ADDCARRY:
8080   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
8081   case ISD::SADDO:
8082   case ISD::SSUBO:
8083     return LowerSignedALUO(Op, DAG);
8084   case ISD::UADDO:
8085   case ISD::USUBO:
8086     return LowerUnsignedALUO(Op, DAG);
8087   case ISD::ATOMIC_LOAD:
8088   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
8089   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
8090   case ISD::SDIVREM:
8091   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
8092   case ISD::DYNAMIC_STACKALLOC:
8093     if (Subtarget->isTargetWindows())
8094       return LowerDYNAMIC_STACKALLOC(Op, DAG);
8095     llvm_unreachable("Don't know how to custom lower this!");
8096   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
8097   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
8098   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
8099   case ARMISD::WIN__DBZCHK: return SDValue();
8100   }
8101 }
8102 
8103 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
8104                                  SelectionDAG &DAG) {
8105   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8106   unsigned Opc = 0;
8107   if (IntNo == Intrinsic::arm_smlald)
8108     Opc = ARMISD::SMLALD;
8109   else if (IntNo == Intrinsic::arm_smlaldx)
8110     Opc = ARMISD::SMLALDX;
8111   else if (IntNo == Intrinsic::arm_smlsld)
8112     Opc = ARMISD::SMLSLD;
8113   else if (IntNo == Intrinsic::arm_smlsldx)
8114     Opc = ARMISD::SMLSLDX;
8115   else
8116     return;
8117 
8118   SDLoc dl(N);
8119   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8120                            N->getOperand(3),
8121                            DAG.getConstant(0, dl, MVT::i32));
8122   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8123                            N->getOperand(3),
8124                            DAG.getConstant(1, dl, MVT::i32));
8125 
8126   SDValue LongMul = DAG.getNode(Opc, dl,
8127                                 DAG.getVTList(MVT::i32, MVT::i32),
8128                                 N->getOperand(1), N->getOperand(2),
8129                                 Lo, Hi);
8130   Results.push_back(LongMul.getValue(0));
8131   Results.push_back(LongMul.getValue(1));
8132 }
8133 
8134 /// ReplaceNodeResults - Replace the results of node with an illegal result
8135 /// type with new values built out of custom code.
8136 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
8137                                            SmallVectorImpl<SDValue> &Results,
8138                                            SelectionDAG &DAG) const {
8139   SDValue Res;
8140   switch (N->getOpcode()) {
8141   default:
8142     llvm_unreachable("Don't know how to custom expand this!");
8143   case ISD::READ_REGISTER:
8144     ExpandREAD_REGISTER(N, Results, DAG);
8145     break;
8146   case ISD::BITCAST:
8147     Res = ExpandBITCAST(N, DAG, Subtarget);
8148     break;
8149   case ISD::SRL:
8150   case ISD::SRA:
8151     Res = Expand64BitShift(N, DAG, Subtarget);
8152     break;
8153   case ISD::SREM:
8154   case ISD::UREM:
8155     Res = LowerREM(N, DAG);
8156     break;
8157   case ISD::SDIVREM:
8158   case ISD::UDIVREM:
8159     Res = LowerDivRem(SDValue(N, 0), DAG);
8160     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
8161     Results.push_back(Res.getValue(0));
8162     Results.push_back(Res.getValue(1));
8163     return;
8164   case ISD::READCYCLECOUNTER:
8165     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
8166     return;
8167   case ISD::UDIV:
8168   case ISD::SDIV:
8169     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
8170     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
8171                              Results);
8172   case ISD::ATOMIC_CMP_SWAP:
8173     ReplaceCMP_SWAP_64Results(N, Results, DAG);
8174     return;
8175   case ISD::INTRINSIC_WO_CHAIN:
8176     return ReplaceLongIntrinsic(N, Results, DAG);
8177   }
8178   if (Res.getNode())
8179     Results.push_back(Res);
8180 }
8181 
8182 //===----------------------------------------------------------------------===//
8183 //                           ARM Scheduler Hooks
8184 //===----------------------------------------------------------------------===//
8185 
8186 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
8187 /// registers the function context.
8188 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
8189                                                MachineBasicBlock *MBB,
8190                                                MachineBasicBlock *DispatchBB,
8191                                                int FI) const {
8192   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
8193          "ROPI/RWPI not currently supported with SjLj");
8194   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8195   DebugLoc dl = MI.getDebugLoc();
8196   MachineFunction *MF = MBB->getParent();
8197   MachineRegisterInfo *MRI = &MF->getRegInfo();
8198   MachineConstantPool *MCP = MF->getConstantPool();
8199   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
8200   const Function &F = MF->getFunction();
8201 
8202   bool isThumb = Subtarget->isThumb();
8203   bool isThumb2 = Subtarget->isThumb2();
8204 
8205   unsigned PCLabelId = AFI->createPICLabelUId();
8206   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
8207   ARMConstantPoolValue *CPV =
8208     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
8209   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
8210 
8211   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
8212                                            : &ARM::GPRRegClass;
8213 
8214   // Grab constant pool and fixed stack memory operands.
8215   MachineMemOperand *CPMMO =
8216       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
8217                                MachineMemOperand::MOLoad, 4, 4);
8218 
8219   MachineMemOperand *FIMMOSt =
8220       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
8221                                MachineMemOperand::MOStore, 4, 4);
8222 
8223   // Load the address of the dispatch MBB into the jump buffer.
8224   if (isThumb2) {
8225     // Incoming value: jbuf
8226     //   ldr.n  r5, LCPI1_1
8227     //   orr    r5, r5, #1
8228     //   add    r5, pc
8229     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
8230     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8231     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
8232         .addConstantPoolIndex(CPI)
8233         .addMemOperand(CPMMO)
8234         .add(predOps(ARMCC::AL));
8235     // Set the low bit because of thumb mode.
8236     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8237     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8238         .addReg(NewVReg1, RegState::Kill)
8239         .addImm(0x01)
8240         .add(predOps(ARMCC::AL))
8241         .add(condCodeOp());
8242     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8243     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8244       .addReg(NewVReg2, RegState::Kill)
8245       .addImm(PCLabelId);
8246     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8247         .addReg(NewVReg3, RegState::Kill)
8248         .addFrameIndex(FI)
8249         .addImm(36) // &jbuf[1] :: pc
8250         .addMemOperand(FIMMOSt)
8251         .add(predOps(ARMCC::AL));
8252   } else if (isThumb) {
8253     // Incoming value: jbuf
8254     //   ldr.n  r1, LCPI1_4
8255     //   add    r1, pc
8256     //   mov    r2, #1
8257     //   orrs   r1, r2
8258     //   add    r2, $jbuf, #+4 ; &jbuf[1]
8259     //   str    r1, [r2]
8260     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8261     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8262         .addConstantPoolIndex(CPI)
8263         .addMemOperand(CPMMO)
8264         .add(predOps(ARMCC::AL));
8265     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8266     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8267       .addReg(NewVReg1, RegState::Kill)
8268       .addImm(PCLabelId);
8269     // Set the low bit because of thumb mode.
8270     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8271     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8272         .addReg(ARM::CPSR, RegState::Define)
8273         .addImm(1)
8274         .add(predOps(ARMCC::AL));
8275     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8276     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8277         .addReg(ARM::CPSR, RegState::Define)
8278         .addReg(NewVReg2, RegState::Kill)
8279         .addReg(NewVReg3, RegState::Kill)
8280         .add(predOps(ARMCC::AL));
8281     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8282     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8283             .addFrameIndex(FI)
8284             .addImm(36); // &jbuf[1] :: pc
8285     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8286         .addReg(NewVReg4, RegState::Kill)
8287         .addReg(NewVReg5, RegState::Kill)
8288         .addImm(0)
8289         .addMemOperand(FIMMOSt)
8290         .add(predOps(ARMCC::AL));
8291   } else {
8292     // Incoming value: jbuf
8293     //   ldr  r1, LCPI1_1
8294     //   add  r1, pc, r1
8295     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
8296     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8297     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
8298         .addConstantPoolIndex(CPI)
8299         .addImm(0)
8300         .addMemOperand(CPMMO)
8301         .add(predOps(ARMCC::AL));
8302     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8303     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
8304         .addReg(NewVReg1, RegState::Kill)
8305         .addImm(PCLabelId)
8306         .add(predOps(ARMCC::AL));
8307     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
8308         .addReg(NewVReg2, RegState::Kill)
8309         .addFrameIndex(FI)
8310         .addImm(36) // &jbuf[1] :: pc
8311         .addMemOperand(FIMMOSt)
8312         .add(predOps(ARMCC::AL));
8313   }
8314 }
8315 
8316 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
8317                                               MachineBasicBlock *MBB) const {
8318   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8319   DebugLoc dl = MI.getDebugLoc();
8320   MachineFunction *MF = MBB->getParent();
8321   MachineRegisterInfo *MRI = &MF->getRegInfo();
8322   MachineFrameInfo &MFI = MF->getFrameInfo();
8323   int FI = MFI.getFunctionContextIndex();
8324 
8325   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
8326                                                         : &ARM::GPRnopcRegClass;
8327 
8328   // Get a mapping of the call site numbers to all of the landing pads they're
8329   // associated with.
8330   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
8331   unsigned MaxCSNum = 0;
8332   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8333        ++BB) {
8334     if (!BB->isEHPad()) continue;
8335 
8336     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8337     // pad.
8338     for (MachineBasicBlock::iterator
8339            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8340       if (!II->isEHLabel()) continue;
8341 
8342       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8343       if (!MF->hasCallSiteLandingPad(Sym)) continue;
8344 
8345       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8346       for (SmallVectorImpl<unsigned>::iterator
8347              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8348            CSI != CSE; ++CSI) {
8349         CallSiteNumToLPad[*CSI].push_back(&*BB);
8350         MaxCSNum = std::max(MaxCSNum, *CSI);
8351       }
8352       break;
8353     }
8354   }
8355 
8356   // Get an ordered list of the machine basic blocks for the jump table.
8357   std::vector<MachineBasicBlock*> LPadList;
8358   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8359   LPadList.reserve(CallSiteNumToLPad.size());
8360   for (unsigned I = 1; I <= MaxCSNum; ++I) {
8361     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8362     for (SmallVectorImpl<MachineBasicBlock*>::iterator
8363            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8364       LPadList.push_back(*II);
8365       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8366     }
8367   }
8368 
8369   assert(!LPadList.empty() &&
8370          "No landing pad destinations for the dispatch jump table!");
8371 
8372   // Create the jump table and associated information.
8373   MachineJumpTableInfo *JTI =
8374     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8375   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8376 
8377   // Create the MBBs for the dispatch code.
8378 
8379   // Shove the dispatch's address into the return slot in the function context.
8380   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8381   DispatchBB->setIsEHPad();
8382 
8383   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8384   unsigned trap_opcode;
8385   if (Subtarget->isThumb())
8386     trap_opcode = ARM::tTRAP;
8387   else
8388     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8389 
8390   BuildMI(TrapBB, dl, TII->get(trap_opcode));
8391   DispatchBB->addSuccessor(TrapBB);
8392 
8393   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8394   DispatchBB->addSuccessor(DispContBB);
8395 
8396   // Insert and MBBs.
8397   MF->insert(MF->end(), DispatchBB);
8398   MF->insert(MF->end(), DispContBB);
8399   MF->insert(MF->end(), TrapBB);
8400 
8401   // Insert code into the entry block that creates and registers the function
8402   // context.
8403   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8404 
8405   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8406       MachinePointerInfo::getFixedStack(*MF, FI),
8407       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8408 
8409   MachineInstrBuilder MIB;
8410   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8411 
8412   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8413   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8414 
8415   // Add a register mask with no preserved registers.  This results in all
8416   // registers being marked as clobbered. This can't work if the dispatch block
8417   // is in a Thumb1 function and is linked with ARM code which uses the FP
8418   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8419   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8420 
8421   bool IsPositionIndependent = isPositionIndependent();
8422   unsigned NumLPads = LPadList.size();
8423   if (Subtarget->isThumb2()) {
8424     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8425     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8426         .addFrameIndex(FI)
8427         .addImm(4)
8428         .addMemOperand(FIMMOLd)
8429         .add(predOps(ARMCC::AL));
8430 
8431     if (NumLPads < 256) {
8432       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8433           .addReg(NewVReg1)
8434           .addImm(LPadList.size())
8435           .add(predOps(ARMCC::AL));
8436     } else {
8437       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8438       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8439           .addImm(NumLPads & 0xFFFF)
8440           .add(predOps(ARMCC::AL));
8441 
8442       unsigned VReg2 = VReg1;
8443       if ((NumLPads & 0xFFFF0000) != 0) {
8444         VReg2 = MRI->createVirtualRegister(TRC);
8445         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8446             .addReg(VReg1)
8447             .addImm(NumLPads >> 16)
8448             .add(predOps(ARMCC::AL));
8449       }
8450 
8451       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8452           .addReg(NewVReg1)
8453           .addReg(VReg2)
8454           .add(predOps(ARMCC::AL));
8455     }
8456 
8457     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8458       .addMBB(TrapBB)
8459       .addImm(ARMCC::HI)
8460       .addReg(ARM::CPSR);
8461 
8462     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8463     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8464         .addJumpTableIndex(MJTI)
8465         .add(predOps(ARMCC::AL));
8466 
8467     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8468     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8469         .addReg(NewVReg3, RegState::Kill)
8470         .addReg(NewVReg1)
8471         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8472         .add(predOps(ARMCC::AL))
8473         .add(condCodeOp());
8474 
8475     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8476       .addReg(NewVReg4, RegState::Kill)
8477       .addReg(NewVReg1)
8478       .addJumpTableIndex(MJTI);
8479   } else if (Subtarget->isThumb()) {
8480     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8481     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8482         .addFrameIndex(FI)
8483         .addImm(1)
8484         .addMemOperand(FIMMOLd)
8485         .add(predOps(ARMCC::AL));
8486 
8487     if (NumLPads < 256) {
8488       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8489           .addReg(NewVReg1)
8490           .addImm(NumLPads)
8491           .add(predOps(ARMCC::AL));
8492     } else {
8493       MachineConstantPool *ConstantPool = MF->getConstantPool();
8494       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8495       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8496 
8497       // MachineConstantPool wants an explicit alignment.
8498       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8499       if (Align == 0)
8500         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8501       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8502 
8503       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8504       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8505           .addReg(VReg1, RegState::Define)
8506           .addConstantPoolIndex(Idx)
8507           .add(predOps(ARMCC::AL));
8508       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8509           .addReg(NewVReg1)
8510           .addReg(VReg1)
8511           .add(predOps(ARMCC::AL));
8512     }
8513 
8514     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8515       .addMBB(TrapBB)
8516       .addImm(ARMCC::HI)
8517       .addReg(ARM::CPSR);
8518 
8519     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8520     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8521         .addReg(ARM::CPSR, RegState::Define)
8522         .addReg(NewVReg1)
8523         .addImm(2)
8524         .add(predOps(ARMCC::AL));
8525 
8526     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8527     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8528         .addJumpTableIndex(MJTI)
8529         .add(predOps(ARMCC::AL));
8530 
8531     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8532     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8533         .addReg(ARM::CPSR, RegState::Define)
8534         .addReg(NewVReg2, RegState::Kill)
8535         .addReg(NewVReg3)
8536         .add(predOps(ARMCC::AL));
8537 
8538     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8539         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8540 
8541     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8542     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8543         .addReg(NewVReg4, RegState::Kill)
8544         .addImm(0)
8545         .addMemOperand(JTMMOLd)
8546         .add(predOps(ARMCC::AL));
8547 
8548     unsigned NewVReg6 = NewVReg5;
8549     if (IsPositionIndependent) {
8550       NewVReg6 = MRI->createVirtualRegister(TRC);
8551       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8552           .addReg(ARM::CPSR, RegState::Define)
8553           .addReg(NewVReg5, RegState::Kill)
8554           .addReg(NewVReg3)
8555           .add(predOps(ARMCC::AL));
8556     }
8557 
8558     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8559       .addReg(NewVReg6, RegState::Kill)
8560       .addJumpTableIndex(MJTI);
8561   } else {
8562     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8563     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8564         .addFrameIndex(FI)
8565         .addImm(4)
8566         .addMemOperand(FIMMOLd)
8567         .add(predOps(ARMCC::AL));
8568 
8569     if (NumLPads < 256) {
8570       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8571           .addReg(NewVReg1)
8572           .addImm(NumLPads)
8573           .add(predOps(ARMCC::AL));
8574     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8575       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8576       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8577           .addImm(NumLPads & 0xFFFF)
8578           .add(predOps(ARMCC::AL));
8579 
8580       unsigned VReg2 = VReg1;
8581       if ((NumLPads & 0xFFFF0000) != 0) {
8582         VReg2 = MRI->createVirtualRegister(TRC);
8583         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8584             .addReg(VReg1)
8585             .addImm(NumLPads >> 16)
8586             .add(predOps(ARMCC::AL));
8587       }
8588 
8589       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8590           .addReg(NewVReg1)
8591           .addReg(VReg2)
8592           .add(predOps(ARMCC::AL));
8593     } else {
8594       MachineConstantPool *ConstantPool = MF->getConstantPool();
8595       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8596       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8597 
8598       // MachineConstantPool wants an explicit alignment.
8599       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8600       if (Align == 0)
8601         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8602       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8603 
8604       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8605       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8606           .addReg(VReg1, RegState::Define)
8607           .addConstantPoolIndex(Idx)
8608           .addImm(0)
8609           .add(predOps(ARMCC::AL));
8610       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8611           .addReg(NewVReg1)
8612           .addReg(VReg1, RegState::Kill)
8613           .add(predOps(ARMCC::AL));
8614     }
8615 
8616     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8617       .addMBB(TrapBB)
8618       .addImm(ARMCC::HI)
8619       .addReg(ARM::CPSR);
8620 
8621     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8622     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8623         .addReg(NewVReg1)
8624         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8625         .add(predOps(ARMCC::AL))
8626         .add(condCodeOp());
8627     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8628     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8629         .addJumpTableIndex(MJTI)
8630         .add(predOps(ARMCC::AL));
8631 
8632     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8633         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8634     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8635     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8636         .addReg(NewVReg3, RegState::Kill)
8637         .addReg(NewVReg4)
8638         .addImm(0)
8639         .addMemOperand(JTMMOLd)
8640         .add(predOps(ARMCC::AL));
8641 
8642     if (IsPositionIndependent) {
8643       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8644         .addReg(NewVReg5, RegState::Kill)
8645         .addReg(NewVReg4)
8646         .addJumpTableIndex(MJTI);
8647     } else {
8648       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8649         .addReg(NewVReg5, RegState::Kill)
8650         .addJumpTableIndex(MJTI);
8651     }
8652   }
8653 
8654   // Add the jump table entries as successors to the MBB.
8655   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8656   for (std::vector<MachineBasicBlock*>::iterator
8657          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8658     MachineBasicBlock *CurMBB = *I;
8659     if (SeenMBBs.insert(CurMBB).second)
8660       DispContBB->addSuccessor(CurMBB);
8661   }
8662 
8663   // N.B. the order the invoke BBs are processed in doesn't matter here.
8664   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8665   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8666   for (MachineBasicBlock *BB : InvokeBBs) {
8667 
8668     // Remove the landing pad successor from the invoke block and replace it
8669     // with the new dispatch block.
8670     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8671                                                   BB->succ_end());
8672     while (!Successors.empty()) {
8673       MachineBasicBlock *SMBB = Successors.pop_back_val();
8674       if (SMBB->isEHPad()) {
8675         BB->removeSuccessor(SMBB);
8676         MBBLPads.push_back(SMBB);
8677       }
8678     }
8679 
8680     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8681     BB->normalizeSuccProbs();
8682 
8683     // Find the invoke call and mark all of the callee-saved registers as
8684     // 'implicit defined' so that they're spilled. This prevents code from
8685     // moving instructions to before the EH block, where they will never be
8686     // executed.
8687     for (MachineBasicBlock::reverse_iterator
8688            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8689       if (!II->isCall()) continue;
8690 
8691       DenseMap<unsigned, bool> DefRegs;
8692       for (MachineInstr::mop_iterator
8693              OI = II->operands_begin(), OE = II->operands_end();
8694            OI != OE; ++OI) {
8695         if (!OI->isReg()) continue;
8696         DefRegs[OI->getReg()] = true;
8697       }
8698 
8699       MachineInstrBuilder MIB(*MF, &*II);
8700 
8701       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8702         unsigned Reg = SavedRegs[i];
8703         if (Subtarget->isThumb2() &&
8704             !ARM::tGPRRegClass.contains(Reg) &&
8705             !ARM::hGPRRegClass.contains(Reg))
8706           continue;
8707         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8708           continue;
8709         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8710           continue;
8711         if (!DefRegs[Reg])
8712           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8713       }
8714 
8715       break;
8716     }
8717   }
8718 
8719   // Mark all former landing pads as non-landing pads. The dispatch is the only
8720   // landing pad now.
8721   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8722          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8723     (*I)->setIsEHPad(false);
8724 
8725   // The instruction is gone now.
8726   MI.eraseFromParent();
8727 }
8728 
8729 static
8730 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8731   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8732        E = MBB->succ_end(); I != E; ++I)
8733     if (*I != Succ)
8734       return *I;
8735   llvm_unreachable("Expecting a BB with two successors!");
8736 }
8737 
8738 /// Return the load opcode for a given load size. If load size >= 8,
8739 /// neon opcode will be returned.
8740 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8741   if (LdSize >= 8)
8742     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8743                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8744   if (IsThumb1)
8745     return LdSize == 4 ? ARM::tLDRi
8746                        : LdSize == 2 ? ARM::tLDRHi
8747                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8748   if (IsThumb2)
8749     return LdSize == 4 ? ARM::t2LDR_POST
8750                        : LdSize == 2 ? ARM::t2LDRH_POST
8751                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8752   return LdSize == 4 ? ARM::LDR_POST_IMM
8753                      : LdSize == 2 ? ARM::LDRH_POST
8754                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8755 }
8756 
8757 /// Return the store opcode for a given store size. If store size >= 8,
8758 /// neon opcode will be returned.
8759 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8760   if (StSize >= 8)
8761     return StSize == 16 ? ARM::VST1q32wb_fixed
8762                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8763   if (IsThumb1)
8764     return StSize == 4 ? ARM::tSTRi
8765                        : StSize == 2 ? ARM::tSTRHi
8766                                      : StSize == 1 ? ARM::tSTRBi : 0;
8767   if (IsThumb2)
8768     return StSize == 4 ? ARM::t2STR_POST
8769                        : StSize == 2 ? ARM::t2STRH_POST
8770                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8771   return StSize == 4 ? ARM::STR_POST_IMM
8772                      : StSize == 2 ? ARM::STRH_POST
8773                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8774 }
8775 
8776 /// Emit a post-increment load operation with given size. The instructions
8777 /// will be added to BB at Pos.
8778 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8779                        const TargetInstrInfo *TII, const DebugLoc &dl,
8780                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8781                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8782   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8783   assert(LdOpc != 0 && "Should have a load opcode");
8784   if (LdSize >= 8) {
8785     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8786         .addReg(AddrOut, RegState::Define)
8787         .addReg(AddrIn)
8788         .addImm(0)
8789         .add(predOps(ARMCC::AL));
8790   } else if (IsThumb1) {
8791     // load + update AddrIn
8792     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8793         .addReg(AddrIn)
8794         .addImm(0)
8795         .add(predOps(ARMCC::AL));
8796     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8797         .add(t1CondCodeOp())
8798         .addReg(AddrIn)
8799         .addImm(LdSize)
8800         .add(predOps(ARMCC::AL));
8801   } else if (IsThumb2) {
8802     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8803         .addReg(AddrOut, RegState::Define)
8804         .addReg(AddrIn)
8805         .addImm(LdSize)
8806         .add(predOps(ARMCC::AL));
8807   } else { // arm
8808     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8809         .addReg(AddrOut, RegState::Define)
8810         .addReg(AddrIn)
8811         .addReg(0)
8812         .addImm(LdSize)
8813         .add(predOps(ARMCC::AL));
8814   }
8815 }
8816 
8817 /// Emit a post-increment store operation with given size. The instructions
8818 /// will be added to BB at Pos.
8819 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8820                        const TargetInstrInfo *TII, const DebugLoc &dl,
8821                        unsigned StSize, unsigned Data, unsigned AddrIn,
8822                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8823   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8824   assert(StOpc != 0 && "Should have a store opcode");
8825   if (StSize >= 8) {
8826     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8827         .addReg(AddrIn)
8828         .addImm(0)
8829         .addReg(Data)
8830         .add(predOps(ARMCC::AL));
8831   } else if (IsThumb1) {
8832     // store + update AddrIn
8833     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8834         .addReg(Data)
8835         .addReg(AddrIn)
8836         .addImm(0)
8837         .add(predOps(ARMCC::AL));
8838     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8839         .add(t1CondCodeOp())
8840         .addReg(AddrIn)
8841         .addImm(StSize)
8842         .add(predOps(ARMCC::AL));
8843   } else if (IsThumb2) {
8844     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8845         .addReg(Data)
8846         .addReg(AddrIn)
8847         .addImm(StSize)
8848         .add(predOps(ARMCC::AL));
8849   } else { // arm
8850     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8851         .addReg(Data)
8852         .addReg(AddrIn)
8853         .addReg(0)
8854         .addImm(StSize)
8855         .add(predOps(ARMCC::AL));
8856   }
8857 }
8858 
8859 MachineBasicBlock *
8860 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8861                                    MachineBasicBlock *BB) const {
8862   // This pseudo instruction has 3 operands: dst, src, size
8863   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8864   // Otherwise, we will generate unrolled scalar copies.
8865   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8866   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8867   MachineFunction::iterator It = ++BB->getIterator();
8868 
8869   unsigned dest = MI.getOperand(0).getReg();
8870   unsigned src = MI.getOperand(1).getReg();
8871   unsigned SizeVal = MI.getOperand(2).getImm();
8872   unsigned Align = MI.getOperand(3).getImm();
8873   DebugLoc dl = MI.getDebugLoc();
8874 
8875   MachineFunction *MF = BB->getParent();
8876   MachineRegisterInfo &MRI = MF->getRegInfo();
8877   unsigned UnitSize = 0;
8878   const TargetRegisterClass *TRC = nullptr;
8879   const TargetRegisterClass *VecTRC = nullptr;
8880 
8881   bool IsThumb1 = Subtarget->isThumb1Only();
8882   bool IsThumb2 = Subtarget->isThumb2();
8883   bool IsThumb = Subtarget->isThumb();
8884 
8885   if (Align & 1) {
8886     UnitSize = 1;
8887   } else if (Align & 2) {
8888     UnitSize = 2;
8889   } else {
8890     // Check whether we can use NEON instructions.
8891     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
8892         Subtarget->hasNEON()) {
8893       if ((Align % 16 == 0) && SizeVal >= 16)
8894         UnitSize = 16;
8895       else if ((Align % 8 == 0) && SizeVal >= 8)
8896         UnitSize = 8;
8897     }
8898     // Can't use NEON instructions.
8899     if (UnitSize == 0)
8900       UnitSize = 4;
8901   }
8902 
8903   // Select the correct opcode and register class for unit size load/store
8904   bool IsNeon = UnitSize >= 8;
8905   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8906   if (IsNeon)
8907     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8908                             : UnitSize == 8 ? &ARM::DPRRegClass
8909                                             : nullptr;
8910 
8911   unsigned BytesLeft = SizeVal % UnitSize;
8912   unsigned LoopSize = SizeVal - BytesLeft;
8913 
8914   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8915     // Use LDR and STR to copy.
8916     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8917     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8918     unsigned srcIn = src;
8919     unsigned destIn = dest;
8920     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8921       unsigned srcOut = MRI.createVirtualRegister(TRC);
8922       unsigned destOut = MRI.createVirtualRegister(TRC);
8923       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8924       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8925                  IsThumb1, IsThumb2);
8926       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8927                  IsThumb1, IsThumb2);
8928       srcIn = srcOut;
8929       destIn = destOut;
8930     }
8931 
8932     // Handle the leftover bytes with LDRB and STRB.
8933     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8934     // [destOut] = STRB_POST(scratch, destIn, 1)
8935     for (unsigned i = 0; i < BytesLeft; i++) {
8936       unsigned srcOut = MRI.createVirtualRegister(TRC);
8937       unsigned destOut = MRI.createVirtualRegister(TRC);
8938       unsigned scratch = MRI.createVirtualRegister(TRC);
8939       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8940                  IsThumb1, IsThumb2);
8941       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8942                  IsThumb1, IsThumb2);
8943       srcIn = srcOut;
8944       destIn = destOut;
8945     }
8946     MI.eraseFromParent(); // The instruction is gone now.
8947     return BB;
8948   }
8949 
8950   // Expand the pseudo op to a loop.
8951   // thisMBB:
8952   //   ...
8953   //   movw varEnd, # --> with thumb2
8954   //   movt varEnd, #
8955   //   ldrcp varEnd, idx --> without thumb2
8956   //   fallthrough --> loopMBB
8957   // loopMBB:
8958   //   PHI varPhi, varEnd, varLoop
8959   //   PHI srcPhi, src, srcLoop
8960   //   PHI destPhi, dst, destLoop
8961   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8962   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8963   //   subs varLoop, varPhi, #UnitSize
8964   //   bne loopMBB
8965   //   fallthrough --> exitMBB
8966   // exitMBB:
8967   //   epilogue to handle left-over bytes
8968   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8969   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8970   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8971   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8972   MF->insert(It, loopMBB);
8973   MF->insert(It, exitMBB);
8974 
8975   // Transfer the remainder of BB and its successor edges to exitMBB.
8976   exitMBB->splice(exitMBB->begin(), BB,
8977                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8978   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8979 
8980   // Load an immediate to varEnd.
8981   unsigned varEnd = MRI.createVirtualRegister(TRC);
8982   if (Subtarget->useMovt(*MF)) {
8983     unsigned Vtmp = varEnd;
8984     if ((LoopSize & 0xFFFF0000) != 0)
8985       Vtmp = MRI.createVirtualRegister(TRC);
8986     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8987         .addImm(LoopSize & 0xFFFF)
8988         .add(predOps(ARMCC::AL));
8989 
8990     if ((LoopSize & 0xFFFF0000) != 0)
8991       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8992           .addReg(Vtmp)
8993           .addImm(LoopSize >> 16)
8994           .add(predOps(ARMCC::AL));
8995   } else {
8996     MachineConstantPool *ConstantPool = MF->getConstantPool();
8997     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8998     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8999 
9000     // MachineConstantPool wants an explicit alignment.
9001     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9002     if (Align == 0)
9003       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9004     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9005 
9006     if (IsThumb)
9007       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
9008           .addReg(varEnd, RegState::Define)
9009           .addConstantPoolIndex(Idx)
9010           .add(predOps(ARMCC::AL));
9011     else
9012       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
9013           .addReg(varEnd, RegState::Define)
9014           .addConstantPoolIndex(Idx)
9015           .addImm(0)
9016           .add(predOps(ARMCC::AL));
9017   }
9018   BB->addSuccessor(loopMBB);
9019 
9020   // Generate the loop body:
9021   //   varPhi = PHI(varLoop, varEnd)
9022   //   srcPhi = PHI(srcLoop, src)
9023   //   destPhi = PHI(destLoop, dst)
9024   MachineBasicBlock *entryBB = BB;
9025   BB = loopMBB;
9026   unsigned varLoop = MRI.createVirtualRegister(TRC);
9027   unsigned varPhi = MRI.createVirtualRegister(TRC);
9028   unsigned srcLoop = MRI.createVirtualRegister(TRC);
9029   unsigned srcPhi = MRI.createVirtualRegister(TRC);
9030   unsigned destLoop = MRI.createVirtualRegister(TRC);
9031   unsigned destPhi = MRI.createVirtualRegister(TRC);
9032 
9033   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
9034     .addReg(varLoop).addMBB(loopMBB)
9035     .addReg(varEnd).addMBB(entryBB);
9036   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
9037     .addReg(srcLoop).addMBB(loopMBB)
9038     .addReg(src).addMBB(entryBB);
9039   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
9040     .addReg(destLoop).addMBB(loopMBB)
9041     .addReg(dest).addMBB(entryBB);
9042 
9043   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9044   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
9045   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9046   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
9047              IsThumb1, IsThumb2);
9048   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
9049              IsThumb1, IsThumb2);
9050 
9051   // Decrement loop variable by UnitSize.
9052   if (IsThumb1) {
9053     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
9054         .add(t1CondCodeOp())
9055         .addReg(varPhi)
9056         .addImm(UnitSize)
9057         .add(predOps(ARMCC::AL));
9058   } else {
9059     MachineInstrBuilder MIB =
9060         BuildMI(*BB, BB->end(), dl,
9061                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
9062     MIB.addReg(varPhi)
9063         .addImm(UnitSize)
9064         .add(predOps(ARMCC::AL))
9065         .add(condCodeOp());
9066     MIB->getOperand(5).setReg(ARM::CPSR);
9067     MIB->getOperand(5).setIsDef(true);
9068   }
9069   BuildMI(*BB, BB->end(), dl,
9070           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
9071       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
9072 
9073   // loopMBB can loop back to loopMBB or fall through to exitMBB.
9074   BB->addSuccessor(loopMBB);
9075   BB->addSuccessor(exitMBB);
9076 
9077   // Add epilogue to handle BytesLeft.
9078   BB = exitMBB;
9079   auto StartOfExit = exitMBB->begin();
9080 
9081   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9082   //   [destOut] = STRB_POST(scratch, destLoop, 1)
9083   unsigned srcIn = srcLoop;
9084   unsigned destIn = destLoop;
9085   for (unsigned i = 0; i < BytesLeft; i++) {
9086     unsigned srcOut = MRI.createVirtualRegister(TRC);
9087     unsigned destOut = MRI.createVirtualRegister(TRC);
9088     unsigned scratch = MRI.createVirtualRegister(TRC);
9089     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
9090                IsThumb1, IsThumb2);
9091     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
9092                IsThumb1, IsThumb2);
9093     srcIn = srcOut;
9094     destIn = destOut;
9095   }
9096 
9097   MI.eraseFromParent(); // The instruction is gone now.
9098   return BB;
9099 }
9100 
9101 MachineBasicBlock *
9102 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
9103                                        MachineBasicBlock *MBB) const {
9104   const TargetMachine &TM = getTargetMachine();
9105   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
9106   DebugLoc DL = MI.getDebugLoc();
9107 
9108   assert(Subtarget->isTargetWindows() &&
9109          "__chkstk is only supported on Windows");
9110   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
9111 
9112   // __chkstk takes the number of words to allocate on the stack in R4, and
9113   // returns the stack adjustment in number of bytes in R4.  This will not
9114   // clober any other registers (other than the obvious lr).
9115   //
9116   // Although, technically, IP should be considered a register which may be
9117   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
9118   // thumb-2 environment, so there is no interworking required.  As a result, we
9119   // do not expect a veneer to be emitted by the linker, clobbering IP.
9120   //
9121   // Each module receives its own copy of __chkstk, so no import thunk is
9122   // required, again, ensuring that IP is not clobbered.
9123   //
9124   // Finally, although some linkers may theoretically provide a trampoline for
9125   // out of range calls (which is quite common due to a 32M range limitation of
9126   // branches for Thumb), we can generate the long-call version via
9127   // -mcmodel=large, alleviating the need for the trampoline which may clobber
9128   // IP.
9129 
9130   switch (TM.getCodeModel()) {
9131   case CodeModel::Tiny:
9132     llvm_unreachable("Tiny code model not available on ARM.");
9133   case CodeModel::Small:
9134   case CodeModel::Medium:
9135   case CodeModel::Kernel:
9136     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
9137         .add(predOps(ARMCC::AL))
9138         .addExternalSymbol("__chkstk")
9139         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9140         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9141         .addReg(ARM::R12,
9142                 RegState::Implicit | RegState::Define | RegState::Dead)
9143         .addReg(ARM::CPSR,
9144                 RegState::Implicit | RegState::Define | RegState::Dead);
9145     break;
9146   case CodeModel::Large: {
9147     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9148     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
9149 
9150     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
9151       .addExternalSymbol("__chkstk");
9152     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
9153         .add(predOps(ARMCC::AL))
9154         .addReg(Reg, RegState::Kill)
9155         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9156         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9157         .addReg(ARM::R12,
9158                 RegState::Implicit | RegState::Define | RegState::Dead)
9159         .addReg(ARM::CPSR,
9160                 RegState::Implicit | RegState::Define | RegState::Dead);
9161     break;
9162   }
9163   }
9164 
9165   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
9166       .addReg(ARM::SP, RegState::Kill)
9167       .addReg(ARM::R4, RegState::Kill)
9168       .setMIFlags(MachineInstr::FrameSetup)
9169       .add(predOps(ARMCC::AL))
9170       .add(condCodeOp());
9171 
9172   MI.eraseFromParent();
9173   return MBB;
9174 }
9175 
9176 MachineBasicBlock *
9177 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
9178                                        MachineBasicBlock *MBB) const {
9179   DebugLoc DL = MI.getDebugLoc();
9180   MachineFunction *MF = MBB->getParent();
9181   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9182 
9183   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
9184   MF->insert(++MBB->getIterator(), ContBB);
9185   ContBB->splice(ContBB->begin(), MBB,
9186                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9187   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
9188   MBB->addSuccessor(ContBB);
9189 
9190   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9191   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
9192   MF->push_back(TrapBB);
9193   MBB->addSuccessor(TrapBB);
9194 
9195   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
9196       .addReg(MI.getOperand(0).getReg())
9197       .addImm(0)
9198       .add(predOps(ARMCC::AL));
9199   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
9200       .addMBB(TrapBB)
9201       .addImm(ARMCC::EQ)
9202       .addReg(ARM::CPSR);
9203 
9204   MI.eraseFromParent();
9205   return ContBB;
9206 }
9207 
9208 // The CPSR operand of SelectItr might be missing a kill marker
9209 // because there were multiple uses of CPSR, and ISel didn't know
9210 // which to mark. Figure out whether SelectItr should have had a
9211 // kill marker, and set it if it should. Returns the correct kill
9212 // marker value.
9213 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
9214                                    MachineBasicBlock* BB,
9215                                    const TargetRegisterInfo* TRI) {
9216   // Scan forward through BB for a use/def of CPSR.
9217   MachineBasicBlock::iterator miI(std::next(SelectItr));
9218   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
9219     const MachineInstr& mi = *miI;
9220     if (mi.readsRegister(ARM::CPSR))
9221       return false;
9222     if (mi.definesRegister(ARM::CPSR))
9223       break; // Should have kill-flag - update below.
9224   }
9225 
9226   // If we hit the end of the block, check whether CPSR is live into a
9227   // successor.
9228   if (miI == BB->end()) {
9229     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
9230                                           sEnd = BB->succ_end();
9231          sItr != sEnd; ++sItr) {
9232       MachineBasicBlock* succ = *sItr;
9233       if (succ->isLiveIn(ARM::CPSR))
9234         return false;
9235     }
9236   }
9237 
9238   // We found a def, or hit the end of the basic block and CPSR wasn't live
9239   // out. SelectMI should have a kill flag on CPSR.
9240   SelectItr->addRegisterKilled(ARM::CPSR, TRI);
9241   return true;
9242 }
9243 
9244 MachineBasicBlock *
9245 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9246                                                MachineBasicBlock *BB) const {
9247   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9248   DebugLoc dl = MI.getDebugLoc();
9249   bool isThumb2 = Subtarget->isThumb2();
9250   switch (MI.getOpcode()) {
9251   default: {
9252     MI.print(errs());
9253     llvm_unreachable("Unexpected instr type to insert");
9254   }
9255 
9256   // Thumb1 post-indexed loads are really just single-register LDMs.
9257   case ARM::tLDR_postidx: {
9258     MachineOperand Def(MI.getOperand(1));
9259     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
9260         .add(Def)  // Rn_wb
9261         .add(MI.getOperand(2))  // Rn
9262         .add(MI.getOperand(3))  // PredImm
9263         .add(MI.getOperand(4))  // PredReg
9264         .add(MI.getOperand(0)); // Rt
9265     MI.eraseFromParent();
9266     return BB;
9267   }
9268 
9269   // The Thumb2 pre-indexed stores have the same MI operands, they just
9270   // define them differently in the .td files from the isel patterns, so
9271   // they need pseudos.
9272   case ARM::t2STR_preidx:
9273     MI.setDesc(TII->get(ARM::t2STR_PRE));
9274     return BB;
9275   case ARM::t2STRB_preidx:
9276     MI.setDesc(TII->get(ARM::t2STRB_PRE));
9277     return BB;
9278   case ARM::t2STRH_preidx:
9279     MI.setDesc(TII->get(ARM::t2STRH_PRE));
9280     return BB;
9281 
9282   case ARM::STRi_preidx:
9283   case ARM::STRBi_preidx: {
9284     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9285                                                          : ARM::STRB_PRE_IMM;
9286     // Decode the offset.
9287     unsigned Offset = MI.getOperand(4).getImm();
9288     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
9289     Offset = ARM_AM::getAM2Offset(Offset);
9290     if (isSub)
9291       Offset = -Offset;
9292 
9293     MachineMemOperand *MMO = *MI.memoperands_begin();
9294     BuildMI(*BB, MI, dl, TII->get(NewOpc))
9295         .add(MI.getOperand(0)) // Rn_wb
9296         .add(MI.getOperand(1)) // Rt
9297         .add(MI.getOperand(2)) // Rn
9298         .addImm(Offset)        // offset (skip GPR==zero_reg)
9299         .add(MI.getOperand(5)) // pred
9300         .add(MI.getOperand(6))
9301         .addMemOperand(MMO);
9302     MI.eraseFromParent();
9303     return BB;
9304   }
9305   case ARM::STRr_preidx:
9306   case ARM::STRBr_preidx:
9307   case ARM::STRH_preidx: {
9308     unsigned NewOpc;
9309     switch (MI.getOpcode()) {
9310     default: llvm_unreachable("unexpected opcode!");
9311     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
9312     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
9313     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
9314     }
9315     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
9316     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
9317       MIB.add(MI.getOperand(i));
9318     MI.eraseFromParent();
9319     return BB;
9320   }
9321 
9322   case ARM::tMOVCCr_pseudo: {
9323     // To "insert" a SELECT_CC instruction, we actually have to insert the
9324     // diamond control-flow pattern.  The incoming instruction knows the
9325     // destination vreg to set, the condition code register to branch on, the
9326     // true/false values to select between, and a branch opcode to use.
9327     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9328     MachineFunction::iterator It = ++BB->getIterator();
9329 
9330     //  thisMBB:
9331     //  ...
9332     //   TrueVal = ...
9333     //   cmpTY ccX, r1, r2
9334     //   bCC copy1MBB
9335     //   fallthrough --> copy0MBB
9336     MachineBasicBlock *thisMBB  = BB;
9337     MachineFunction *F = BB->getParent();
9338     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9339     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
9340     F->insert(It, copy0MBB);
9341     F->insert(It, sinkMBB);
9342 
9343     // Check whether CPSR is live past the tMOVCCr_pseudo.
9344     const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
9345     if (!MI.killsRegister(ARM::CPSR) &&
9346         !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
9347       copy0MBB->addLiveIn(ARM::CPSR);
9348       sinkMBB->addLiveIn(ARM::CPSR);
9349     }
9350 
9351     // Transfer the remainder of BB and its successor edges to sinkMBB.
9352     sinkMBB->splice(sinkMBB->begin(), BB,
9353                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9354     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9355 
9356     BB->addSuccessor(copy0MBB);
9357     BB->addSuccessor(sinkMBB);
9358 
9359     BuildMI(BB, dl, TII->get(ARM::tBcc))
9360         .addMBB(sinkMBB)
9361         .addImm(MI.getOperand(3).getImm())
9362         .addReg(MI.getOperand(4).getReg());
9363 
9364     //  copy0MBB:
9365     //   %FalseValue = ...
9366     //   # fallthrough to sinkMBB
9367     BB = copy0MBB;
9368 
9369     // Update machine-CFG edges
9370     BB->addSuccessor(sinkMBB);
9371 
9372     //  sinkMBB:
9373     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9374     //  ...
9375     BB = sinkMBB;
9376     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
9377         .addReg(MI.getOperand(1).getReg())
9378         .addMBB(copy0MBB)
9379         .addReg(MI.getOperand(2).getReg())
9380         .addMBB(thisMBB);
9381 
9382     MI.eraseFromParent(); // The pseudo instruction is gone now.
9383     return BB;
9384   }
9385 
9386   case ARM::BCCi64:
9387   case ARM::BCCZi64: {
9388     // If there is an unconditional branch to the other successor, remove it.
9389     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9390 
9391     // Compare both parts that make up the double comparison separately for
9392     // equality.
9393     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9394 
9395     unsigned LHS1 = MI.getOperand(1).getReg();
9396     unsigned LHS2 = MI.getOperand(2).getReg();
9397     if (RHSisZero) {
9398       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9399           .addReg(LHS1)
9400           .addImm(0)
9401           .add(predOps(ARMCC::AL));
9402       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9403         .addReg(LHS2).addImm(0)
9404         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9405     } else {
9406       unsigned RHS1 = MI.getOperand(3).getReg();
9407       unsigned RHS2 = MI.getOperand(4).getReg();
9408       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9409           .addReg(LHS1)
9410           .addReg(RHS1)
9411           .add(predOps(ARMCC::AL));
9412       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9413         .addReg(LHS2).addReg(RHS2)
9414         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9415     }
9416 
9417     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9418     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9419     if (MI.getOperand(0).getImm() == ARMCC::NE)
9420       std::swap(destMBB, exitMBB);
9421 
9422     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9423       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9424     if (isThumb2)
9425       BuildMI(BB, dl, TII->get(ARM::t2B))
9426           .addMBB(exitMBB)
9427           .add(predOps(ARMCC::AL));
9428     else
9429       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9430 
9431     MI.eraseFromParent(); // The pseudo instruction is gone now.
9432     return BB;
9433   }
9434 
9435   case ARM::Int_eh_sjlj_setjmp:
9436   case ARM::Int_eh_sjlj_setjmp_nofp:
9437   case ARM::tInt_eh_sjlj_setjmp:
9438   case ARM::t2Int_eh_sjlj_setjmp:
9439   case ARM::t2Int_eh_sjlj_setjmp_nofp:
9440     return BB;
9441 
9442   case ARM::Int_eh_sjlj_setup_dispatch:
9443     EmitSjLjDispatchBlock(MI, BB);
9444     return BB;
9445 
9446   case ARM::ABS:
9447   case ARM::t2ABS: {
9448     // To insert an ABS instruction, we have to insert the
9449     // diamond control-flow pattern.  The incoming instruction knows the
9450     // source vreg to test against 0, the destination vreg to set,
9451     // the condition code register to branch on, the
9452     // true/false values to select between, and a branch opcode to use.
9453     // It transforms
9454     //     V1 = ABS V0
9455     // into
9456     //     V2 = MOVS V0
9457     //     BCC                      (branch to SinkBB if V0 >= 0)
9458     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
9459     //     SinkBB: V1 = PHI(V2, V3)
9460     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9461     MachineFunction::iterator BBI = ++BB->getIterator();
9462     MachineFunction *Fn = BB->getParent();
9463     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9464     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
9465     Fn->insert(BBI, RSBBB);
9466     Fn->insert(BBI, SinkBB);
9467 
9468     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9469     unsigned int ABSDstReg = MI.getOperand(0).getReg();
9470     bool ABSSrcKIll = MI.getOperand(1).isKill();
9471     bool isThumb2 = Subtarget->isThumb2();
9472     MachineRegisterInfo &MRI = Fn->getRegInfo();
9473     // In Thumb mode S must not be specified if source register is the SP or
9474     // PC and if destination register is the SP, so restrict register class
9475     unsigned NewRsbDstReg =
9476       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9477 
9478     // Transfer the remainder of BB and its successor edges to sinkMBB.
9479     SinkBB->splice(SinkBB->begin(), BB,
9480                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9481     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9482 
9483     BB->addSuccessor(RSBBB);
9484     BB->addSuccessor(SinkBB);
9485 
9486     // fall through to SinkMBB
9487     RSBBB->addSuccessor(SinkBB);
9488 
9489     // insert a cmp at the end of BB
9490     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9491         .addReg(ABSSrcReg)
9492         .addImm(0)
9493         .add(predOps(ARMCC::AL));
9494 
9495     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9496     BuildMI(BB, dl,
9497       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9498       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9499 
9500     // insert rsbri in RSBBB
9501     // Note: BCC and rsbri will be converted into predicated rsbmi
9502     // by if-conversion pass
9503     BuildMI(*RSBBB, RSBBB->begin(), dl,
9504             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9505         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9506         .addImm(0)
9507         .add(predOps(ARMCC::AL))
9508         .add(condCodeOp());
9509 
9510     // insert PHI in SinkBB,
9511     // reuse ABSDstReg to not change uses of ABS instruction
9512     BuildMI(*SinkBB, SinkBB->begin(), dl,
9513       TII->get(ARM::PHI), ABSDstReg)
9514       .addReg(NewRsbDstReg).addMBB(RSBBB)
9515       .addReg(ABSSrcReg).addMBB(BB);
9516 
9517     // remove ABS instruction
9518     MI.eraseFromParent();
9519 
9520     // return last added BB
9521     return SinkBB;
9522   }
9523   case ARM::COPY_STRUCT_BYVAL_I32:
9524     ++NumLoopByVals;
9525     return EmitStructByval(MI, BB);
9526   case ARM::WIN__CHKSTK:
9527     return EmitLowered__chkstk(MI, BB);
9528   case ARM::WIN__DBZCHK:
9529     return EmitLowered__dbzchk(MI, BB);
9530   }
9531 }
9532 
9533 /// Attaches vregs to MEMCPY that it will use as scratch registers
9534 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9535 /// instead of as a custom inserter because we need the use list from the SDNode.
9536 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9537                                     MachineInstr &MI, const SDNode *Node) {
9538   bool isThumb1 = Subtarget->isThumb1Only();
9539 
9540   DebugLoc DL = MI.getDebugLoc();
9541   MachineFunction *MF = MI.getParent()->getParent();
9542   MachineRegisterInfo &MRI = MF->getRegInfo();
9543   MachineInstrBuilder MIB(*MF, MI);
9544 
9545   // If the new dst/src is unused mark it as dead.
9546   if (!Node->hasAnyUseOfValue(0)) {
9547     MI.getOperand(0).setIsDead(true);
9548   }
9549   if (!Node->hasAnyUseOfValue(1)) {
9550     MI.getOperand(1).setIsDead(true);
9551   }
9552 
9553   // The MEMCPY both defines and kills the scratch registers.
9554   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9555     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9556                                                          : &ARM::GPRRegClass);
9557     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9558   }
9559 }
9560 
9561 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9562                                                       SDNode *Node) const {
9563   if (MI.getOpcode() == ARM::MEMCPY) {
9564     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9565     return;
9566   }
9567 
9568   const MCInstrDesc *MCID = &MI.getDesc();
9569   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9570   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9571   // operand is still set to noreg. If needed, set the optional operand's
9572   // register to CPSR, and remove the redundant implicit def.
9573   //
9574   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
9575 
9576   // Rename pseudo opcodes.
9577   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9578   unsigned ccOutIdx;
9579   if (NewOpc) {
9580     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9581     MCID = &TII->get(NewOpc);
9582 
9583     assert(MCID->getNumOperands() ==
9584            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9585         && "converted opcode should be the same except for cc_out"
9586            " (and, on Thumb1, pred)");
9587 
9588     MI.setDesc(*MCID);
9589 
9590     // Add the optional cc_out operand
9591     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9592 
9593     // On Thumb1, move all input operands to the end, then add the predicate
9594     if (Subtarget->isThumb1Only()) {
9595       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9596         MI.addOperand(MI.getOperand(1));
9597         MI.RemoveOperand(1);
9598       }
9599 
9600       // Restore the ties
9601       for (unsigned i = MI.getNumOperands(); i--;) {
9602         const MachineOperand& op = MI.getOperand(i);
9603         if (op.isReg() && op.isUse()) {
9604           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9605           if (DefIdx != -1)
9606             MI.tieOperands(DefIdx, i);
9607         }
9608       }
9609 
9610       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9611       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9612       ccOutIdx = 1;
9613     } else
9614       ccOutIdx = MCID->getNumOperands() - 1;
9615   } else
9616     ccOutIdx = MCID->getNumOperands() - 1;
9617 
9618   // Any ARM instruction that sets the 's' bit should specify an optional
9619   // "cc_out" operand in the last operand position.
9620   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9621     assert(!NewOpc && "Optional cc_out operand required");
9622     return;
9623   }
9624   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9625   // since we already have an optional CPSR def.
9626   bool definesCPSR = false;
9627   bool deadCPSR = false;
9628   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9629        ++i) {
9630     const MachineOperand &MO = MI.getOperand(i);
9631     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9632       definesCPSR = true;
9633       if (MO.isDead())
9634         deadCPSR = true;
9635       MI.RemoveOperand(i);
9636       break;
9637     }
9638   }
9639   if (!definesCPSR) {
9640     assert(!NewOpc && "Optional cc_out operand required");
9641     return;
9642   }
9643   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9644   if (deadCPSR) {
9645     assert(!MI.getOperand(ccOutIdx).getReg() &&
9646            "expect uninitialized optional cc_out operand");
9647     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9648     if (!Subtarget->isThumb1Only())
9649       return;
9650   }
9651 
9652   // If this instruction was defined with an optional CPSR def and its dag node
9653   // had a live implicit CPSR def, then activate the optional CPSR def.
9654   MachineOperand &MO = MI.getOperand(ccOutIdx);
9655   MO.setReg(ARM::CPSR);
9656   MO.setIsDef(true);
9657 }
9658 
9659 //===----------------------------------------------------------------------===//
9660 //                           ARM Optimization Hooks
9661 //===----------------------------------------------------------------------===//
9662 
9663 // Helper function that checks if N is a null or all ones constant.
9664 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9665   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9666 }
9667 
9668 // Return true if N is conditionally 0 or all ones.
9669 // Detects these expressions where cc is an i1 value:
9670 //
9671 //   (select cc 0, y)   [AllOnes=0]
9672 //   (select cc y, 0)   [AllOnes=0]
9673 //   (zext cc)          [AllOnes=0]
9674 //   (sext cc)          [AllOnes=0/1]
9675 //   (select cc -1, y)  [AllOnes=1]
9676 //   (select cc y, -1)  [AllOnes=1]
9677 //
9678 // Invert is set when N is the null/all ones constant when CC is false.
9679 // OtherOp is set to the alternative value of N.
9680 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9681                                        SDValue &CC, bool &Invert,
9682                                        SDValue &OtherOp,
9683                                        SelectionDAG &DAG) {
9684   switch (N->getOpcode()) {
9685   default: return false;
9686   case ISD::SELECT: {
9687     CC = N->getOperand(0);
9688     SDValue N1 = N->getOperand(1);
9689     SDValue N2 = N->getOperand(2);
9690     if (isZeroOrAllOnes(N1, AllOnes)) {
9691       Invert = false;
9692       OtherOp = N2;
9693       return true;
9694     }
9695     if (isZeroOrAllOnes(N2, AllOnes)) {
9696       Invert = true;
9697       OtherOp = N1;
9698       return true;
9699     }
9700     return false;
9701   }
9702   case ISD::ZERO_EXTEND:
9703     // (zext cc) can never be the all ones value.
9704     if (AllOnes)
9705       return false;
9706     LLVM_FALLTHROUGH;
9707   case ISD::SIGN_EXTEND: {
9708     SDLoc dl(N);
9709     EVT VT = N->getValueType(0);
9710     CC = N->getOperand(0);
9711     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9712       return false;
9713     Invert = !AllOnes;
9714     if (AllOnes)
9715       // When looking for an AllOnes constant, N is an sext, and the 'other'
9716       // value is 0.
9717       OtherOp = DAG.getConstant(0, dl, VT);
9718     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9719       // When looking for a 0 constant, N can be zext or sext.
9720       OtherOp = DAG.getConstant(1, dl, VT);
9721     else
9722       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9723                                 VT);
9724     return true;
9725   }
9726   }
9727 }
9728 
9729 // Combine a constant select operand into its use:
9730 //
9731 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9732 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9733 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9734 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9735 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9736 //
9737 // The transform is rejected if the select doesn't have a constant operand that
9738 // is null, or all ones when AllOnes is set.
9739 //
9740 // Also recognize sext/zext from i1:
9741 //
9742 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9743 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9744 //
9745 // These transformations eventually create predicated instructions.
9746 //
9747 // @param N       The node to transform.
9748 // @param Slct    The N operand that is a select.
9749 // @param OtherOp The other N operand (x above).
9750 // @param DCI     Context.
9751 // @param AllOnes Require the select constant to be all ones instead of null.
9752 // @returns The new node, or SDValue() on failure.
9753 static
9754 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9755                             TargetLowering::DAGCombinerInfo &DCI,
9756                             bool AllOnes = false) {
9757   SelectionDAG &DAG = DCI.DAG;
9758   EVT VT = N->getValueType(0);
9759   SDValue NonConstantVal;
9760   SDValue CCOp;
9761   bool SwapSelectOps;
9762   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9763                                   NonConstantVal, DAG))
9764     return SDValue();
9765 
9766   // Slct is now know to be the desired identity constant when CC is true.
9767   SDValue TrueVal = OtherOp;
9768   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9769                                  OtherOp, NonConstantVal);
9770   // Unless SwapSelectOps says CC should be false.
9771   if (SwapSelectOps)
9772     std::swap(TrueVal, FalseVal);
9773 
9774   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9775                      CCOp, TrueVal, FalseVal);
9776 }
9777 
9778 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9779 static
9780 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9781                                        TargetLowering::DAGCombinerInfo &DCI) {
9782   SDValue N0 = N->getOperand(0);
9783   SDValue N1 = N->getOperand(1);
9784   if (N0.getNode()->hasOneUse())
9785     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9786       return Result;
9787   if (N1.getNode()->hasOneUse())
9788     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9789       return Result;
9790   return SDValue();
9791 }
9792 
9793 static bool IsVUZPShuffleNode(SDNode *N) {
9794   // VUZP shuffle node.
9795   if (N->getOpcode() == ARMISD::VUZP)
9796     return true;
9797 
9798   // "VUZP" on i32 is an alias for VTRN.
9799   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9800     return true;
9801 
9802   return false;
9803 }
9804 
9805 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9806                                  TargetLowering::DAGCombinerInfo &DCI,
9807                                  const ARMSubtarget *Subtarget) {
9808   // Look for ADD(VUZP.0, VUZP.1).
9809   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9810       N0 == N1)
9811    return SDValue();
9812 
9813   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9814   if (!N->getValueType(0).is64BitVector())
9815     return SDValue();
9816 
9817   // Generate vpadd.
9818   SelectionDAG &DAG = DCI.DAG;
9819   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9820   SDLoc dl(N);
9821   SDNode *Unzip = N0.getNode();
9822   EVT VT = N->getValueType(0);
9823 
9824   SmallVector<SDValue, 8> Ops;
9825   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9826                                 TLI.getPointerTy(DAG.getDataLayout())));
9827   Ops.push_back(Unzip->getOperand(0));
9828   Ops.push_back(Unzip->getOperand(1));
9829 
9830   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9831 }
9832 
9833 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9834                                       TargetLowering::DAGCombinerInfo &DCI,
9835                                       const ARMSubtarget *Subtarget) {
9836   // Check for two extended operands.
9837   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9838         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9839       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9840         N1.getOpcode() == ISD::ZERO_EXTEND))
9841     return SDValue();
9842 
9843   SDValue N00 = N0.getOperand(0);
9844   SDValue N10 = N1.getOperand(0);
9845 
9846   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9847   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9848       N00 == N10)
9849     return SDValue();
9850 
9851   // We only recognize Q register paddl here; this can't be reached until
9852   // after type legalization.
9853   if (!N00.getValueType().is64BitVector() ||
9854       !N0.getValueType().is128BitVector())
9855     return SDValue();
9856 
9857   // Generate vpaddl.
9858   SelectionDAG &DAG = DCI.DAG;
9859   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9860   SDLoc dl(N);
9861   EVT VT = N->getValueType(0);
9862 
9863   SmallVector<SDValue, 8> Ops;
9864   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9865   unsigned Opcode;
9866   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9867     Opcode = Intrinsic::arm_neon_vpaddls;
9868   else
9869     Opcode = Intrinsic::arm_neon_vpaddlu;
9870   Ops.push_back(DAG.getConstant(Opcode, dl,
9871                                 TLI.getPointerTy(DAG.getDataLayout())));
9872   EVT ElemTy = N00.getValueType().getVectorElementType();
9873   unsigned NumElts = VT.getVectorNumElements();
9874   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9875   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9876                                N00.getOperand(0), N00.getOperand(1));
9877   Ops.push_back(Concat);
9878 
9879   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9880 }
9881 
9882 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9883 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9884 // much easier to match.
9885 static SDValue
9886 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9887                                TargetLowering::DAGCombinerInfo &DCI,
9888                                const ARMSubtarget *Subtarget) {
9889   // Only perform optimization if after legalize, and if NEON is available. We
9890   // also expected both operands to be BUILD_VECTORs.
9891   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9892       || N0.getOpcode() != ISD::BUILD_VECTOR
9893       || N1.getOpcode() != ISD::BUILD_VECTOR)
9894     return SDValue();
9895 
9896   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9897   EVT VT = N->getValueType(0);
9898   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9899     return SDValue();
9900 
9901   // Check that the vector operands are of the right form.
9902   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9903   // operands, where N is the size of the formed vector.
9904   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9905   // index such that we have a pair wise add pattern.
9906 
9907   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9908   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9909     return SDValue();
9910   SDValue Vec = N0->getOperand(0)->getOperand(0);
9911   SDNode *V = Vec.getNode();
9912   unsigned nextIndex = 0;
9913 
9914   // For each operands to the ADD which are BUILD_VECTORs,
9915   // check to see if each of their operands are an EXTRACT_VECTOR with
9916   // the same vector and appropriate index.
9917   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9918     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9919         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9920 
9921       SDValue ExtVec0 = N0->getOperand(i);
9922       SDValue ExtVec1 = N1->getOperand(i);
9923 
9924       // First operand is the vector, verify its the same.
9925       if (V != ExtVec0->getOperand(0).getNode() ||
9926           V != ExtVec1->getOperand(0).getNode())
9927         return SDValue();
9928 
9929       // Second is the constant, verify its correct.
9930       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9931       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9932 
9933       // For the constant, we want to see all the even or all the odd.
9934       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9935           || C1->getZExtValue() != nextIndex+1)
9936         return SDValue();
9937 
9938       // Increment index.
9939       nextIndex+=2;
9940     } else
9941       return SDValue();
9942   }
9943 
9944   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9945   // we're using the entire input vector, otherwise there's a size/legality
9946   // mismatch somewhere.
9947   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9948       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9949     return SDValue();
9950 
9951   // Create VPADDL node.
9952   SelectionDAG &DAG = DCI.DAG;
9953   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9954 
9955   SDLoc dl(N);
9956 
9957   // Build operand list.
9958   SmallVector<SDValue, 8> Ops;
9959   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9960                                 TLI.getPointerTy(DAG.getDataLayout())));
9961 
9962   // Input is the vector.
9963   Ops.push_back(Vec);
9964 
9965   // Get widened type and narrowed type.
9966   MVT widenType;
9967   unsigned numElem = VT.getVectorNumElements();
9968 
9969   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9970   switch (inputLaneType.getSimpleVT().SimpleTy) {
9971     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9972     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9973     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9974     default:
9975       llvm_unreachable("Invalid vector element type for padd optimization.");
9976   }
9977 
9978   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9979   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9980   return DAG.getNode(ExtOp, dl, VT, tmp);
9981 }
9982 
9983 static SDValue findMUL_LOHI(SDValue V) {
9984   if (V->getOpcode() == ISD::UMUL_LOHI ||
9985       V->getOpcode() == ISD::SMUL_LOHI)
9986     return V;
9987   return SDValue();
9988 }
9989 
9990 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9991                                         TargetLowering::DAGCombinerInfo &DCI,
9992                                         const ARMSubtarget *Subtarget) {
9993   if (Subtarget->isThumb()) {
9994     if (!Subtarget->hasDSP())
9995       return SDValue();
9996   } else if (!Subtarget->hasV5TEOps())
9997     return SDValue();
9998 
9999   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
10000   // accumulates the product into a 64-bit value. The 16-bit values will
10001   // be sign extended somehow or SRA'd into 32-bit values
10002   // (addc (adde (mul 16bit, 16bit), lo), hi)
10003   SDValue Mul = AddcNode->getOperand(0);
10004   SDValue Lo = AddcNode->getOperand(1);
10005   if (Mul.getOpcode() != ISD::MUL) {
10006     Lo = AddcNode->getOperand(0);
10007     Mul = AddcNode->getOperand(1);
10008     if (Mul.getOpcode() != ISD::MUL)
10009       return SDValue();
10010   }
10011 
10012   SDValue SRA = AddeNode->getOperand(0);
10013   SDValue Hi = AddeNode->getOperand(1);
10014   if (SRA.getOpcode() != ISD::SRA) {
10015     SRA = AddeNode->getOperand(1);
10016     Hi = AddeNode->getOperand(0);
10017     if (SRA.getOpcode() != ISD::SRA)
10018       return SDValue();
10019   }
10020   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
10021     if (Const->getZExtValue() != 31)
10022       return SDValue();
10023   } else
10024     return SDValue();
10025 
10026   if (SRA.getOperand(0) != Mul)
10027     return SDValue();
10028 
10029   SelectionDAG &DAG = DCI.DAG;
10030   SDLoc dl(AddcNode);
10031   unsigned Opcode = 0;
10032   SDValue Op0;
10033   SDValue Op1;
10034 
10035   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
10036     Opcode = ARMISD::SMLALBB;
10037     Op0 = Mul.getOperand(0);
10038     Op1 = Mul.getOperand(1);
10039   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
10040     Opcode = ARMISD::SMLALBT;
10041     Op0 = Mul.getOperand(0);
10042     Op1 = Mul.getOperand(1).getOperand(0);
10043   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
10044     Opcode = ARMISD::SMLALTB;
10045     Op0 = Mul.getOperand(0).getOperand(0);
10046     Op1 = Mul.getOperand(1);
10047   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
10048     Opcode = ARMISD::SMLALTT;
10049     Op0 = Mul->getOperand(0).getOperand(0);
10050     Op1 = Mul->getOperand(1).getOperand(0);
10051   }
10052 
10053   if (!Op0 || !Op1)
10054     return SDValue();
10055 
10056   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
10057                               Op0, Op1, Lo, Hi);
10058   // Replace the ADDs' nodes uses by the MLA node's values.
10059   SDValue HiMLALResult(SMLAL.getNode(), 1);
10060   SDValue LoMLALResult(SMLAL.getNode(), 0);
10061 
10062   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
10063   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
10064 
10065   // Return original node to notify the driver to stop replacing.
10066   SDValue resNode(AddcNode, 0);
10067   return resNode;
10068 }
10069 
10070 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
10071                                      TargetLowering::DAGCombinerInfo &DCI,
10072                                      const ARMSubtarget *Subtarget) {
10073   // Look for multiply add opportunities.
10074   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
10075   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
10076   // a glue link from the first add to the second add.
10077   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
10078   // a S/UMLAL instruction.
10079   //                  UMUL_LOHI
10080   //                 / :lo    \ :hi
10081   //                V          \          [no multiline comment]
10082   //    loAdd ->  ADDC         |
10083   //                 \ :carry /
10084   //                  V      V
10085   //                    ADDE   <- hiAdd
10086   //
10087   // In the special case where only the higher part of a signed result is used
10088   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
10089   // a constant with the exact value of 0x80000000, we recognize we are dealing
10090   // with a "rounded multiply and add" (or subtract) and transform it into
10091   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
10092 
10093   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
10094           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
10095          "Expect an ADDE or SUBE");
10096 
10097   assert(AddeSubeNode->getNumOperands() == 3 &&
10098          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
10099          "ADDE node has the wrong inputs");
10100 
10101   // Check that we are chained to the right ADDC or SUBC node.
10102   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
10103   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10104        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
10105       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
10106        AddcSubcNode->getOpcode() != ARMISD::SUBC))
10107     return SDValue();
10108 
10109   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
10110   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
10111 
10112   // Check if the two operands are from the same mul_lohi node.
10113   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
10114     return SDValue();
10115 
10116   assert(AddcSubcNode->getNumValues() == 2 &&
10117          AddcSubcNode->getValueType(0) == MVT::i32 &&
10118          "Expect ADDC with two result values. First: i32");
10119 
10120   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
10121   // maybe a SMLAL which multiplies two 16-bit values.
10122   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10123       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
10124       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
10125       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
10126       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
10127     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
10128 
10129   // Check for the triangle shape.
10130   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
10131   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
10132 
10133   // Make sure that the ADDE/SUBE operands are not coming from the same node.
10134   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
10135     return SDValue();
10136 
10137   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
10138   bool IsLeftOperandMUL = false;
10139   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
10140   if (MULOp == SDValue())
10141     MULOp = findMUL_LOHI(AddeSubeOp1);
10142   else
10143     IsLeftOperandMUL = true;
10144   if (MULOp == SDValue())
10145     return SDValue();
10146 
10147   // Figure out the right opcode.
10148   unsigned Opc = MULOp->getOpcode();
10149   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
10150 
10151   // Figure out the high and low input values to the MLAL node.
10152   SDValue *HiAddSub = nullptr;
10153   SDValue *LoMul = nullptr;
10154   SDValue *LowAddSub = nullptr;
10155 
10156   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
10157   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
10158     return SDValue();
10159 
10160   if (IsLeftOperandMUL)
10161     HiAddSub = &AddeSubeOp1;
10162   else
10163     HiAddSub = &AddeSubeOp0;
10164 
10165   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
10166   // whose low result is fed to the ADDC/SUBC we are checking.
10167 
10168   if (AddcSubcOp0 == MULOp.getValue(0)) {
10169     LoMul = &AddcSubcOp0;
10170     LowAddSub = &AddcSubcOp1;
10171   }
10172   if (AddcSubcOp1 == MULOp.getValue(0)) {
10173     LoMul = &AddcSubcOp1;
10174     LowAddSub = &AddcSubcOp0;
10175   }
10176 
10177   if (!LoMul)
10178     return SDValue();
10179 
10180   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
10181   // the replacement below will create a cycle.
10182   if (AddcSubcNode == HiAddSub->getNode() ||
10183       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
10184     return SDValue();
10185 
10186   // Create the merged node.
10187   SelectionDAG &DAG = DCI.DAG;
10188 
10189   // Start building operand list.
10190   SmallVector<SDValue, 8> Ops;
10191   Ops.push_back(LoMul->getOperand(0));
10192   Ops.push_back(LoMul->getOperand(1));
10193 
10194   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
10195   // the case, we must be doing signed multiplication and only use the higher
10196   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
10197   // addition or subtraction with the value of 0x800000.
10198   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
10199       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
10200       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
10201       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
10202           0x80000000) {
10203     Ops.push_back(*HiAddSub);
10204     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
10205       FinalOpc = ARMISD::SMMLSR;
10206     } else {
10207       FinalOpc = ARMISD::SMMLAR;
10208     }
10209     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
10210     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
10211 
10212     return SDValue(AddeSubeNode, 0);
10213   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
10214     // SMMLS is generated during instruction selection and the rest of this
10215     // function can not handle the case where AddcSubcNode is a SUBC.
10216     return SDValue();
10217 
10218   // Finish building the operand list for {U/S}MLAL
10219   Ops.push_back(*LowAddSub);
10220   Ops.push_back(*HiAddSub);
10221 
10222   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
10223                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10224 
10225   // Replace the ADDs' nodes uses by the MLA node's values.
10226   SDValue HiMLALResult(MLALNode.getNode(), 1);
10227   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
10228 
10229   SDValue LoMLALResult(MLALNode.getNode(), 0);
10230   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
10231 
10232   // Return original node to notify the driver to stop replacing.
10233   return SDValue(AddeSubeNode, 0);
10234 }
10235 
10236 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
10237                                       TargetLowering::DAGCombinerInfo &DCI,
10238                                       const ARMSubtarget *Subtarget) {
10239   // UMAAL is similar to UMLAL except that it adds two unsigned values.
10240   // While trying to combine for the other MLAL nodes, first search for the
10241   // chance to use UMAAL. Check if Addc uses a node which has already
10242   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
10243   // as the addend, and it's handled in PerformUMLALCombine.
10244 
10245   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10246     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10247 
10248   // Check that we have a glued ADDC node.
10249   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
10250   if (AddcNode->getOpcode() != ARMISD::ADDC)
10251     return SDValue();
10252 
10253   // Find the converted UMAAL or quit if it doesn't exist.
10254   SDNode *UmlalNode = nullptr;
10255   SDValue AddHi;
10256   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
10257     UmlalNode = AddcNode->getOperand(0).getNode();
10258     AddHi = AddcNode->getOperand(1);
10259   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
10260     UmlalNode = AddcNode->getOperand(1).getNode();
10261     AddHi = AddcNode->getOperand(0);
10262   } else {
10263     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10264   }
10265 
10266   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
10267   // the ADDC as well as Zero.
10268   if (!isNullConstant(UmlalNode->getOperand(3)))
10269     return SDValue();
10270 
10271   if ((isNullConstant(AddeNode->getOperand(0)) &&
10272        AddeNode->getOperand(1).getNode() == UmlalNode) ||
10273       (AddeNode->getOperand(0).getNode() == UmlalNode &&
10274        isNullConstant(AddeNode->getOperand(1)))) {
10275     SelectionDAG &DAG = DCI.DAG;
10276     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
10277                       UmlalNode->getOperand(2), AddHi };
10278     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
10279                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10280 
10281     // Replace the ADDs' nodes uses by the UMAAL node's values.
10282     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
10283     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
10284 
10285     // Return original node to notify the driver to stop replacing.
10286     return SDValue(AddeNode, 0);
10287   }
10288   return SDValue();
10289 }
10290 
10291 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
10292                                    const ARMSubtarget *Subtarget) {
10293   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10294     return SDValue();
10295 
10296   // Check that we have a pair of ADDC and ADDE as operands.
10297   // Both addends of the ADDE must be zero.
10298   SDNode* AddcNode = N->getOperand(2).getNode();
10299   SDNode* AddeNode = N->getOperand(3).getNode();
10300   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
10301       (AddeNode->getOpcode() == ARMISD::ADDE) &&
10302       isNullConstant(AddeNode->getOperand(0)) &&
10303       isNullConstant(AddeNode->getOperand(1)) &&
10304       (AddeNode->getOperand(2).getNode() == AddcNode))
10305     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
10306                        DAG.getVTList(MVT::i32, MVT::i32),
10307                        {N->getOperand(0), N->getOperand(1),
10308                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
10309   else
10310     return SDValue();
10311 }
10312 
10313 static SDValue PerformAddcSubcCombine(SDNode *N,
10314                                       TargetLowering::DAGCombinerInfo &DCI,
10315                                       const ARMSubtarget *Subtarget) {
10316   SelectionDAG &DAG(DCI.DAG);
10317 
10318   if (N->getOpcode() == ARMISD::SUBC) {
10319     // (SUBC (ADDE 0, 0, C), 1) -> C
10320     SDValue LHS = N->getOperand(0);
10321     SDValue RHS = N->getOperand(1);
10322     if (LHS->getOpcode() == ARMISD::ADDE &&
10323         isNullConstant(LHS->getOperand(0)) &&
10324         isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
10325       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
10326     }
10327   }
10328 
10329   if (Subtarget->isThumb1Only()) {
10330     SDValue RHS = N->getOperand(1);
10331     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10332       int32_t imm = C->getSExtValue();
10333       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
10334         SDLoc DL(N);
10335         RHS = DAG.getConstant(-imm, DL, MVT::i32);
10336         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
10337                                                            : ARMISD::ADDC;
10338         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
10339       }
10340     }
10341   }
10342 
10343   return SDValue();
10344 }
10345 
10346 static SDValue PerformAddeSubeCombine(SDNode *N,
10347                                       TargetLowering::DAGCombinerInfo &DCI,
10348                                       const ARMSubtarget *Subtarget) {
10349   if (Subtarget->isThumb1Only()) {
10350     SelectionDAG &DAG = DCI.DAG;
10351     SDValue RHS = N->getOperand(1);
10352     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10353       int64_t imm = C->getSExtValue();
10354       if (imm < 0) {
10355         SDLoc DL(N);
10356 
10357         // The with-carry-in form matches bitwise not instead of the negation.
10358         // Effectively, the inverse interpretation of the carry flag already
10359         // accounts for part of the negation.
10360         RHS = DAG.getConstant(~imm, DL, MVT::i32);
10361 
10362         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
10363                                                            : ARMISD::ADDE;
10364         return DAG.getNode(Opcode, DL, N->getVTList(),
10365                            N->getOperand(0), RHS, N->getOperand(2));
10366       }
10367     }
10368   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
10369     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
10370   }
10371   return SDValue();
10372 }
10373 
10374 /// PerformADDECombine - Target-specific dag combine transform from
10375 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
10376 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
10377 static SDValue PerformADDECombine(SDNode *N,
10378                                   TargetLowering::DAGCombinerInfo &DCI,
10379                                   const ARMSubtarget *Subtarget) {
10380   // Only ARM and Thumb2 support UMLAL/SMLAL.
10381   if (Subtarget->isThumb1Only())
10382     return PerformAddeSubeCombine(N, DCI, Subtarget);
10383 
10384   // Only perform the checks after legalize when the pattern is available.
10385   if (DCI.isBeforeLegalize()) return SDValue();
10386 
10387   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
10388 }
10389 
10390 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
10391 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
10392 /// called with the default operands, and if that fails, with commuted
10393 /// operands.
10394 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
10395                                           TargetLowering::DAGCombinerInfo &DCI,
10396                                           const ARMSubtarget *Subtarget){
10397   // Attempt to create vpadd for this add.
10398   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
10399     return Result;
10400 
10401   // Attempt to create vpaddl for this add.
10402   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
10403     return Result;
10404   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
10405                                                       Subtarget))
10406     return Result;
10407 
10408   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10409   if (N0.getNode()->hasOneUse())
10410     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
10411       return Result;
10412   return SDValue();
10413 }
10414 
10415 bool
10416 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
10417                                                  CombineLevel Level) const {
10418   if (Level == BeforeLegalizeTypes)
10419     return true;
10420 
10421   if (Subtarget->isThumb() && Subtarget->isThumb1Only())
10422     return true;
10423 
10424   if (N->getOpcode() != ISD::SHL)
10425     return true;
10426 
10427   // Turn off commute-with-shift transform after legalization, so it doesn't
10428   // conflict with PerformSHLSimplify.  (We could try to detect when
10429   // PerformSHLSimplify would trigger more precisely, but it isn't
10430   // really necessary.)
10431   return false;
10432 }
10433 
10434 static SDValue PerformSHLSimplify(SDNode *N,
10435                                 TargetLowering::DAGCombinerInfo &DCI,
10436                                 const ARMSubtarget *ST) {
10437   // Allow the generic combiner to identify potential bswaps.
10438   if (DCI.isBeforeLegalize())
10439     return SDValue();
10440 
10441   // DAG combiner will fold:
10442   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
10443   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
10444   // Other code patterns that can be also be modified have the following form:
10445   // b + ((a << 1) | 510)
10446   // b + ((a << 1) & 510)
10447   // b + ((a << 1) ^ 510)
10448   // b + ((a << 1) + 510)
10449 
10450   // Many instructions can  perform the shift for free, but it requires both
10451   // the operands to be registers. If c1 << c2 is too large, a mov immediate
10452   // instruction will needed. So, unfold back to the original pattern if:
10453   // - if c1 and c2 are small enough that they don't require mov imms.
10454   // - the user(s) of the node can perform an shl
10455 
10456   // No shifted operands for 16-bit instructions.
10457   if (ST->isThumb() && ST->isThumb1Only())
10458     return SDValue();
10459 
10460   // Check that all the users could perform the shl themselves.
10461   for (auto U : N->uses()) {
10462     switch(U->getOpcode()) {
10463     default:
10464       return SDValue();
10465     case ISD::SUB:
10466     case ISD::ADD:
10467     case ISD::AND:
10468     case ISD::OR:
10469     case ISD::XOR:
10470     case ISD::SETCC:
10471     case ARMISD::CMP:
10472       // Check that the user isn't already using a constant because there
10473       // aren't any instructions that support an immediate operand and a
10474       // shifted operand.
10475       if (isa<ConstantSDNode>(U->getOperand(0)) ||
10476           isa<ConstantSDNode>(U->getOperand(1)))
10477         return SDValue();
10478 
10479       // Check that it's not already using a shift.
10480       if (U->getOperand(0).getOpcode() == ISD::SHL ||
10481           U->getOperand(1).getOpcode() == ISD::SHL)
10482         return SDValue();
10483       break;
10484     }
10485   }
10486 
10487   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
10488       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
10489     return SDValue();
10490 
10491   if (N->getOperand(0).getOpcode() != ISD::SHL)
10492     return SDValue();
10493 
10494   SDValue SHL = N->getOperand(0);
10495 
10496   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
10497   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
10498   if (!C1ShlC2 || !C2)
10499     return SDValue();
10500 
10501   APInt C2Int = C2->getAPIntValue();
10502   APInt C1Int = C1ShlC2->getAPIntValue();
10503 
10504   // Check that performing a lshr will not lose any information.
10505   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
10506                                      C2Int.getBitWidth() - C2->getZExtValue());
10507   if ((C1Int & Mask) != C1Int)
10508     return SDValue();
10509 
10510   // Shift the first constant.
10511   C1Int.lshrInPlace(C2Int);
10512 
10513   // The immediates are encoded as an 8-bit value that can be rotated.
10514   auto LargeImm = [](const APInt &Imm) {
10515     unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
10516     return Imm.getBitWidth() - Zeros > 8;
10517   };
10518 
10519   if (LargeImm(C1Int) || LargeImm(C2Int))
10520     return SDValue();
10521 
10522   SelectionDAG &DAG = DCI.DAG;
10523   SDLoc dl(N);
10524   SDValue X = SHL.getOperand(0);
10525   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
10526                               DAG.getConstant(C1Int, dl, MVT::i32));
10527   // Shift left to compensate for the lshr of C1Int.
10528   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
10529 
10530   LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
10531              SHL.dump(); N->dump());
10532   LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
10533   return Res;
10534 }
10535 
10536 
10537 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
10538 ///
10539 static SDValue PerformADDCombine(SDNode *N,
10540                                  TargetLowering::DAGCombinerInfo &DCI,
10541                                  const ARMSubtarget *Subtarget) {
10542   SDValue N0 = N->getOperand(0);
10543   SDValue N1 = N->getOperand(1);
10544 
10545   // Only works one way, because it needs an immediate operand.
10546   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10547     return Result;
10548 
10549   // First try with the default operand order.
10550   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
10551     return Result;
10552 
10553   // If that didn't work, try again with the operands commuted.
10554   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
10555 }
10556 
10557 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
10558 ///
10559 static SDValue PerformSUBCombine(SDNode *N,
10560                                  TargetLowering::DAGCombinerInfo &DCI) {
10561   SDValue N0 = N->getOperand(0);
10562   SDValue N1 = N->getOperand(1);
10563 
10564   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10565   if (N1.getNode()->hasOneUse())
10566     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10567       return Result;
10568 
10569   return SDValue();
10570 }
10571 
10572 /// PerformVMULCombine
10573 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10574 /// special multiplier accumulator forwarding.
10575 ///   vmul d3, d0, d2
10576 ///   vmla d3, d1, d2
10577 /// is faster than
10578 ///   vadd d3, d0, d1
10579 ///   vmul d3, d3, d2
10580 //  However, for (A + B) * (A + B),
10581 //    vadd d2, d0, d1
10582 //    vmul d3, d0, d2
10583 //    vmla d3, d1, d2
10584 //  is slower than
10585 //    vadd d2, d0, d1
10586 //    vmul d3, d2, d2
10587 static SDValue PerformVMULCombine(SDNode *N,
10588                                   TargetLowering::DAGCombinerInfo &DCI,
10589                                   const ARMSubtarget *Subtarget) {
10590   if (!Subtarget->hasVMLxForwarding())
10591     return SDValue();
10592 
10593   SelectionDAG &DAG = DCI.DAG;
10594   SDValue N0 = N->getOperand(0);
10595   SDValue N1 = N->getOperand(1);
10596   unsigned Opcode = N0.getOpcode();
10597   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10598       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10599     Opcode = N1.getOpcode();
10600     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10601         Opcode != ISD::FADD && Opcode != ISD::FSUB)
10602       return SDValue();
10603     std::swap(N0, N1);
10604   }
10605 
10606   if (N0 == N1)
10607     return SDValue();
10608 
10609   EVT VT = N->getValueType(0);
10610   SDLoc DL(N);
10611   SDValue N00 = N0->getOperand(0);
10612   SDValue N01 = N0->getOperand(1);
10613   return DAG.getNode(Opcode, DL, VT,
10614                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10615                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10616 }
10617 
10618 static SDValue PerformMULCombine(SDNode *N,
10619                                  TargetLowering::DAGCombinerInfo &DCI,
10620                                  const ARMSubtarget *Subtarget) {
10621   SelectionDAG &DAG = DCI.DAG;
10622 
10623   if (Subtarget->isThumb1Only())
10624     return SDValue();
10625 
10626   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10627     return SDValue();
10628 
10629   EVT VT = N->getValueType(0);
10630   if (VT.is64BitVector() || VT.is128BitVector())
10631     return PerformVMULCombine(N, DCI, Subtarget);
10632   if (VT != MVT::i32)
10633     return SDValue();
10634 
10635   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10636   if (!C)
10637     return SDValue();
10638 
10639   int64_t MulAmt = C->getSExtValue();
10640   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10641 
10642   ShiftAmt = ShiftAmt & (32 - 1);
10643   SDValue V = N->getOperand(0);
10644   SDLoc DL(N);
10645 
10646   SDValue Res;
10647   MulAmt >>= ShiftAmt;
10648 
10649   if (MulAmt >= 0) {
10650     if (isPowerOf2_32(MulAmt - 1)) {
10651       // (mul x, 2^N + 1) => (add (shl x, N), x)
10652       Res = DAG.getNode(ISD::ADD, DL, VT,
10653                         V,
10654                         DAG.getNode(ISD::SHL, DL, VT,
10655                                     V,
10656                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
10657                                                     MVT::i32)));
10658     } else if (isPowerOf2_32(MulAmt + 1)) {
10659       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10660       Res = DAG.getNode(ISD::SUB, DL, VT,
10661                         DAG.getNode(ISD::SHL, DL, VT,
10662                                     V,
10663                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10664                                                     MVT::i32)),
10665                         V);
10666     } else
10667       return SDValue();
10668   } else {
10669     uint64_t MulAmtAbs = -MulAmt;
10670     if (isPowerOf2_32(MulAmtAbs + 1)) {
10671       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10672       Res = DAG.getNode(ISD::SUB, DL, VT,
10673                         V,
10674                         DAG.getNode(ISD::SHL, DL, VT,
10675                                     V,
10676                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10677                                                     MVT::i32)));
10678     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10679       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10680       Res = DAG.getNode(ISD::ADD, DL, VT,
10681                         V,
10682                         DAG.getNode(ISD::SHL, DL, VT,
10683                                     V,
10684                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10685                                                     MVT::i32)));
10686       Res = DAG.getNode(ISD::SUB, DL, VT,
10687                         DAG.getConstant(0, DL, MVT::i32), Res);
10688     } else
10689       return SDValue();
10690   }
10691 
10692   if (ShiftAmt != 0)
10693     Res = DAG.getNode(ISD::SHL, DL, VT,
10694                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10695 
10696   // Do not add new nodes to DAG combiner worklist.
10697   DCI.CombineTo(N, Res, false);
10698   return SDValue();
10699 }
10700 
10701 static SDValue CombineANDShift(SDNode *N,
10702                                TargetLowering::DAGCombinerInfo &DCI,
10703                                const ARMSubtarget *Subtarget) {
10704   // Allow DAGCombine to pattern-match before we touch the canonical form.
10705   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10706     return SDValue();
10707 
10708   if (N->getValueType(0) != MVT::i32)
10709     return SDValue();
10710 
10711   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10712   if (!N1C)
10713     return SDValue();
10714 
10715   uint32_t C1 = (uint32_t)N1C->getZExtValue();
10716   // Don't transform uxtb/uxth.
10717   if (C1 == 255 || C1 == 65535)
10718     return SDValue();
10719 
10720   SDNode *N0 = N->getOperand(0).getNode();
10721   if (!N0->hasOneUse())
10722     return SDValue();
10723 
10724   if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
10725     return SDValue();
10726 
10727   bool LeftShift = N0->getOpcode() == ISD::SHL;
10728 
10729   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10730   if (!N01C)
10731     return SDValue();
10732 
10733   uint32_t C2 = (uint32_t)N01C->getZExtValue();
10734   if (!C2 || C2 >= 32)
10735     return SDValue();
10736 
10737   SelectionDAG &DAG = DCI.DAG;
10738   SDLoc DL(N);
10739 
10740   // We have a pattern of the form "(and (shl x, c2) c1)" or
10741   // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
10742   // transform to a pair of shifts, to save materializing c1.
10743 
10744   // First pattern: right shift, and c1+1 is a power of two.
10745   // FIXME: Also check reversed pattern (left shift, and ~c1+1 is a power
10746   // of two).
10747   // FIXME: Use demanded bits?
10748   if (!LeftShift && isMask_32(C1)) {
10749     uint32_t C3 = countLeadingZeros(C1);
10750     if (C2 < C3) {
10751       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
10752                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
10753       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
10754                          DAG.getConstant(C3, DL, MVT::i32));
10755     }
10756   }
10757 
10758   // Second pattern: left shift, and (c1>>c2)+1 is a power of two.
10759   // FIXME: Also check reversed pattern (right shift, and ~(c1<<c2)+1
10760   // is a power of two).
10761   // FIXME: Use demanded bits?
10762   if (LeftShift && isShiftedMask_32(C1)) {
10763     uint32_t C3 = countLeadingZeros(C1);
10764     if (C2 + C3 < 32 && C1 == ((-1U << (C2 + C3)) >> C3)) {
10765       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
10766                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
10767       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
10768                         DAG.getConstant(C3, DL, MVT::i32));
10769     }
10770   }
10771 
10772   // FIXME: Transform "(and (shl x, c2) c1)" ->
10773   // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
10774   // c1.
10775   return SDValue();
10776 }
10777 
10778 static SDValue PerformANDCombine(SDNode *N,
10779                                  TargetLowering::DAGCombinerInfo &DCI,
10780                                  const ARMSubtarget *Subtarget) {
10781   // Attempt to use immediate-form VBIC
10782   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10783   SDLoc dl(N);
10784   EVT VT = N->getValueType(0);
10785   SelectionDAG &DAG = DCI.DAG;
10786 
10787   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10788     return SDValue();
10789 
10790   APInt SplatBits, SplatUndef;
10791   unsigned SplatBitSize;
10792   bool HasAnyUndefs;
10793   if (BVN &&
10794       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10795     if (SplatBitSize <= 64) {
10796       EVT VbicVT;
10797       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10798                                       SplatUndef.getZExtValue(), SplatBitSize,
10799                                       DAG, dl, VbicVT, VT.is128BitVector(),
10800                                       OtherModImm);
10801       if (Val.getNode()) {
10802         SDValue Input =
10803           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10804         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10805         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10806       }
10807     }
10808   }
10809 
10810   if (!Subtarget->isThumb1Only()) {
10811     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10812     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10813       return Result;
10814 
10815     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10816       return Result;
10817   }
10818 
10819   if (Subtarget->isThumb1Only())
10820     if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
10821       return Result;
10822 
10823   return SDValue();
10824 }
10825 
10826 // Try combining OR nodes to SMULWB, SMULWT.
10827 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10828                                          TargetLowering::DAGCombinerInfo &DCI,
10829                                          const ARMSubtarget *Subtarget) {
10830   if (!Subtarget->hasV6Ops() ||
10831       (Subtarget->isThumb() &&
10832        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10833     return SDValue();
10834 
10835   SDValue SRL = OR->getOperand(0);
10836   SDValue SHL = OR->getOperand(1);
10837 
10838   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10839     SRL = OR->getOperand(1);
10840     SHL = OR->getOperand(0);
10841   }
10842   if (!isSRL16(SRL) || !isSHL16(SHL))
10843     return SDValue();
10844 
10845   // The first operands to the shifts need to be the two results from the
10846   // same smul_lohi node.
10847   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10848        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10849     return SDValue();
10850 
10851   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10852   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10853       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10854     return SDValue();
10855 
10856   // Now we have:
10857   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10858   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10859   // For SMUWB the 16-bit value will signed extended somehow.
10860   // For SMULWT only the SRA is required.
10861   // Check both sides of SMUL_LOHI
10862   SDValue OpS16 = SMULLOHI->getOperand(0);
10863   SDValue OpS32 = SMULLOHI->getOperand(1);
10864 
10865   SelectionDAG &DAG = DCI.DAG;
10866   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10867     OpS16 = OpS32;
10868     OpS32 = SMULLOHI->getOperand(0);
10869   }
10870 
10871   SDLoc dl(OR);
10872   unsigned Opcode = 0;
10873   if (isS16(OpS16, DAG))
10874     Opcode = ARMISD::SMULWB;
10875   else if (isSRA16(OpS16)) {
10876     Opcode = ARMISD::SMULWT;
10877     OpS16 = OpS16->getOperand(0);
10878   }
10879   else
10880     return SDValue();
10881 
10882   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10883   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10884   return SDValue(OR, 0);
10885 }
10886 
10887 static SDValue PerformORCombineToBFI(SDNode *N,
10888                                      TargetLowering::DAGCombinerInfo &DCI,
10889                                      const ARMSubtarget *Subtarget) {
10890   // BFI is only available on V6T2+
10891   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10892     return SDValue();
10893 
10894   EVT VT = N->getValueType(0);
10895   SDValue N0 = N->getOperand(0);
10896   SDValue N1 = N->getOperand(1);
10897   SelectionDAG &DAG = DCI.DAG;
10898   SDLoc DL(N);
10899   // 1) or (and A, mask), val => ARMbfi A, val, mask
10900   //      iff (val & mask) == val
10901   //
10902   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10903   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10904   //          && mask == ~mask2
10905   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10906   //          && ~mask == mask2
10907   //  (i.e., copy a bitfield value into another bitfield of the same width)
10908 
10909   if (VT != MVT::i32)
10910     return SDValue();
10911 
10912   SDValue N00 = N0.getOperand(0);
10913 
10914   // The value and the mask need to be constants so we can verify this is
10915   // actually a bitfield set. If the mask is 0xffff, we can do better
10916   // via a movt instruction, so don't use BFI in that case.
10917   SDValue MaskOp = N0.getOperand(1);
10918   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10919   if (!MaskC)
10920     return SDValue();
10921   unsigned Mask = MaskC->getZExtValue();
10922   if (Mask == 0xffff)
10923     return SDValue();
10924   SDValue Res;
10925   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10926   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10927   if (N1C) {
10928     unsigned Val = N1C->getZExtValue();
10929     if ((Val & ~Mask) != Val)
10930       return SDValue();
10931 
10932     if (ARM::isBitFieldInvertedMask(Mask)) {
10933       Val >>= countTrailingZeros(~Mask);
10934 
10935       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10936                         DAG.getConstant(Val, DL, MVT::i32),
10937                         DAG.getConstant(Mask, DL, MVT::i32));
10938 
10939       DCI.CombineTo(N, Res, false);
10940       // Return value from the original node to inform the combiner than N is
10941       // now dead.
10942       return SDValue(N, 0);
10943     }
10944   } else if (N1.getOpcode() == ISD::AND) {
10945     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10946     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10947     if (!N11C)
10948       return SDValue();
10949     unsigned Mask2 = N11C->getZExtValue();
10950 
10951     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10952     // as is to match.
10953     if (ARM::isBitFieldInvertedMask(Mask) &&
10954         (Mask == ~Mask2)) {
10955       // The pack halfword instruction works better for masks that fit it,
10956       // so use that when it's available.
10957       if (Subtarget->hasDSP() &&
10958           (Mask == 0xffff || Mask == 0xffff0000))
10959         return SDValue();
10960       // 2a
10961       unsigned amt = countTrailingZeros(Mask2);
10962       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10963                         DAG.getConstant(amt, DL, MVT::i32));
10964       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10965                         DAG.getConstant(Mask, DL, MVT::i32));
10966       DCI.CombineTo(N, Res, false);
10967       // Return value from the original node to inform the combiner than N is
10968       // now dead.
10969       return SDValue(N, 0);
10970     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10971                (~Mask == Mask2)) {
10972       // The pack halfword instruction works better for masks that fit it,
10973       // so use that when it's available.
10974       if (Subtarget->hasDSP() &&
10975           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10976         return SDValue();
10977       // 2b
10978       unsigned lsb = countTrailingZeros(Mask);
10979       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10980                         DAG.getConstant(lsb, DL, MVT::i32));
10981       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10982                         DAG.getConstant(Mask2, DL, MVT::i32));
10983       DCI.CombineTo(N, Res, false);
10984       // Return value from the original node to inform the combiner than N is
10985       // now dead.
10986       return SDValue(N, 0);
10987     }
10988   }
10989 
10990   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10991       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10992       ARM::isBitFieldInvertedMask(~Mask)) {
10993     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10994     // where lsb(mask) == #shamt and masked bits of B are known zero.
10995     SDValue ShAmt = N00.getOperand(1);
10996     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10997     unsigned LSB = countTrailingZeros(Mask);
10998     if (ShAmtC != LSB)
10999       return SDValue();
11000 
11001     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
11002                       DAG.getConstant(~Mask, DL, MVT::i32));
11003 
11004     DCI.CombineTo(N, Res, false);
11005     // Return value from the original node to inform the combiner than N is
11006     // now dead.
11007     return SDValue(N, 0);
11008   }
11009 
11010   return SDValue();
11011 }
11012 
11013 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
11014 static SDValue PerformORCombine(SDNode *N,
11015                                 TargetLowering::DAGCombinerInfo &DCI,
11016                                 const ARMSubtarget *Subtarget) {
11017   // Attempt to use immediate-form VORR
11018   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11019   SDLoc dl(N);
11020   EVT VT = N->getValueType(0);
11021   SelectionDAG &DAG = DCI.DAG;
11022 
11023   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11024     return SDValue();
11025 
11026   APInt SplatBits, SplatUndef;
11027   unsigned SplatBitSize;
11028   bool HasAnyUndefs;
11029   if (BVN && Subtarget->hasNEON() &&
11030       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11031     if (SplatBitSize <= 64) {
11032       EVT VorrVT;
11033       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
11034                                       SplatUndef.getZExtValue(), SplatBitSize,
11035                                       DAG, dl, VorrVT, VT.is128BitVector(),
11036                                       OtherModImm);
11037       if (Val.getNode()) {
11038         SDValue Input =
11039           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
11040         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
11041         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
11042       }
11043     }
11044   }
11045 
11046   if (!Subtarget->isThumb1Only()) {
11047     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
11048     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11049       return Result;
11050     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
11051       return Result;
11052   }
11053 
11054   SDValue N0 = N->getOperand(0);
11055   SDValue N1 = N->getOperand(1);
11056 
11057   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
11058   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
11059       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11060 
11061     // The code below optimizes (or (and X, Y), Z).
11062     // The AND operand needs to have a single user to make these optimizations
11063     // profitable.
11064     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
11065       return SDValue();
11066 
11067     APInt SplatUndef;
11068     unsigned SplatBitSize;
11069     bool HasAnyUndefs;
11070 
11071     APInt SplatBits0, SplatBits1;
11072     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
11073     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
11074     // Ensure that the second operand of both ands are constants
11075     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
11076                                       HasAnyUndefs) && !HasAnyUndefs) {
11077         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
11078                                           HasAnyUndefs) && !HasAnyUndefs) {
11079             // Ensure that the bit width of the constants are the same and that
11080             // the splat arguments are logical inverses as per the pattern we
11081             // are trying to simplify.
11082             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
11083                 SplatBits0 == ~SplatBits1) {
11084                 // Canonicalize the vector type to make instruction selection
11085                 // simpler.
11086                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
11087                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
11088                                              N0->getOperand(1),
11089                                              N0->getOperand(0),
11090                                              N1->getOperand(0));
11091                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11092             }
11093         }
11094     }
11095   }
11096 
11097   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
11098   // reasonable.
11099   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
11100     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
11101       return Res;
11102   }
11103 
11104   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11105     return Result;
11106 
11107   return SDValue();
11108 }
11109 
11110 static SDValue PerformXORCombine(SDNode *N,
11111                                  TargetLowering::DAGCombinerInfo &DCI,
11112                                  const ARMSubtarget *Subtarget) {
11113   EVT VT = N->getValueType(0);
11114   SelectionDAG &DAG = DCI.DAG;
11115 
11116   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11117     return SDValue();
11118 
11119   if (!Subtarget->isThumb1Only()) {
11120     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
11121     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11122       return Result;
11123 
11124     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11125       return Result;
11126   }
11127 
11128   return SDValue();
11129 }
11130 
11131 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
11132 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
11133 // their position in "to" (Rd).
11134 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
11135   assert(N->getOpcode() == ARMISD::BFI);
11136 
11137   SDValue From = N->getOperand(1);
11138   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
11139   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
11140 
11141   // If the Base came from a SHR #C, we can deduce that it is really testing bit
11142   // #C in the base of the SHR.
11143   if (From->getOpcode() == ISD::SRL &&
11144       isa<ConstantSDNode>(From->getOperand(1))) {
11145     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
11146     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
11147     FromMask <<= Shift.getLimitedValue(31);
11148     From = From->getOperand(0);
11149   }
11150 
11151   return From;
11152 }
11153 
11154 // If A and B contain one contiguous set of bits, does A | B == A . B?
11155 //
11156 // Neither A nor B must be zero.
11157 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
11158   unsigned LastActiveBitInA =  A.countTrailingZeros();
11159   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
11160   return LastActiveBitInA - 1 == FirstActiveBitInB;
11161 }
11162 
11163 static SDValue FindBFIToCombineWith(SDNode *N) {
11164   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
11165   // if one exists.
11166   APInt ToMask, FromMask;
11167   SDValue From = ParseBFI(N, ToMask, FromMask);
11168   SDValue To = N->getOperand(0);
11169 
11170   // Now check for a compatible BFI to merge with. We can pass through BFIs that
11171   // aren't compatible, but not if they set the same bit in their destination as
11172   // we do (or that of any BFI we're going to combine with).
11173   SDValue V = To;
11174   APInt CombinedToMask = ToMask;
11175   while (V.getOpcode() == ARMISD::BFI) {
11176     APInt NewToMask, NewFromMask;
11177     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
11178     if (NewFrom != From) {
11179       // This BFI has a different base. Keep going.
11180       CombinedToMask |= NewToMask;
11181       V = V.getOperand(0);
11182       continue;
11183     }
11184 
11185     // Do the written bits conflict with any we've seen so far?
11186     if ((NewToMask & CombinedToMask).getBoolValue())
11187       // Conflicting bits - bail out because going further is unsafe.
11188       return SDValue();
11189 
11190     // Are the new bits contiguous when combined with the old bits?
11191     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
11192         BitsProperlyConcatenate(FromMask, NewFromMask))
11193       return V;
11194     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
11195         BitsProperlyConcatenate(NewFromMask, FromMask))
11196       return V;
11197 
11198     // We've seen a write to some bits, so track it.
11199     CombinedToMask |= NewToMask;
11200     // Keep going...
11201     V = V.getOperand(0);
11202   }
11203 
11204   return SDValue();
11205 }
11206 
11207 static SDValue PerformBFICombine(SDNode *N,
11208                                  TargetLowering::DAGCombinerInfo &DCI) {
11209   SDValue N1 = N->getOperand(1);
11210   if (N1.getOpcode() == ISD::AND) {
11211     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
11212     // the bits being cleared by the AND are not demanded by the BFI.
11213     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11214     if (!N11C)
11215       return SDValue();
11216     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11217     unsigned LSB = countTrailingZeros(~InvMask);
11218     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
11219     assert(Width <
11220                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
11221            "undefined behavior");
11222     unsigned Mask = (1u << Width) - 1;
11223     unsigned Mask2 = N11C->getZExtValue();
11224     if ((Mask & (~Mask2)) == 0)
11225       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
11226                              N->getOperand(0), N1.getOperand(0),
11227                              N->getOperand(2));
11228   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
11229     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
11230     // Keep track of any consecutive bits set that all come from the same base
11231     // value. We can combine these together into a single BFI.
11232     SDValue CombineBFI = FindBFIToCombineWith(N);
11233     if (CombineBFI == SDValue())
11234       return SDValue();
11235 
11236     // We've found a BFI.
11237     APInt ToMask1, FromMask1;
11238     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
11239 
11240     APInt ToMask2, FromMask2;
11241     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
11242     assert(From1 == From2);
11243     (void)From2;
11244 
11245     // First, unlink CombineBFI.
11246     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
11247     // Then create a new BFI, combining the two together.
11248     APInt NewFromMask = FromMask1 | FromMask2;
11249     APInt NewToMask = ToMask1 | ToMask2;
11250 
11251     EVT VT = N->getValueType(0);
11252     SDLoc dl(N);
11253 
11254     if (NewFromMask[0] == 0)
11255       From1 = DCI.DAG.getNode(
11256         ISD::SRL, dl, VT, From1,
11257         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
11258     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
11259                            DCI.DAG.getConstant(~NewToMask, dl, VT));
11260   }
11261   return SDValue();
11262 }
11263 
11264 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
11265 /// ARMISD::VMOVRRD.
11266 static SDValue PerformVMOVRRDCombine(SDNode *N,
11267                                      TargetLowering::DAGCombinerInfo &DCI,
11268                                      const ARMSubtarget *Subtarget) {
11269   // vmovrrd(vmovdrr x, y) -> x,y
11270   SDValue InDouble = N->getOperand(0);
11271   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
11272     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
11273 
11274   // vmovrrd(load f64) -> (load i32), (load i32)
11275   SDNode *InNode = InDouble.getNode();
11276   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
11277       InNode->getValueType(0) == MVT::f64 &&
11278       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
11279       !cast<LoadSDNode>(InNode)->isVolatile()) {
11280     // TODO: Should this be done for non-FrameIndex operands?
11281     LoadSDNode *LD = cast<LoadSDNode>(InNode);
11282 
11283     SelectionDAG &DAG = DCI.DAG;
11284     SDLoc DL(LD);
11285     SDValue BasePtr = LD->getBasePtr();
11286     SDValue NewLD1 =
11287         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
11288                     LD->getAlignment(), LD->getMemOperand()->getFlags());
11289 
11290     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11291                                     DAG.getConstant(4, DL, MVT::i32));
11292     SDValue NewLD2 = DAG.getLoad(
11293         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
11294         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
11295 
11296     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
11297     if (DCI.DAG.getDataLayout().isBigEndian())
11298       std::swap (NewLD1, NewLD2);
11299     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
11300     return Result;
11301   }
11302 
11303   return SDValue();
11304 }
11305 
11306 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
11307 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
11308 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
11309   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
11310   SDValue Op0 = N->getOperand(0);
11311   SDValue Op1 = N->getOperand(1);
11312   if (Op0.getOpcode() == ISD::BITCAST)
11313     Op0 = Op0.getOperand(0);
11314   if (Op1.getOpcode() == ISD::BITCAST)
11315     Op1 = Op1.getOperand(0);
11316   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
11317       Op0.getNode() == Op1.getNode() &&
11318       Op0.getResNo() == 0 && Op1.getResNo() == 1)
11319     return DAG.getNode(ISD::BITCAST, SDLoc(N),
11320                        N->getValueType(0), Op0.getOperand(0));
11321   return SDValue();
11322 }
11323 
11324 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
11325 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
11326 /// i64 vector to have f64 elements, since the value can then be loaded
11327 /// directly into a VFP register.
11328 static bool hasNormalLoadOperand(SDNode *N) {
11329   unsigned NumElts = N->getValueType(0).getVectorNumElements();
11330   for (unsigned i = 0; i < NumElts; ++i) {
11331     SDNode *Elt = N->getOperand(i).getNode();
11332     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
11333       return true;
11334   }
11335   return false;
11336 }
11337 
11338 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
11339 /// ISD::BUILD_VECTOR.
11340 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
11341                                           TargetLowering::DAGCombinerInfo &DCI,
11342                                           const ARMSubtarget *Subtarget) {
11343   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
11344   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
11345   // into a pair of GPRs, which is fine when the value is used as a scalar,
11346   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
11347   SelectionDAG &DAG = DCI.DAG;
11348   if (N->getNumOperands() == 2)
11349     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
11350       return RV;
11351 
11352   // Load i64 elements as f64 values so that type legalization does not split
11353   // them up into i32 values.
11354   EVT VT = N->getValueType(0);
11355   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
11356     return SDValue();
11357   SDLoc dl(N);
11358   SmallVector<SDValue, 8> Ops;
11359   unsigned NumElts = VT.getVectorNumElements();
11360   for (unsigned i = 0; i < NumElts; ++i) {
11361     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
11362     Ops.push_back(V);
11363     // Make the DAGCombiner fold the bitcast.
11364     DCI.AddToWorklist(V.getNode());
11365   }
11366   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
11367   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
11368   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11369 }
11370 
11371 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
11372 static SDValue
11373 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11374   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
11375   // At that time, we may have inserted bitcasts from integer to float.
11376   // If these bitcasts have survived DAGCombine, change the lowering of this
11377   // BUILD_VECTOR in something more vector friendly, i.e., that does not
11378   // force to use floating point types.
11379 
11380   // Make sure we can change the type of the vector.
11381   // This is possible iff:
11382   // 1. The vector is only used in a bitcast to a integer type. I.e.,
11383   //    1.1. Vector is used only once.
11384   //    1.2. Use is a bit convert to an integer type.
11385   // 2. The size of its operands are 32-bits (64-bits are not legal).
11386   EVT VT = N->getValueType(0);
11387   EVT EltVT = VT.getVectorElementType();
11388 
11389   // Check 1.1. and 2.
11390   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
11391     return SDValue();
11392 
11393   // By construction, the input type must be float.
11394   assert(EltVT == MVT::f32 && "Unexpected type!");
11395 
11396   // Check 1.2.
11397   SDNode *Use = *N->use_begin();
11398   if (Use->getOpcode() != ISD::BITCAST ||
11399       Use->getValueType(0).isFloatingPoint())
11400     return SDValue();
11401 
11402   // Check profitability.
11403   // Model is, if more than half of the relevant operands are bitcast from
11404   // i32, turn the build_vector into a sequence of insert_vector_elt.
11405   // Relevant operands are everything that is not statically
11406   // (i.e., at compile time) bitcasted.
11407   unsigned NumOfBitCastedElts = 0;
11408   unsigned NumElts = VT.getVectorNumElements();
11409   unsigned NumOfRelevantElts = NumElts;
11410   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
11411     SDValue Elt = N->getOperand(Idx);
11412     if (Elt->getOpcode() == ISD::BITCAST) {
11413       // Assume only bit cast to i32 will go away.
11414       if (Elt->getOperand(0).getValueType() == MVT::i32)
11415         ++NumOfBitCastedElts;
11416     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
11417       // Constants are statically casted, thus do not count them as
11418       // relevant operands.
11419       --NumOfRelevantElts;
11420   }
11421 
11422   // Check if more than half of the elements require a non-free bitcast.
11423   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
11424     return SDValue();
11425 
11426   SelectionDAG &DAG = DCI.DAG;
11427   // Create the new vector type.
11428   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
11429   // Check if the type is legal.
11430   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11431   if (!TLI.isTypeLegal(VecVT))
11432     return SDValue();
11433 
11434   // Combine:
11435   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
11436   // => BITCAST INSERT_VECTOR_ELT
11437   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
11438   //                      (BITCAST EN), N.
11439   SDValue Vec = DAG.getUNDEF(VecVT);
11440   SDLoc dl(N);
11441   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
11442     SDValue V = N->getOperand(Idx);
11443     if (V.isUndef())
11444       continue;
11445     if (V.getOpcode() == ISD::BITCAST &&
11446         V->getOperand(0).getValueType() == MVT::i32)
11447       // Fold obvious case.
11448       V = V.getOperand(0);
11449     else {
11450       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
11451       // Make the DAGCombiner fold the bitcasts.
11452       DCI.AddToWorklist(V.getNode());
11453     }
11454     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
11455     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
11456   }
11457   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
11458   // Make the DAGCombiner fold the bitcasts.
11459   DCI.AddToWorklist(Vec.getNode());
11460   return Vec;
11461 }
11462 
11463 /// PerformInsertEltCombine - Target-specific dag combine xforms for
11464 /// ISD::INSERT_VECTOR_ELT.
11465 static SDValue PerformInsertEltCombine(SDNode *N,
11466                                        TargetLowering::DAGCombinerInfo &DCI) {
11467   // Bitcast an i64 load inserted into a vector to f64.
11468   // Otherwise, the i64 value will be legalized to a pair of i32 values.
11469   EVT VT = N->getValueType(0);
11470   SDNode *Elt = N->getOperand(1).getNode();
11471   if (VT.getVectorElementType() != MVT::i64 ||
11472       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
11473     return SDValue();
11474 
11475   SelectionDAG &DAG = DCI.DAG;
11476   SDLoc dl(N);
11477   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11478                                  VT.getVectorNumElements());
11479   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
11480   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
11481   // Make the DAGCombiner fold the bitcasts.
11482   DCI.AddToWorklist(Vec.getNode());
11483   DCI.AddToWorklist(V.getNode());
11484   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
11485                                Vec, V, N->getOperand(2));
11486   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
11487 }
11488 
11489 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
11490 /// ISD::VECTOR_SHUFFLE.
11491 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
11492   // The LLVM shufflevector instruction does not require the shuffle mask
11493   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
11494   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
11495   // operands do not match the mask length, they are extended by concatenating
11496   // them with undef vectors.  That is probably the right thing for other
11497   // targets, but for NEON it is better to concatenate two double-register
11498   // size vector operands into a single quad-register size vector.  Do that
11499   // transformation here:
11500   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
11501   //   shuffle(concat(v1, v2), undef)
11502   SDValue Op0 = N->getOperand(0);
11503   SDValue Op1 = N->getOperand(1);
11504   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
11505       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
11506       Op0.getNumOperands() != 2 ||
11507       Op1.getNumOperands() != 2)
11508     return SDValue();
11509   SDValue Concat0Op1 = Op0.getOperand(1);
11510   SDValue Concat1Op1 = Op1.getOperand(1);
11511   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
11512     return SDValue();
11513   // Skip the transformation if any of the types are illegal.
11514   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11515   EVT VT = N->getValueType(0);
11516   if (!TLI.isTypeLegal(VT) ||
11517       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
11518       !TLI.isTypeLegal(Concat1Op1.getValueType()))
11519     return SDValue();
11520 
11521   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11522                                   Op0.getOperand(0), Op1.getOperand(0));
11523   // Translate the shuffle mask.
11524   SmallVector<int, 16> NewMask;
11525   unsigned NumElts = VT.getVectorNumElements();
11526   unsigned HalfElts = NumElts/2;
11527   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11528   for (unsigned n = 0; n < NumElts; ++n) {
11529     int MaskElt = SVN->getMaskElt(n);
11530     int NewElt = -1;
11531     if (MaskElt < (int)HalfElts)
11532       NewElt = MaskElt;
11533     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
11534       NewElt = HalfElts + MaskElt - NumElts;
11535     NewMask.push_back(NewElt);
11536   }
11537   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
11538                               DAG.getUNDEF(VT), NewMask);
11539 }
11540 
11541 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
11542 /// NEON load/store intrinsics, and generic vector load/stores, to merge
11543 /// base address updates.
11544 /// For generic load/stores, the memory type is assumed to be a vector.
11545 /// The caller is assumed to have checked legality.
11546 static SDValue CombineBaseUpdate(SDNode *N,
11547                                  TargetLowering::DAGCombinerInfo &DCI) {
11548   SelectionDAG &DAG = DCI.DAG;
11549   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
11550                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
11551   const bool isStore = N->getOpcode() == ISD::STORE;
11552   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
11553   SDValue Addr = N->getOperand(AddrOpIdx);
11554   MemSDNode *MemN = cast<MemSDNode>(N);
11555   SDLoc dl(N);
11556 
11557   // Search for a use of the address operand that is an increment.
11558   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11559          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11560     SDNode *User = *UI;
11561     if (User->getOpcode() != ISD::ADD ||
11562         UI.getUse().getResNo() != Addr.getResNo())
11563       continue;
11564 
11565     // Check that the add is independent of the load/store.  Otherwise, folding
11566     // it would create a cycle. We can avoid searching through Addr as it's a
11567     // predecessor to both.
11568     SmallPtrSet<const SDNode *, 32> Visited;
11569     SmallVector<const SDNode *, 16> Worklist;
11570     Visited.insert(Addr.getNode());
11571     Worklist.push_back(N);
11572     Worklist.push_back(User);
11573     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
11574         SDNode::hasPredecessorHelper(User, Visited, Worklist))
11575       continue;
11576 
11577     // Find the new opcode for the updating load/store.
11578     bool isLoadOp = true;
11579     bool isLaneOp = false;
11580     unsigned NewOpc = 0;
11581     unsigned NumVecs = 0;
11582     if (isIntrinsic) {
11583       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11584       switch (IntNo) {
11585       default: llvm_unreachable("unexpected intrinsic for Neon base update");
11586       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
11587         NumVecs = 1; break;
11588       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
11589         NumVecs = 2; break;
11590       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
11591         NumVecs = 3; break;
11592       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
11593         NumVecs = 4; break;
11594       case Intrinsic::arm_neon_vld2dup:
11595       case Intrinsic::arm_neon_vld3dup:
11596       case Intrinsic::arm_neon_vld4dup:
11597         // TODO: Support updating VLDxDUP nodes. For now, we just skip
11598         // combining base updates for such intrinsics.
11599         continue;
11600       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
11601         NumVecs = 2; isLaneOp = true; break;
11602       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
11603         NumVecs = 3; isLaneOp = true; break;
11604       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
11605         NumVecs = 4; isLaneOp = true; break;
11606       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
11607         NumVecs = 1; isLoadOp = false; break;
11608       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
11609         NumVecs = 2; isLoadOp = false; break;
11610       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
11611         NumVecs = 3; isLoadOp = false; break;
11612       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
11613         NumVecs = 4; isLoadOp = false; break;
11614       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
11615         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
11616       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
11617         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
11618       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
11619         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
11620       }
11621     } else {
11622       isLaneOp = true;
11623       switch (N->getOpcode()) {
11624       default: llvm_unreachable("unexpected opcode for Neon base update");
11625       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
11626       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
11627       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
11628       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
11629       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
11630         NumVecs = 1; isLaneOp = false; break;
11631       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
11632         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
11633       }
11634     }
11635 
11636     // Find the size of memory referenced by the load/store.
11637     EVT VecTy;
11638     if (isLoadOp) {
11639       VecTy = N->getValueType(0);
11640     } else if (isIntrinsic) {
11641       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
11642     } else {
11643       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
11644       VecTy = N->getOperand(1).getValueType();
11645     }
11646 
11647     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11648     if (isLaneOp)
11649       NumBytes /= VecTy.getVectorNumElements();
11650 
11651     // If the increment is a constant, it must match the memory ref size.
11652     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11653     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
11654     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
11655       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
11656       // separate instructions that make it harder to use a non-constant update.
11657       continue;
11658     }
11659 
11660     // OK, we found an ADD we can fold into the base update.
11661     // Now, create a _UPD node, taking care of not breaking alignment.
11662 
11663     EVT AlignedVecTy = VecTy;
11664     unsigned Alignment = MemN->getAlignment();
11665 
11666     // If this is a less-than-standard-aligned load/store, change the type to
11667     // match the standard alignment.
11668     // The alignment is overlooked when selecting _UPD variants; and it's
11669     // easier to introduce bitcasts here than fix that.
11670     // There are 3 ways to get to this base-update combine:
11671     // - intrinsics: they are assumed to be properly aligned (to the standard
11672     //   alignment of the memory type), so we don't need to do anything.
11673     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
11674     //   intrinsics, so, likewise, there's nothing to do.
11675     // - generic load/store instructions: the alignment is specified as an
11676     //   explicit operand, rather than implicitly as the standard alignment
11677     //   of the memory type (like the intrisics).  We need to change the
11678     //   memory type to match the explicit alignment.  That way, we don't
11679     //   generate non-standard-aligned ARMISD::VLDx nodes.
11680     if (isa<LSBaseSDNode>(N)) {
11681       if (Alignment == 0)
11682         Alignment = 1;
11683       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
11684         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
11685         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
11686         assert(!isLaneOp && "Unexpected generic load/store lane.");
11687         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
11688         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
11689       }
11690       // Don't set an explicit alignment on regular load/stores that we want
11691       // to transform to VLD/VST 1_UPD nodes.
11692       // This matches the behavior of regular load/stores, which only get an
11693       // explicit alignment if the MMO alignment is larger than the standard
11694       // alignment of the memory type.
11695       // Intrinsics, however, always get an explicit alignment, set to the
11696       // alignment of the MMO.
11697       Alignment = 1;
11698     }
11699 
11700     // Create the new updating load/store node.
11701     // First, create an SDVTList for the new updating node's results.
11702     EVT Tys[6];
11703     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
11704     unsigned n;
11705     for (n = 0; n < NumResultVecs; ++n)
11706       Tys[n] = AlignedVecTy;
11707     Tys[n++] = MVT::i32;
11708     Tys[n] = MVT::Other;
11709     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
11710 
11711     // Then, gather the new node's operands.
11712     SmallVector<SDValue, 8> Ops;
11713     Ops.push_back(N->getOperand(0)); // incoming chain
11714     Ops.push_back(N->getOperand(AddrOpIdx));
11715     Ops.push_back(Inc);
11716 
11717     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
11718       // Try to match the intrinsic's signature
11719       Ops.push_back(StN->getValue());
11720     } else {
11721       // Loads (and of course intrinsics) match the intrinsics' signature,
11722       // so just add all but the alignment operand.
11723       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
11724         Ops.push_back(N->getOperand(i));
11725     }
11726 
11727     // For all node types, the alignment operand is always the last one.
11728     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
11729 
11730     // If this is a non-standard-aligned STORE, the penultimate operand is the
11731     // stored value.  Bitcast it to the aligned type.
11732     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11733       SDValue &StVal = Ops[Ops.size()-2];
11734       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11735     }
11736 
11737     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11738     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11739                                            MemN->getMemOperand());
11740 
11741     // Update the uses.
11742     SmallVector<SDValue, 5> NewResults;
11743     for (unsigned i = 0; i < NumResultVecs; ++i)
11744       NewResults.push_back(SDValue(UpdN.getNode(), i));
11745 
11746     // If this is an non-standard-aligned LOAD, the first result is the loaded
11747     // value.  Bitcast it to the expected result type.
11748     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11749       SDValue &LdVal = NewResults[0];
11750       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11751     }
11752 
11753     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11754     DCI.CombineTo(N, NewResults);
11755     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11756 
11757     break;
11758   }
11759   return SDValue();
11760 }
11761 
11762 static SDValue PerformVLDCombine(SDNode *N,
11763                                  TargetLowering::DAGCombinerInfo &DCI) {
11764   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11765     return SDValue();
11766 
11767   return CombineBaseUpdate(N, DCI);
11768 }
11769 
11770 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11771 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11772 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
11773 /// return true.
11774 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11775   SelectionDAG &DAG = DCI.DAG;
11776   EVT VT = N->getValueType(0);
11777   // vldN-dup instructions only support 64-bit vectors for N > 1.
11778   if (!VT.is64BitVector())
11779     return false;
11780 
11781   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11782   SDNode *VLD = N->getOperand(0).getNode();
11783   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11784     return false;
11785   unsigned NumVecs = 0;
11786   unsigned NewOpc = 0;
11787   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11788   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11789     NumVecs = 2;
11790     NewOpc = ARMISD::VLD2DUP;
11791   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11792     NumVecs = 3;
11793     NewOpc = ARMISD::VLD3DUP;
11794   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11795     NumVecs = 4;
11796     NewOpc = ARMISD::VLD4DUP;
11797   } else {
11798     return false;
11799   }
11800 
11801   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11802   // numbers match the load.
11803   unsigned VLDLaneNo =
11804     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11805   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11806        UI != UE; ++UI) {
11807     // Ignore uses of the chain result.
11808     if (UI.getUse().getResNo() == NumVecs)
11809       continue;
11810     SDNode *User = *UI;
11811     if (User->getOpcode() != ARMISD::VDUPLANE ||
11812         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11813       return false;
11814   }
11815 
11816   // Create the vldN-dup node.
11817   EVT Tys[5];
11818   unsigned n;
11819   for (n = 0; n < NumVecs; ++n)
11820     Tys[n] = VT;
11821   Tys[n] = MVT::Other;
11822   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11823   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11824   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11825   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11826                                            Ops, VLDMemInt->getMemoryVT(),
11827                                            VLDMemInt->getMemOperand());
11828 
11829   // Update the uses.
11830   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11831        UI != UE; ++UI) {
11832     unsigned ResNo = UI.getUse().getResNo();
11833     // Ignore uses of the chain result.
11834     if (ResNo == NumVecs)
11835       continue;
11836     SDNode *User = *UI;
11837     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11838   }
11839 
11840   // Now the vldN-lane intrinsic is dead except for its chain result.
11841   // Update uses of the chain.
11842   std::vector<SDValue> VLDDupResults;
11843   for (unsigned n = 0; n < NumVecs; ++n)
11844     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11845   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11846   DCI.CombineTo(VLD, VLDDupResults);
11847 
11848   return true;
11849 }
11850 
11851 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11852 /// ARMISD::VDUPLANE.
11853 static SDValue PerformVDUPLANECombine(SDNode *N,
11854                                       TargetLowering::DAGCombinerInfo &DCI) {
11855   SDValue Op = N->getOperand(0);
11856 
11857   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11858   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11859   if (CombineVLDDUP(N, DCI))
11860     return SDValue(N, 0);
11861 
11862   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11863   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11864   while (Op.getOpcode() == ISD::BITCAST)
11865     Op = Op.getOperand(0);
11866   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11867     return SDValue();
11868 
11869   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11870   unsigned EltSize = Op.getScalarValueSizeInBits();
11871   // The canonical VMOV for a zero vector uses a 32-bit element size.
11872   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11873   unsigned EltBits;
11874   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11875     EltSize = 8;
11876   EVT VT = N->getValueType(0);
11877   if (EltSize > VT.getScalarSizeInBits())
11878     return SDValue();
11879 
11880   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11881 }
11882 
11883 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11884 static SDValue PerformVDUPCombine(SDNode *N,
11885                                   TargetLowering::DAGCombinerInfo &DCI) {
11886   SelectionDAG &DAG = DCI.DAG;
11887   SDValue Op = N->getOperand(0);
11888 
11889   // Match VDUP(LOAD) -> VLD1DUP.
11890   // We match this pattern here rather than waiting for isel because the
11891   // transform is only legal for unindexed loads.
11892   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11893   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11894       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11895     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11896                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11897     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11898     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11899                                              Ops, LD->getMemoryVT(),
11900                                              LD->getMemOperand());
11901     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11902     return VLDDup;
11903   }
11904 
11905   return SDValue();
11906 }
11907 
11908 static SDValue PerformLOADCombine(SDNode *N,
11909                                   TargetLowering::DAGCombinerInfo &DCI) {
11910   EVT VT = N->getValueType(0);
11911 
11912   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11913   if (ISD::isNormalLoad(N) && VT.isVector() &&
11914       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11915     return CombineBaseUpdate(N, DCI);
11916 
11917   return SDValue();
11918 }
11919 
11920 /// PerformSTORECombine - Target-specific dag combine xforms for
11921 /// ISD::STORE.
11922 static SDValue PerformSTORECombine(SDNode *N,
11923                                    TargetLowering::DAGCombinerInfo &DCI) {
11924   StoreSDNode *St = cast<StoreSDNode>(N);
11925   if (St->isVolatile())
11926     return SDValue();
11927 
11928   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11929   // pack all of the elements in one place.  Next, store to memory in fewer
11930   // chunks.
11931   SDValue StVal = St->getValue();
11932   EVT VT = StVal.getValueType();
11933   if (St->isTruncatingStore() && VT.isVector()) {
11934     SelectionDAG &DAG = DCI.DAG;
11935     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11936     EVT StVT = St->getMemoryVT();
11937     unsigned NumElems = VT.getVectorNumElements();
11938     assert(StVT != VT && "Cannot truncate to the same type");
11939     unsigned FromEltSz = VT.getScalarSizeInBits();
11940     unsigned ToEltSz = StVT.getScalarSizeInBits();
11941 
11942     // From, To sizes and ElemCount must be pow of two
11943     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11944 
11945     // We are going to use the original vector elt for storing.
11946     // Accumulated smaller vector elements must be a multiple of the store size.
11947     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11948 
11949     unsigned SizeRatio  = FromEltSz / ToEltSz;
11950     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11951 
11952     // Create a type on which we perform the shuffle.
11953     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11954                                      NumElems*SizeRatio);
11955     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11956 
11957     SDLoc DL(St);
11958     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11959     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11960     for (unsigned i = 0; i < NumElems; ++i)
11961       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11962                           ? (i + 1) * SizeRatio - 1
11963                           : i * SizeRatio;
11964 
11965     // Can't shuffle using an illegal type.
11966     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11967 
11968     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11969                                 DAG.getUNDEF(WideVec.getValueType()),
11970                                 ShuffleVec);
11971     // At this point all of the data is stored at the bottom of the
11972     // register. We now need to save it to mem.
11973 
11974     // Find the largest store unit
11975     MVT StoreType = MVT::i8;
11976     for (MVT Tp : MVT::integer_valuetypes()) {
11977       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11978         StoreType = Tp;
11979     }
11980     // Didn't find a legal store type.
11981     if (!TLI.isTypeLegal(StoreType))
11982       return SDValue();
11983 
11984     // Bitcast the original vector into a vector of store-size units
11985     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11986             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11987     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11988     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11989     SmallVector<SDValue, 8> Chains;
11990     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11991                                         TLI.getPointerTy(DAG.getDataLayout()));
11992     SDValue BasePtr = St->getBasePtr();
11993 
11994     // Perform one or more big stores into memory.
11995     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11996     for (unsigned I = 0; I < E; I++) {
11997       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11998                                    StoreType, ShuffWide,
11999                                    DAG.getIntPtrConstant(I, DL));
12000       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
12001                                 St->getPointerInfo(), St->getAlignment(),
12002                                 St->getMemOperand()->getFlags());
12003       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
12004                             Increment);
12005       Chains.push_back(Ch);
12006     }
12007     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
12008   }
12009 
12010   if (!ISD::isNormalStore(St))
12011     return SDValue();
12012 
12013   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
12014   // ARM stores of arguments in the same cache line.
12015   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
12016       StVal.getNode()->hasOneUse()) {
12017     SelectionDAG  &DAG = DCI.DAG;
12018     bool isBigEndian = DAG.getDataLayout().isBigEndian();
12019     SDLoc DL(St);
12020     SDValue BasePtr = St->getBasePtr();
12021     SDValue NewST1 = DAG.getStore(
12022         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
12023         BasePtr, St->getPointerInfo(), St->getAlignment(),
12024         St->getMemOperand()->getFlags());
12025 
12026     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12027                                     DAG.getConstant(4, DL, MVT::i32));
12028     return DAG.getStore(NewST1.getValue(0), DL,
12029                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
12030                         OffsetPtr, St->getPointerInfo(),
12031                         std::min(4U, St->getAlignment() / 2),
12032                         St->getMemOperand()->getFlags());
12033   }
12034 
12035   if (StVal.getValueType() == MVT::i64 &&
12036       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12037 
12038     // Bitcast an i64 store extracted from a vector to f64.
12039     // Otherwise, the i64 value will be legalized to a pair of i32 values.
12040     SelectionDAG &DAG = DCI.DAG;
12041     SDLoc dl(StVal);
12042     SDValue IntVec = StVal.getOperand(0);
12043     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12044                                    IntVec.getValueType().getVectorNumElements());
12045     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
12046     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12047                                  Vec, StVal.getOperand(1));
12048     dl = SDLoc(N);
12049     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
12050     // Make the DAGCombiner fold the bitcasts.
12051     DCI.AddToWorklist(Vec.getNode());
12052     DCI.AddToWorklist(ExtElt.getNode());
12053     DCI.AddToWorklist(V.getNode());
12054     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
12055                         St->getPointerInfo(), St->getAlignment(),
12056                         St->getMemOperand()->getFlags(), St->getAAInfo());
12057   }
12058 
12059   // If this is a legal vector store, try to combine it into a VST1_UPD.
12060   if (ISD::isNormalStore(N) && VT.isVector() &&
12061       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12062     return CombineBaseUpdate(N, DCI);
12063 
12064   return SDValue();
12065 }
12066 
12067 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
12068 /// can replace combinations of VMUL and VCVT (floating-point to integer)
12069 /// when the VMUL has a constant operand that is a power of 2.
12070 ///
12071 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
12072 ///  vmul.f32        d16, d17, d16
12073 ///  vcvt.s32.f32    d16, d16
12074 /// becomes:
12075 ///  vcvt.s32.f32    d16, d16, #3
12076 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
12077                                   const ARMSubtarget *Subtarget) {
12078   if (!Subtarget->hasNEON())
12079     return SDValue();
12080 
12081   SDValue Op = N->getOperand(0);
12082   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
12083       Op.getOpcode() != ISD::FMUL)
12084     return SDValue();
12085 
12086   SDValue ConstVec = Op->getOperand(1);
12087   if (!isa<BuildVectorSDNode>(ConstVec))
12088     return SDValue();
12089 
12090   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
12091   uint32_t FloatBits = FloatTy.getSizeInBits();
12092   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
12093   uint32_t IntBits = IntTy.getSizeInBits();
12094   unsigned NumLanes = Op.getValueType().getVectorNumElements();
12095   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
12096     // These instructions only exist converting from f32 to i32. We can handle
12097     // smaller integers by generating an extra truncate, but larger ones would
12098     // be lossy. We also can't handle more then 4 lanes, since these intructions
12099     // only support v2i32/v4i32 types.
12100     return SDValue();
12101   }
12102 
12103   BitVector UndefElements;
12104   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12105   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12106   if (C == -1 || C == 0 || C > 32)
12107     return SDValue();
12108 
12109   SDLoc dl(N);
12110   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
12111   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
12112     Intrinsic::arm_neon_vcvtfp2fxu;
12113   SDValue FixConv = DAG.getNode(
12114       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12115       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
12116       DAG.getConstant(C, dl, MVT::i32));
12117 
12118   if (IntBits < FloatBits)
12119     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
12120 
12121   return FixConv;
12122 }
12123 
12124 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
12125 /// can replace combinations of VCVT (integer to floating-point) and VDIV
12126 /// when the VDIV has a constant operand that is a power of 2.
12127 ///
12128 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
12129 ///  vcvt.f32.s32    d16, d16
12130 ///  vdiv.f32        d16, d17, d16
12131 /// becomes:
12132 ///  vcvt.f32.s32    d16, d16, #3
12133 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
12134                                   const ARMSubtarget *Subtarget) {
12135   if (!Subtarget->hasNEON())
12136     return SDValue();
12137 
12138   SDValue Op = N->getOperand(0);
12139   unsigned OpOpcode = Op.getNode()->getOpcode();
12140   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
12141       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
12142     return SDValue();
12143 
12144   SDValue ConstVec = N->getOperand(1);
12145   if (!isa<BuildVectorSDNode>(ConstVec))
12146     return SDValue();
12147 
12148   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
12149   uint32_t FloatBits = FloatTy.getSizeInBits();
12150   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
12151   uint32_t IntBits = IntTy.getSizeInBits();
12152   unsigned NumLanes = Op.getValueType().getVectorNumElements();
12153   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
12154     // These instructions only exist converting from i32 to f32. We can handle
12155     // smaller integers by generating an extra extend, but larger ones would
12156     // be lossy. We also can't handle more then 4 lanes, since these intructions
12157     // only support v2i32/v4i32 types.
12158     return SDValue();
12159   }
12160 
12161   BitVector UndefElements;
12162   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12163   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12164   if (C == -1 || C == 0 || C > 32)
12165     return SDValue();
12166 
12167   SDLoc dl(N);
12168   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
12169   SDValue ConvInput = Op.getOperand(0);
12170   if (IntBits < FloatBits)
12171     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
12172                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12173                             ConvInput);
12174 
12175   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
12176     Intrinsic::arm_neon_vcvtfxu2fp;
12177   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
12178                      Op.getValueType(),
12179                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
12180                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
12181 }
12182 
12183 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
12184 /// operand of a vector shift operation, where all the elements of the
12185 /// build_vector must have the same constant integer value.
12186 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
12187   // Ignore bit_converts.
12188   while (Op.getOpcode() == ISD::BITCAST)
12189     Op = Op.getOperand(0);
12190   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
12191   APInt SplatBits, SplatUndef;
12192   unsigned SplatBitSize;
12193   bool HasAnyUndefs;
12194   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
12195                                       HasAnyUndefs, ElementBits) ||
12196       SplatBitSize > ElementBits)
12197     return false;
12198   Cnt = SplatBits.getSExtValue();
12199   return true;
12200 }
12201 
12202 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
12203 /// operand of a vector shift left operation.  That value must be in the range:
12204 ///   0 <= Value < ElementBits for a left shift; or
12205 ///   0 <= Value <= ElementBits for a long left shift.
12206 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
12207   assert(VT.isVector() && "vector shift count is not a vector type");
12208   int64_t ElementBits = VT.getScalarSizeInBits();
12209   if (! getVShiftImm(Op, ElementBits, Cnt))
12210     return false;
12211   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
12212 }
12213 
12214 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
12215 /// operand of a vector shift right operation.  For a shift opcode, the value
12216 /// is positive, but for an intrinsic the value count must be negative. The
12217 /// absolute value must be in the range:
12218 ///   1 <= |Value| <= ElementBits for a right shift; or
12219 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
12220 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
12221                          int64_t &Cnt) {
12222   assert(VT.isVector() && "vector shift count is not a vector type");
12223   int64_t ElementBits = VT.getScalarSizeInBits();
12224   if (! getVShiftImm(Op, ElementBits, Cnt))
12225     return false;
12226   if (!isIntrinsic)
12227     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
12228   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
12229     Cnt = -Cnt;
12230     return true;
12231   }
12232   return false;
12233 }
12234 
12235 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
12236 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
12237   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12238   switch (IntNo) {
12239   default:
12240     // Don't do anything for most intrinsics.
12241     break;
12242 
12243   // Vector shifts: check for immediate versions and lower them.
12244   // Note: This is done during DAG combining instead of DAG legalizing because
12245   // the build_vectors for 64-bit vector element shift counts are generally
12246   // not legal, and it is hard to see their values after they get legalized to
12247   // loads from a constant pool.
12248   case Intrinsic::arm_neon_vshifts:
12249   case Intrinsic::arm_neon_vshiftu:
12250   case Intrinsic::arm_neon_vrshifts:
12251   case Intrinsic::arm_neon_vrshiftu:
12252   case Intrinsic::arm_neon_vrshiftn:
12253   case Intrinsic::arm_neon_vqshifts:
12254   case Intrinsic::arm_neon_vqshiftu:
12255   case Intrinsic::arm_neon_vqshiftsu:
12256   case Intrinsic::arm_neon_vqshiftns:
12257   case Intrinsic::arm_neon_vqshiftnu:
12258   case Intrinsic::arm_neon_vqshiftnsu:
12259   case Intrinsic::arm_neon_vqrshiftns:
12260   case Intrinsic::arm_neon_vqrshiftnu:
12261   case Intrinsic::arm_neon_vqrshiftnsu: {
12262     EVT VT = N->getOperand(1).getValueType();
12263     int64_t Cnt;
12264     unsigned VShiftOpc = 0;
12265 
12266     switch (IntNo) {
12267     case Intrinsic::arm_neon_vshifts:
12268     case Intrinsic::arm_neon_vshiftu:
12269       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
12270         VShiftOpc = ARMISD::VSHL;
12271         break;
12272       }
12273       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
12274         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
12275                      ARMISD::VSHRs : ARMISD::VSHRu);
12276         break;
12277       }
12278       return SDValue();
12279 
12280     case Intrinsic::arm_neon_vrshifts:
12281     case Intrinsic::arm_neon_vrshiftu:
12282       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
12283         break;
12284       return SDValue();
12285 
12286     case Intrinsic::arm_neon_vqshifts:
12287     case Intrinsic::arm_neon_vqshiftu:
12288       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12289         break;
12290       return SDValue();
12291 
12292     case Intrinsic::arm_neon_vqshiftsu:
12293       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12294         break;
12295       llvm_unreachable("invalid shift count for vqshlu intrinsic");
12296 
12297     case Intrinsic::arm_neon_vrshiftn:
12298     case Intrinsic::arm_neon_vqshiftns:
12299     case Intrinsic::arm_neon_vqshiftnu:
12300     case Intrinsic::arm_neon_vqshiftnsu:
12301     case Intrinsic::arm_neon_vqrshiftns:
12302     case Intrinsic::arm_neon_vqrshiftnu:
12303     case Intrinsic::arm_neon_vqrshiftnsu:
12304       // Narrowing shifts require an immediate right shift.
12305       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
12306         break;
12307       llvm_unreachable("invalid shift count for narrowing vector shift "
12308                        "intrinsic");
12309 
12310     default:
12311       llvm_unreachable("unhandled vector shift");
12312     }
12313 
12314     switch (IntNo) {
12315     case Intrinsic::arm_neon_vshifts:
12316     case Intrinsic::arm_neon_vshiftu:
12317       // Opcode already set above.
12318       break;
12319     case Intrinsic::arm_neon_vrshifts:
12320       VShiftOpc = ARMISD::VRSHRs; break;
12321     case Intrinsic::arm_neon_vrshiftu:
12322       VShiftOpc = ARMISD::VRSHRu; break;
12323     case Intrinsic::arm_neon_vrshiftn:
12324       VShiftOpc = ARMISD::VRSHRN; break;
12325     case Intrinsic::arm_neon_vqshifts:
12326       VShiftOpc = ARMISD::VQSHLs; break;
12327     case Intrinsic::arm_neon_vqshiftu:
12328       VShiftOpc = ARMISD::VQSHLu; break;
12329     case Intrinsic::arm_neon_vqshiftsu:
12330       VShiftOpc = ARMISD::VQSHLsu; break;
12331     case Intrinsic::arm_neon_vqshiftns:
12332       VShiftOpc = ARMISD::VQSHRNs; break;
12333     case Intrinsic::arm_neon_vqshiftnu:
12334       VShiftOpc = ARMISD::VQSHRNu; break;
12335     case Intrinsic::arm_neon_vqshiftnsu:
12336       VShiftOpc = ARMISD::VQSHRNsu; break;
12337     case Intrinsic::arm_neon_vqrshiftns:
12338       VShiftOpc = ARMISD::VQRSHRNs; break;
12339     case Intrinsic::arm_neon_vqrshiftnu:
12340       VShiftOpc = ARMISD::VQRSHRNu; break;
12341     case Intrinsic::arm_neon_vqrshiftnsu:
12342       VShiftOpc = ARMISD::VQRSHRNsu; break;
12343     }
12344 
12345     SDLoc dl(N);
12346     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12347                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
12348   }
12349 
12350   case Intrinsic::arm_neon_vshiftins: {
12351     EVT VT = N->getOperand(1).getValueType();
12352     int64_t Cnt;
12353     unsigned VShiftOpc = 0;
12354 
12355     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
12356       VShiftOpc = ARMISD::VSLI;
12357     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
12358       VShiftOpc = ARMISD::VSRI;
12359     else {
12360       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
12361     }
12362 
12363     SDLoc dl(N);
12364     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12365                        N->getOperand(1), N->getOperand(2),
12366                        DAG.getConstant(Cnt, dl, MVT::i32));
12367   }
12368 
12369   case Intrinsic::arm_neon_vqrshifts:
12370   case Intrinsic::arm_neon_vqrshiftu:
12371     // No immediate versions of these to check for.
12372     break;
12373   }
12374 
12375   return SDValue();
12376 }
12377 
12378 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
12379 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
12380 /// combining instead of DAG legalizing because the build_vectors for 64-bit
12381 /// vector element shift counts are generally not legal, and it is hard to see
12382 /// their values after they get legalized to loads from a constant pool.
12383 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
12384                                    const ARMSubtarget *ST) {
12385   EVT VT = N->getValueType(0);
12386   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
12387     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
12388     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
12389     SDValue N1 = N->getOperand(1);
12390     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
12391       SDValue N0 = N->getOperand(0);
12392       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
12393           DAG.MaskedValueIsZero(N0.getOperand(0),
12394                                 APInt::getHighBitsSet(32, 16)))
12395         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
12396     }
12397   }
12398 
12399   // Nothing to be done for scalar shifts.
12400   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12401   if (!VT.isVector() || !TLI.isTypeLegal(VT))
12402     return SDValue();
12403 
12404   assert(ST->hasNEON() && "unexpected vector shift");
12405   int64_t Cnt;
12406 
12407   switch (N->getOpcode()) {
12408   default: llvm_unreachable("unexpected shift opcode");
12409 
12410   case ISD::SHL:
12411     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
12412       SDLoc dl(N);
12413       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
12414                          DAG.getConstant(Cnt, dl, MVT::i32));
12415     }
12416     break;
12417 
12418   case ISD::SRA:
12419   case ISD::SRL:
12420     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
12421       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
12422                             ARMISD::VSHRs : ARMISD::VSHRu);
12423       SDLoc dl(N);
12424       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
12425                          DAG.getConstant(Cnt, dl, MVT::i32));
12426     }
12427   }
12428   return SDValue();
12429 }
12430 
12431 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
12432 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
12433 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
12434                                     const ARMSubtarget *ST) {
12435   SDValue N0 = N->getOperand(0);
12436 
12437   // Check for sign- and zero-extensions of vector extract operations of 8-
12438   // and 16-bit vector elements.  NEON supports these directly.  They are
12439   // handled during DAG combining because type legalization will promote them
12440   // to 32-bit types and it is messy to recognize the operations after that.
12441   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12442     SDValue Vec = N0.getOperand(0);
12443     SDValue Lane = N0.getOperand(1);
12444     EVT VT = N->getValueType(0);
12445     EVT EltVT = N0.getValueType();
12446     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12447 
12448     if (VT == MVT::i32 &&
12449         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
12450         TLI.isTypeLegal(Vec.getValueType()) &&
12451         isa<ConstantSDNode>(Lane)) {
12452 
12453       unsigned Opc = 0;
12454       switch (N->getOpcode()) {
12455       default: llvm_unreachable("unexpected opcode");
12456       case ISD::SIGN_EXTEND:
12457         Opc = ARMISD::VGETLANEs;
12458         break;
12459       case ISD::ZERO_EXTEND:
12460       case ISD::ANY_EXTEND:
12461         Opc = ARMISD::VGETLANEu;
12462         break;
12463       }
12464       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
12465     }
12466   }
12467 
12468   return SDValue();
12469 }
12470 
12471 static const APInt *isPowerOf2Constant(SDValue V) {
12472   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12473   if (!C)
12474     return nullptr;
12475   const APInt *CV = &C->getAPIntValue();
12476   return CV->isPowerOf2() ? CV : nullptr;
12477 }
12478 
12479 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
12480   // If we have a CMOV, OR and AND combination such as:
12481   //   if (x & CN)
12482   //     y |= CM;
12483   //
12484   // And:
12485   //   * CN is a single bit;
12486   //   * All bits covered by CM are known zero in y
12487   //
12488   // Then we can convert this into a sequence of BFI instructions. This will
12489   // always be a win if CM is a single bit, will always be no worse than the
12490   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
12491   // three bits (due to the extra IT instruction).
12492 
12493   SDValue Op0 = CMOV->getOperand(0);
12494   SDValue Op1 = CMOV->getOperand(1);
12495   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
12496   auto CC = CCNode->getAPIntValue().getLimitedValue();
12497   SDValue CmpZ = CMOV->getOperand(4);
12498 
12499   // The compare must be against zero.
12500   if (!isNullConstant(CmpZ->getOperand(1)))
12501     return SDValue();
12502 
12503   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
12504   SDValue And = CmpZ->getOperand(0);
12505   if (And->getOpcode() != ISD::AND)
12506     return SDValue();
12507   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
12508   if (!AndC)
12509     return SDValue();
12510   SDValue X = And->getOperand(0);
12511 
12512   if (CC == ARMCC::EQ) {
12513     // We're performing an "equal to zero" compare. Swap the operands so we
12514     // canonicalize on a "not equal to zero" compare.
12515     std::swap(Op0, Op1);
12516   } else {
12517     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
12518   }
12519 
12520   if (Op1->getOpcode() != ISD::OR)
12521     return SDValue();
12522 
12523   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
12524   if (!OrC)
12525     return SDValue();
12526   SDValue Y = Op1->getOperand(0);
12527 
12528   if (Op0 != Y)
12529     return SDValue();
12530 
12531   // Now, is it profitable to continue?
12532   APInt OrCI = OrC->getAPIntValue();
12533   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
12534   if (OrCI.countPopulation() > Heuristic)
12535     return SDValue();
12536 
12537   // Lastly, can we determine that the bits defined by OrCI
12538   // are zero in Y?
12539   KnownBits Known;
12540   DAG.computeKnownBits(Y, Known);
12541   if ((OrCI & Known.Zero) != OrCI)
12542     return SDValue();
12543 
12544   // OK, we can do the combine.
12545   SDValue V = Y;
12546   SDLoc dl(X);
12547   EVT VT = X.getValueType();
12548   unsigned BitInX = AndC->logBase2();
12549 
12550   if (BitInX != 0) {
12551     // We must shift X first.
12552     X = DAG.getNode(ISD::SRL, dl, VT, X,
12553                     DAG.getConstant(BitInX, dl, VT));
12554   }
12555 
12556   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
12557        BitInY < NumActiveBits; ++BitInY) {
12558     if (OrCI[BitInY] == 0)
12559       continue;
12560     APInt Mask(VT.getSizeInBits(), 0);
12561     Mask.setBit(BitInY);
12562     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
12563                     // Confusingly, the operand is an *inverted* mask.
12564                     DAG.getConstant(~Mask, dl, VT));
12565   }
12566 
12567   return V;
12568 }
12569 
12570 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
12571 SDValue
12572 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
12573   SDValue Cmp = N->getOperand(4);
12574   if (Cmp.getOpcode() != ARMISD::CMPZ)
12575     // Only looking at NE cases.
12576     return SDValue();
12577 
12578   EVT VT = N->getValueType(0);
12579   SDLoc dl(N);
12580   SDValue LHS = Cmp.getOperand(0);
12581   SDValue RHS = Cmp.getOperand(1);
12582   SDValue Chain = N->getOperand(0);
12583   SDValue BB = N->getOperand(1);
12584   SDValue ARMcc = N->getOperand(2);
12585   ARMCC::CondCodes CC =
12586     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12587 
12588   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
12589   // -> (brcond Chain BB CC CPSR Cmp)
12590   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
12591       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
12592       LHS->getOperand(0)->hasOneUse()) {
12593     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
12594     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
12595     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12596     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12597     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
12598         (LHS01C && LHS01C->getZExtValue() == 1) &&
12599         (LHS1C && LHS1C->getZExtValue() == 1) &&
12600         (RHSC && RHSC->getZExtValue() == 0)) {
12601       return DAG.getNode(
12602           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
12603           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
12604     }
12605   }
12606 
12607   return SDValue();
12608 }
12609 
12610 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
12611 SDValue
12612 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
12613   SDValue Cmp = N->getOperand(4);
12614   if (Cmp.getOpcode() != ARMISD::CMPZ)
12615     // Only looking at EQ and NE cases.
12616     return SDValue();
12617 
12618   EVT VT = N->getValueType(0);
12619   SDLoc dl(N);
12620   SDValue LHS = Cmp.getOperand(0);
12621   SDValue RHS = Cmp.getOperand(1);
12622   SDValue FalseVal = N->getOperand(0);
12623   SDValue TrueVal = N->getOperand(1);
12624   SDValue ARMcc = N->getOperand(2);
12625   ARMCC::CondCodes CC =
12626     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12627 
12628   // BFI is only available on V6T2+.
12629   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
12630     SDValue R = PerformCMOVToBFICombine(N, DAG);
12631     if (R)
12632       return R;
12633   }
12634 
12635   // Simplify
12636   //   mov     r1, r0
12637   //   cmp     r1, x
12638   //   mov     r0, y
12639   //   moveq   r0, x
12640   // to
12641   //   cmp     r0, x
12642   //   movne   r0, y
12643   //
12644   //   mov     r1, r0
12645   //   cmp     r1, x
12646   //   mov     r0, x
12647   //   movne   r0, y
12648   // to
12649   //   cmp     r0, x
12650   //   movne   r0, y
12651   /// FIXME: Turn this into a target neutral optimization?
12652   SDValue Res;
12653   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
12654     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
12655                       N->getOperand(3), Cmp);
12656   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
12657     SDValue ARMcc;
12658     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
12659     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
12660                       N->getOperand(3), NewCmp);
12661   }
12662 
12663   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
12664   // -> (cmov F T CC CPSR Cmp)
12665   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
12666     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
12667     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12668     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12669     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
12670         (LHS1C && LHS1C->getZExtValue() == 1) &&
12671         (RHSC && RHSC->getZExtValue() == 0)) {
12672       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
12673                          LHS->getOperand(2), LHS->getOperand(3),
12674                          LHS->getOperand(4));
12675     }
12676   }
12677 
12678   if (!VT.isInteger())
12679       return SDValue();
12680 
12681   // Materialize a boolean comparison for integers so we can avoid branching.
12682   if (isNullConstant(FalseVal)) {
12683     if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
12684       if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
12685         // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
12686         // right 5 bits will make that 32 be 1, otherwise it will be 0.
12687         // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
12688         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12689         Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
12690                           DAG.getConstant(5, dl, MVT::i32));
12691       } else {
12692         // CMOV 0, 1, ==, (CMPZ x, y) ->
12693         //     (ADDCARRY (SUB x, y), t:0, t:1)
12694         // where t = (SUBCARRY 0, (SUB x, y), 0)
12695         //
12696         // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
12697         // x != y. In other words, a carry C == 1 when x == y, C == 0
12698         // otherwise.
12699         // The final ADDCARRY computes
12700         //     x - y + (0 - (x - y)) + C == C
12701         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12702         SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12703         SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
12704         // ISD::SUBCARRY returns a borrow but we want the carry here
12705         // actually.
12706         SDValue Carry =
12707             DAG.getNode(ISD::SUB, dl, MVT::i32,
12708                         DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
12709         Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
12710       }
12711     } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
12712                (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
12713       // This seems pointless but will allow us to combine it further below.
12714       // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
12715       SDValue Sub =
12716           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
12717       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
12718                                           Sub.getValue(1), SDValue());
12719       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
12720                         N->getOperand(3), CPSRGlue.getValue(1));
12721       FalseVal = Sub;
12722     }
12723   } else if (isNullConstant(TrueVal)) {
12724     if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
12725         (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
12726       // This seems pointless but will allow us to combine it further below
12727       // Note that we change == for != as this is the dual for the case above.
12728       // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
12729       SDValue Sub =
12730           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
12731       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
12732                                           Sub.getValue(1), SDValue());
12733       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
12734                         DAG.getConstant(ARMCC::NE, dl, MVT::i32),
12735                         N->getOperand(3), CPSRGlue.getValue(1));
12736       FalseVal = Sub;
12737     }
12738   }
12739 
12740   // On Thumb1, the DAG above may be further combined if z is a power of 2
12741   // (z == 2 ^ K).
12742   // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
12743   //       merge t3, t4
12744   // where t1 = (SUBCARRY (SUB x, y), z, 0)
12745   //       t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
12746   //       t3 = if K != 0 then (SHL t2:0, K) else t2:0
12747   //       t4 = (SUB 1, t2:1)   [ we want a carry, not a borrow ]
12748   const APInt *TrueConst;
12749   if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
12750       (FalseVal.getOpcode() == ARMISD::SUBS) &&
12751       (FalseVal.getOperand(0) == LHS) && (FalseVal.getOperand(1) == RHS) &&
12752       (TrueConst = isPowerOf2Constant(TrueVal))) {
12753     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12754     unsigned ShiftAmount = TrueConst->logBase2();
12755     if (ShiftAmount)
12756       TrueVal = DAG.getConstant(1, dl, VT);
12757     SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
12758     Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
12759     // Make it a carry, not a borrow.
12760     SDValue Carry = DAG.getNode(
12761         ISD::SUB, dl, VT, DAG.getConstant(1, dl, MVT::i32), Res.getValue(1));
12762     Res = DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Res, Carry);
12763 
12764     if (ShiftAmount)
12765       Res = DAG.getNode(ISD::SHL, dl, VT, Res,
12766                         DAG.getConstant(ShiftAmount, dl, MVT::i32));
12767   }
12768 
12769   if (Res.getNode()) {
12770     KnownBits Known;
12771     DAG.computeKnownBits(SDValue(N,0), Known);
12772     // Capture demanded bits information that would be otherwise lost.
12773     if (Known.Zero == 0xfffffffe)
12774       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12775                         DAG.getValueType(MVT::i1));
12776     else if (Known.Zero == 0xffffff00)
12777       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12778                         DAG.getValueType(MVT::i8));
12779     else if (Known.Zero == 0xffff0000)
12780       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12781                         DAG.getValueType(MVT::i16));
12782   }
12783 
12784   return Res;
12785 }
12786 
12787 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
12788                                              DAGCombinerInfo &DCI) const {
12789   switch (N->getOpcode()) {
12790   default: break;
12791   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
12792   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
12793   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
12794   case ISD::SUB:        return PerformSUBCombine(N, DCI);
12795   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
12796   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
12797   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
12798   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
12799   case ARMISD::ADDC:
12800   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
12801   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
12802   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
12803   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
12804   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
12805   case ISD::STORE:      return PerformSTORECombine(N, DCI);
12806   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
12807   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
12808   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
12809   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
12810   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
12811   case ISD::FP_TO_SINT:
12812   case ISD::FP_TO_UINT:
12813     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
12814   case ISD::FDIV:
12815     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
12816   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
12817   case ISD::SHL:
12818   case ISD::SRA:
12819   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
12820   case ISD::SIGN_EXTEND:
12821   case ISD::ZERO_EXTEND:
12822   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
12823   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
12824   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
12825   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
12826   case ARMISD::VLD1DUP:
12827   case ARMISD::VLD2DUP:
12828   case ARMISD::VLD3DUP:
12829   case ARMISD::VLD4DUP:
12830     return PerformVLDCombine(N, DCI);
12831   case ARMISD::BUILD_VECTOR:
12832     return PerformARMBUILD_VECTORCombine(N, DCI);
12833   case ARMISD::SMULWB: {
12834     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12835     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12836     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12837       return SDValue();
12838     break;
12839   }
12840   case ARMISD::SMULWT: {
12841     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12842     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12843     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12844       return SDValue();
12845     break;
12846   }
12847   case ARMISD::SMLALBB: {
12848     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12849     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12850     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12851         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12852       return SDValue();
12853     break;
12854   }
12855   case ARMISD::SMLALBT: {
12856     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12857     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12858     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12859     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12860     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12861         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12862       return SDValue();
12863     break;
12864   }
12865   case ARMISD::SMLALTB: {
12866     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12867     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12868     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12869     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12870     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12871         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12872       return SDValue();
12873     break;
12874   }
12875   case ARMISD::SMLALTT: {
12876     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12877     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12878     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12879         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12880       return SDValue();
12881     break;
12882   }
12883   case ISD::INTRINSIC_VOID:
12884   case ISD::INTRINSIC_W_CHAIN:
12885     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12886     case Intrinsic::arm_neon_vld1:
12887     case Intrinsic::arm_neon_vld1x2:
12888     case Intrinsic::arm_neon_vld1x3:
12889     case Intrinsic::arm_neon_vld1x4:
12890     case Intrinsic::arm_neon_vld2:
12891     case Intrinsic::arm_neon_vld3:
12892     case Intrinsic::arm_neon_vld4:
12893     case Intrinsic::arm_neon_vld2lane:
12894     case Intrinsic::arm_neon_vld3lane:
12895     case Intrinsic::arm_neon_vld4lane:
12896     case Intrinsic::arm_neon_vld2dup:
12897     case Intrinsic::arm_neon_vld3dup:
12898     case Intrinsic::arm_neon_vld4dup:
12899     case Intrinsic::arm_neon_vst1:
12900     case Intrinsic::arm_neon_vst1x2:
12901     case Intrinsic::arm_neon_vst1x3:
12902     case Intrinsic::arm_neon_vst1x4:
12903     case Intrinsic::arm_neon_vst2:
12904     case Intrinsic::arm_neon_vst3:
12905     case Intrinsic::arm_neon_vst4:
12906     case Intrinsic::arm_neon_vst2lane:
12907     case Intrinsic::arm_neon_vst3lane:
12908     case Intrinsic::arm_neon_vst4lane:
12909       return PerformVLDCombine(N, DCI);
12910     default: break;
12911     }
12912     break;
12913   }
12914   return SDValue();
12915 }
12916 
12917 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12918                                                           EVT VT) const {
12919   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12920 }
12921 
12922 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12923                                                        unsigned,
12924                                                        unsigned,
12925                                                        bool *Fast) const {
12926   // Depends what it gets converted into if the type is weird.
12927   if (!VT.isSimple())
12928     return false;
12929 
12930   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12931   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12932 
12933   switch (VT.getSimpleVT().SimpleTy) {
12934   default:
12935     return false;
12936   case MVT::i8:
12937   case MVT::i16:
12938   case MVT::i32: {
12939     // Unaligned access can use (for example) LRDB, LRDH, LDR
12940     if (AllowsUnaligned) {
12941       if (Fast)
12942         *Fast = Subtarget->hasV7Ops();
12943       return true;
12944     }
12945     return false;
12946   }
12947   case MVT::f64:
12948   case MVT::v2f64: {
12949     // For any little-endian targets with neon, we can support unaligned ld/st
12950     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12951     // A big-endian target may also explicitly support unaligned accesses
12952     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12953       if (Fast)
12954         *Fast = true;
12955       return true;
12956     }
12957     return false;
12958   }
12959   }
12960 }
12961 
12962 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12963                        unsigned AlignCheck) {
12964   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12965           (DstAlign == 0 || DstAlign % AlignCheck == 0));
12966 }
12967 
12968 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12969                                            unsigned DstAlign, unsigned SrcAlign,
12970                                            bool IsMemset, bool ZeroMemset,
12971                                            bool MemcpyStrSrc,
12972                                            MachineFunction &MF) const {
12973   const Function &F = MF.getFunction();
12974 
12975   // See if we can use NEON instructions for this...
12976   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12977       !F.hasFnAttribute(Attribute::NoImplicitFloat)) {
12978     bool Fast;
12979     if (Size >= 16 &&
12980         (memOpAlign(SrcAlign, DstAlign, 16) ||
12981          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12982       return MVT::v2f64;
12983     } else if (Size >= 8 &&
12984                (memOpAlign(SrcAlign, DstAlign, 8) ||
12985                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12986                  Fast))) {
12987       return MVT::f64;
12988     }
12989   }
12990 
12991   // Let the target-independent logic figure it out.
12992   return MVT::Other;
12993 }
12994 
12995 // 64-bit integers are split into their high and low parts and held in two
12996 // different registers, so the trunc is free since the low register can just
12997 // be used.
12998 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
12999   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
13000     return false;
13001   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
13002   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
13003   return (SrcBits == 64 && DestBits == 32);
13004 }
13005 
13006 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
13007   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
13008       !DstVT.isInteger())
13009     return false;
13010   unsigned SrcBits = SrcVT.getSizeInBits();
13011   unsigned DestBits = DstVT.getSizeInBits();
13012   return (SrcBits == 64 && DestBits == 32);
13013 }
13014 
13015 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13016   if (Val.getOpcode() != ISD::LOAD)
13017     return false;
13018 
13019   EVT VT1 = Val.getValueType();
13020   if (!VT1.isSimple() || !VT1.isInteger() ||
13021       !VT2.isSimple() || !VT2.isInteger())
13022     return false;
13023 
13024   switch (VT1.getSimpleVT().SimpleTy) {
13025   default: break;
13026   case MVT::i1:
13027   case MVT::i8:
13028   case MVT::i16:
13029     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
13030     return true;
13031   }
13032 
13033   return false;
13034 }
13035 
13036 bool ARMTargetLowering::isFNegFree(EVT VT) const {
13037   if (!VT.isSimple())
13038     return false;
13039 
13040   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
13041   // negate values directly (fneg is free). So, we don't want to let the DAG
13042   // combiner rewrite fneg into xors and some other instructions.  For f16 and
13043   // FullFP16 argument passing, some bitcast nodes may be introduced,
13044   // triggering this DAG combine rewrite, so we are avoiding that with this.
13045   switch (VT.getSimpleVT().SimpleTy) {
13046   default: break;
13047   case MVT::f16:
13048     return Subtarget->hasFullFP16();
13049   }
13050 
13051   return false;
13052 }
13053 
13054 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
13055   EVT VT = ExtVal.getValueType();
13056 
13057   if (!isTypeLegal(VT))
13058     return false;
13059 
13060   // Don't create a loadext if we can fold the extension into a wide/long
13061   // instruction.
13062   // If there's more than one user instruction, the loadext is desirable no
13063   // matter what.  There can be two uses by the same instruction.
13064   if (ExtVal->use_empty() ||
13065       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
13066     return true;
13067 
13068   SDNode *U = *ExtVal->use_begin();
13069   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
13070        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
13071     return false;
13072 
13073   return true;
13074 }
13075 
13076 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
13077   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13078     return false;
13079 
13080   if (!isTypeLegal(EVT::getEVT(Ty1)))
13081     return false;
13082 
13083   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
13084 
13085   // Assuming the caller doesn't have a zeroext or signext return parameter,
13086   // truncation all the way down to i1 is valid.
13087   return true;
13088 }
13089 
13090 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
13091                                                 const AddrMode &AM, Type *Ty,
13092                                                 unsigned AS) const {
13093   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
13094     if (Subtarget->hasFPAO())
13095       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
13096     return 0;
13097   }
13098   return -1;
13099 }
13100 
13101 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
13102   if (V < 0)
13103     return false;
13104 
13105   unsigned Scale = 1;
13106   switch (VT.getSimpleVT().SimpleTy) {
13107   default: return false;
13108   case MVT::i1:
13109   case MVT::i8:
13110     // Scale == 1;
13111     break;
13112   case MVT::i16:
13113     // Scale == 2;
13114     Scale = 2;
13115     break;
13116   case MVT::i32:
13117     // Scale == 4;
13118     Scale = 4;
13119     break;
13120   }
13121 
13122   if ((V & (Scale - 1)) != 0)
13123     return false;
13124   V /= Scale;
13125   return V == (V & ((1LL << 5) - 1));
13126 }
13127 
13128 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
13129                                       const ARMSubtarget *Subtarget) {
13130   bool isNeg = false;
13131   if (V < 0) {
13132     isNeg = true;
13133     V = - V;
13134   }
13135 
13136   switch (VT.getSimpleVT().SimpleTy) {
13137   default: return false;
13138   case MVT::i1:
13139   case MVT::i8:
13140   case MVT::i16:
13141   case MVT::i32:
13142     // + imm12 or - imm8
13143     if (isNeg)
13144       return V == (V & ((1LL << 8) - 1));
13145     return V == (V & ((1LL << 12) - 1));
13146   case MVT::f32:
13147   case MVT::f64:
13148     // Same as ARM mode. FIXME: NEON?
13149     if (!Subtarget->hasVFP2())
13150       return false;
13151     if ((V & 3) != 0)
13152       return false;
13153     V >>= 2;
13154     return V == (V & ((1LL << 8) - 1));
13155   }
13156 }
13157 
13158 /// isLegalAddressImmediate - Return true if the integer value can be used
13159 /// as the offset of the target addressing mode for load / store of the
13160 /// given type.
13161 static bool isLegalAddressImmediate(int64_t V, EVT VT,
13162                                     const ARMSubtarget *Subtarget) {
13163   if (V == 0)
13164     return true;
13165 
13166   if (!VT.isSimple())
13167     return false;
13168 
13169   if (Subtarget->isThumb1Only())
13170     return isLegalT1AddressImmediate(V, VT);
13171   else if (Subtarget->isThumb2())
13172     return isLegalT2AddressImmediate(V, VT, Subtarget);
13173 
13174   // ARM mode.
13175   if (V < 0)
13176     V = - V;
13177   switch (VT.getSimpleVT().SimpleTy) {
13178   default: return false;
13179   case MVT::i1:
13180   case MVT::i8:
13181   case MVT::i32:
13182     // +- imm12
13183     return V == (V & ((1LL << 12) - 1));
13184   case MVT::i16:
13185     // +- imm8
13186     return V == (V & ((1LL << 8) - 1));
13187   case MVT::f32:
13188   case MVT::f64:
13189     if (!Subtarget->hasVFP2()) // FIXME: NEON?
13190       return false;
13191     if ((V & 3) != 0)
13192       return false;
13193     V >>= 2;
13194     return V == (V & ((1LL << 8) - 1));
13195   }
13196 }
13197 
13198 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
13199                                                       EVT VT) const {
13200   int Scale = AM.Scale;
13201   if (Scale < 0)
13202     return false;
13203 
13204   switch (VT.getSimpleVT().SimpleTy) {
13205   default: return false;
13206   case MVT::i1:
13207   case MVT::i8:
13208   case MVT::i16:
13209   case MVT::i32:
13210     if (Scale == 1)
13211       return true;
13212     // r + r << imm
13213     Scale = Scale & ~1;
13214     return Scale == 2 || Scale == 4 || Scale == 8;
13215   case MVT::i64:
13216     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
13217     // version in Thumb mode.
13218     // r + r
13219     if (Scale == 1)
13220       return true;
13221     // r * 2 (this can be lowered to r + r).
13222     if (!AM.HasBaseReg && Scale == 2)
13223       return true;
13224     return false;
13225   case MVT::isVoid:
13226     // Note, we allow "void" uses (basically, uses that aren't loads or
13227     // stores), because arm allows folding a scale into many arithmetic
13228     // operations.  This should be made more precise and revisited later.
13229 
13230     // Allow r << imm, but the imm has to be a multiple of two.
13231     if (Scale & 1) return false;
13232     return isPowerOf2_32(Scale);
13233   }
13234 }
13235 
13236 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
13237                                                       EVT VT) const {
13238   const int Scale = AM.Scale;
13239 
13240   // Negative scales are not supported in Thumb1.
13241   if (Scale < 0)
13242     return false;
13243 
13244   // Thumb1 addressing modes do not support register scaling excepting the
13245   // following cases:
13246   // 1. Scale == 1 means no scaling.
13247   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
13248   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
13249 }
13250 
13251 /// isLegalAddressingMode - Return true if the addressing mode represented
13252 /// by AM is legal for this target, for a load/store of the specified type.
13253 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
13254                                               const AddrMode &AM, Type *Ty,
13255                                               unsigned AS, Instruction *I) const {
13256   EVT VT = getValueType(DL, Ty, true);
13257   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
13258     return false;
13259 
13260   // Can never fold addr of global into load/store.
13261   if (AM.BaseGV)
13262     return false;
13263 
13264   switch (AM.Scale) {
13265   case 0:  // no scale reg, must be "r+i" or "r", or "i".
13266     break;
13267   default:
13268     // ARM doesn't support any R+R*scale+imm addr modes.
13269     if (AM.BaseOffs)
13270       return false;
13271 
13272     if (!VT.isSimple())
13273       return false;
13274 
13275     if (Subtarget->isThumb1Only())
13276       return isLegalT1ScaledAddressingMode(AM, VT);
13277 
13278     if (Subtarget->isThumb2())
13279       return isLegalT2ScaledAddressingMode(AM, VT);
13280 
13281     int Scale = AM.Scale;
13282     switch (VT.getSimpleVT().SimpleTy) {
13283     default: return false;
13284     case MVT::i1:
13285     case MVT::i8:
13286     case MVT::i32:
13287       if (Scale < 0) Scale = -Scale;
13288       if (Scale == 1)
13289         return true;
13290       // r + r << imm
13291       return isPowerOf2_32(Scale & ~1);
13292     case MVT::i16:
13293     case MVT::i64:
13294       // r +/- r
13295       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
13296         return true;
13297       // r * 2 (this can be lowered to r + r).
13298       if (!AM.HasBaseReg && Scale == 2)
13299         return true;
13300       return false;
13301 
13302     case MVT::isVoid:
13303       // Note, we allow "void" uses (basically, uses that aren't loads or
13304       // stores), because arm allows folding a scale into many arithmetic
13305       // operations.  This should be made more precise and revisited later.
13306 
13307       // Allow r << imm, but the imm has to be a multiple of two.
13308       if (Scale & 1) return false;
13309       return isPowerOf2_32(Scale);
13310     }
13311   }
13312   return true;
13313 }
13314 
13315 /// isLegalICmpImmediate - Return true if the specified immediate is legal
13316 /// icmp immediate, that is the target has icmp instructions which can compare
13317 /// a register against the immediate without having to materialize the
13318 /// immediate into a register.
13319 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13320   // Thumb2 and ARM modes can use cmn for negative immediates.
13321   if (!Subtarget->isThumb())
13322     return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
13323            ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
13324   if (Subtarget->isThumb2())
13325     return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
13326            ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
13327   // Thumb1 doesn't have cmn, and only 8-bit immediates.
13328   return Imm >= 0 && Imm <= 255;
13329 }
13330 
13331 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
13332 /// *or sub* immediate, that is the target has add or sub instructions which can
13333 /// add a register with the immediate without having to materialize the
13334 /// immediate into a register.
13335 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13336   // Same encoding for add/sub, just flip the sign.
13337   int64_t AbsImm = std::abs(Imm);
13338   if (!Subtarget->isThumb())
13339     return ARM_AM::getSOImmVal(AbsImm) != -1;
13340   if (Subtarget->isThumb2())
13341     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
13342   // Thumb1 only has 8-bit unsigned immediate.
13343   return AbsImm >= 0 && AbsImm <= 255;
13344 }
13345 
13346 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
13347                                       bool isSEXTLoad, SDValue &Base,
13348                                       SDValue &Offset, bool &isInc,
13349                                       SelectionDAG &DAG) {
13350   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13351     return false;
13352 
13353   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
13354     // AddressingMode 3
13355     Base = Ptr->getOperand(0);
13356     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13357       int RHSC = (int)RHS->getZExtValue();
13358       if (RHSC < 0 && RHSC > -256) {
13359         assert(Ptr->getOpcode() == ISD::ADD);
13360         isInc = false;
13361         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13362         return true;
13363       }
13364     }
13365     isInc = (Ptr->getOpcode() == ISD::ADD);
13366     Offset = Ptr->getOperand(1);
13367     return true;
13368   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
13369     // AddressingMode 2
13370     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13371       int RHSC = (int)RHS->getZExtValue();
13372       if (RHSC < 0 && RHSC > -0x1000) {
13373         assert(Ptr->getOpcode() == ISD::ADD);
13374         isInc = false;
13375         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13376         Base = Ptr->getOperand(0);
13377         return true;
13378       }
13379     }
13380 
13381     if (Ptr->getOpcode() == ISD::ADD) {
13382       isInc = true;
13383       ARM_AM::ShiftOpc ShOpcVal=
13384         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
13385       if (ShOpcVal != ARM_AM::no_shift) {
13386         Base = Ptr->getOperand(1);
13387         Offset = Ptr->getOperand(0);
13388       } else {
13389         Base = Ptr->getOperand(0);
13390         Offset = Ptr->getOperand(1);
13391       }
13392       return true;
13393     }
13394 
13395     isInc = (Ptr->getOpcode() == ISD::ADD);
13396     Base = Ptr->getOperand(0);
13397     Offset = Ptr->getOperand(1);
13398     return true;
13399   }
13400 
13401   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
13402   return false;
13403 }
13404 
13405 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
13406                                      bool isSEXTLoad, SDValue &Base,
13407                                      SDValue &Offset, bool &isInc,
13408                                      SelectionDAG &DAG) {
13409   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13410     return false;
13411 
13412   Base = Ptr->getOperand(0);
13413   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13414     int RHSC = (int)RHS->getZExtValue();
13415     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
13416       assert(Ptr->getOpcode() == ISD::ADD);
13417       isInc = false;
13418       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13419       return true;
13420     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
13421       isInc = Ptr->getOpcode() == ISD::ADD;
13422       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
13423       return true;
13424     }
13425   }
13426 
13427   return false;
13428 }
13429 
13430 /// getPreIndexedAddressParts - returns true by value, base pointer and
13431 /// offset pointer and addressing mode by reference if the node's address
13432 /// can be legally represented as pre-indexed load / store address.
13433 bool
13434 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
13435                                              SDValue &Offset,
13436                                              ISD::MemIndexedMode &AM,
13437                                              SelectionDAG &DAG) const {
13438   if (Subtarget->isThumb1Only())
13439     return false;
13440 
13441   EVT VT;
13442   SDValue Ptr;
13443   bool isSEXTLoad = false;
13444   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13445     Ptr = LD->getBasePtr();
13446     VT  = LD->getMemoryVT();
13447     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13448   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13449     Ptr = ST->getBasePtr();
13450     VT  = ST->getMemoryVT();
13451   } else
13452     return false;
13453 
13454   bool isInc;
13455   bool isLegal = false;
13456   if (Subtarget->isThumb2())
13457     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13458                                        Offset, isInc, DAG);
13459   else
13460     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13461                                         Offset, isInc, DAG);
13462   if (!isLegal)
13463     return false;
13464 
13465   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
13466   return true;
13467 }
13468 
13469 /// getPostIndexedAddressParts - returns true by value, base pointer and
13470 /// offset pointer and addressing mode by reference if this node can be
13471 /// combined with a load / store to form a post-indexed load / store.
13472 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
13473                                                    SDValue &Base,
13474                                                    SDValue &Offset,
13475                                                    ISD::MemIndexedMode &AM,
13476                                                    SelectionDAG &DAG) const {
13477   EVT VT;
13478   SDValue Ptr;
13479   bool isSEXTLoad = false, isNonExt;
13480   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13481     VT  = LD->getMemoryVT();
13482     Ptr = LD->getBasePtr();
13483     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13484     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
13485   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13486     VT  = ST->getMemoryVT();
13487     Ptr = ST->getBasePtr();
13488     isNonExt = !ST->isTruncatingStore();
13489   } else
13490     return false;
13491 
13492   if (Subtarget->isThumb1Only()) {
13493     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
13494     // must be non-extending/truncating, i32, with an offset of 4.
13495     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
13496     if (Op->getOpcode() != ISD::ADD || !isNonExt)
13497       return false;
13498     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
13499     if (!RHS || RHS->getZExtValue() != 4)
13500       return false;
13501 
13502     Offset = Op->getOperand(1);
13503     Base = Op->getOperand(0);
13504     AM = ISD::POST_INC;
13505     return true;
13506   }
13507 
13508   bool isInc;
13509   bool isLegal = false;
13510   if (Subtarget->isThumb2())
13511     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13512                                        isInc, DAG);
13513   else
13514     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13515                                         isInc, DAG);
13516   if (!isLegal)
13517     return false;
13518 
13519   if (Ptr != Base) {
13520     // Swap base ptr and offset to catch more post-index load / store when
13521     // it's legal. In Thumb2 mode, offset must be an immediate.
13522     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
13523         !Subtarget->isThumb2())
13524       std::swap(Base, Offset);
13525 
13526     // Post-indexed load / store update the base pointer.
13527     if (Ptr != Base)
13528       return false;
13529   }
13530 
13531   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
13532   return true;
13533 }
13534 
13535 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13536                                                       KnownBits &Known,
13537                                                       const APInt &DemandedElts,
13538                                                       const SelectionDAG &DAG,
13539                                                       unsigned Depth) const {
13540   unsigned BitWidth = Known.getBitWidth();
13541   Known.resetAll();
13542   switch (Op.getOpcode()) {
13543   default: break;
13544   case ARMISD::ADDC:
13545   case ARMISD::ADDE:
13546   case ARMISD::SUBC:
13547   case ARMISD::SUBE:
13548     // Special cases when we convert a carry to a boolean.
13549     if (Op.getResNo() == 0) {
13550       SDValue LHS = Op.getOperand(0);
13551       SDValue RHS = Op.getOperand(1);
13552       // (ADDE 0, 0, C) will give us a single bit.
13553       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
13554           isNullConstant(RHS)) {
13555         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13556         return;
13557       }
13558     }
13559     break;
13560   case ARMISD::CMOV: {
13561     // Bits are known zero/one if known on the LHS and RHS.
13562     DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1);
13563     if (Known.isUnknown())
13564       return;
13565 
13566     KnownBits KnownRHS;
13567     DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1);
13568     Known.Zero &= KnownRHS.Zero;
13569     Known.One  &= KnownRHS.One;
13570     return;
13571   }
13572   case ISD::INTRINSIC_W_CHAIN: {
13573     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
13574     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
13575     switch (IntID) {
13576     default: return;
13577     case Intrinsic::arm_ldaex:
13578     case Intrinsic::arm_ldrex: {
13579       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
13580       unsigned MemBits = VT.getScalarSizeInBits();
13581       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
13582       return;
13583     }
13584     }
13585   }
13586   case ARMISD::BFI: {
13587     // Conservatively, we can recurse down the first operand
13588     // and just mask out all affected bits.
13589     DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1);
13590 
13591     // The operand to BFI is already a mask suitable for removing the bits it
13592     // sets.
13593     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
13594     const APInt &Mask = CI->getAPIntValue();
13595     Known.Zero &= Mask;
13596     Known.One &= Mask;
13597     return;
13598   }
13599   }
13600 }
13601 
13602 bool
13603 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
13604                                                 const APInt &DemandedAPInt,
13605                                                 TargetLoweringOpt &TLO) const {
13606   // Delay optimization, so we don't have to deal with illegal types, or block
13607   // optimizations.
13608   if (!TLO.LegalOps)
13609     return false;
13610 
13611   // Only optimize AND for now.
13612   if (Op.getOpcode() != ISD::AND)
13613     return false;
13614 
13615   EVT VT = Op.getValueType();
13616 
13617   // Ignore vectors.
13618   if (VT.isVector())
13619     return false;
13620 
13621   assert(VT == MVT::i32 && "Unexpected integer type");
13622 
13623   // Make sure the RHS really is a constant.
13624   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13625   if (!C)
13626     return false;
13627 
13628   unsigned Mask = C->getZExtValue();
13629 
13630   unsigned Demanded = DemandedAPInt.getZExtValue();
13631   unsigned ShrunkMask = Mask & Demanded;
13632   unsigned ExpandedMask = Mask | ~Demanded;
13633 
13634   // If the mask is all zeros, let the target-independent code replace the
13635   // result with zero.
13636   if (ShrunkMask == 0)
13637     return false;
13638 
13639   // If the mask is all ones, erase the AND. (Currently, the target-independent
13640   // code won't do this, so we have to do it explicitly to avoid an infinite
13641   // loop in obscure cases.)
13642   if (ExpandedMask == ~0U)
13643     return TLO.CombineTo(Op, Op.getOperand(0));
13644 
13645   auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
13646     return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
13647   };
13648   auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
13649     if (NewMask == Mask)
13650       return true;
13651     SDLoc DL(Op);
13652     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
13653     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
13654     return TLO.CombineTo(Op, NewOp);
13655   };
13656 
13657   // Prefer uxtb mask.
13658   if (IsLegalMask(0xFF))
13659     return UseMask(0xFF);
13660 
13661   // Prefer uxth mask.
13662   if (IsLegalMask(0xFFFF))
13663     return UseMask(0xFFFF);
13664 
13665   // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
13666   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
13667   if (ShrunkMask < 256)
13668     return UseMask(ShrunkMask);
13669 
13670   // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
13671   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
13672   if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
13673     return UseMask(ExpandedMask);
13674 
13675   // Potential improvements:
13676   //
13677   // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
13678   // We could try to prefer Thumb1 immediates which can be lowered to a
13679   // two-instruction sequence.
13680   // We could try to recognize more legal ARM/Thumb2 immediates here.
13681 
13682   return false;
13683 }
13684 
13685 
13686 //===----------------------------------------------------------------------===//
13687 //                           ARM Inline Assembly Support
13688 //===----------------------------------------------------------------------===//
13689 
13690 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
13691   // Looking for "rev" which is V6+.
13692   if (!Subtarget->hasV6Ops())
13693     return false;
13694 
13695   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13696   std::string AsmStr = IA->getAsmString();
13697   SmallVector<StringRef, 4> AsmPieces;
13698   SplitString(AsmStr, AsmPieces, ";\n");
13699 
13700   switch (AsmPieces.size()) {
13701   default: return false;
13702   case 1:
13703     AsmStr = AsmPieces[0];
13704     AsmPieces.clear();
13705     SplitString(AsmStr, AsmPieces, " \t,");
13706 
13707     // rev $0, $1
13708     if (AsmPieces.size() == 3 &&
13709         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
13710         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
13711       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13712       if (Ty && Ty->getBitWidth() == 32)
13713         return IntrinsicLowering::LowerToByteSwap(CI);
13714     }
13715     break;
13716   }
13717 
13718   return false;
13719 }
13720 
13721 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
13722   // At this point, we have to lower this constraint to something else, so we
13723   // lower it to an "r" or "w". However, by doing this we will force the result
13724   // to be in register, while the X constraint is much more permissive.
13725   //
13726   // Although we are correct (we are free to emit anything, without
13727   // constraints), we might break use cases that would expect us to be more
13728   // efficient and emit something else.
13729   if (!Subtarget->hasVFP2())
13730     return "r";
13731   if (ConstraintVT.isFloatingPoint())
13732     return "w";
13733   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
13734      (ConstraintVT.getSizeInBits() == 64 ||
13735       ConstraintVT.getSizeInBits() == 128))
13736     return "w";
13737 
13738   return "r";
13739 }
13740 
13741 /// getConstraintType - Given a constraint letter, return the type of
13742 /// constraint it is for this target.
13743 ARMTargetLowering::ConstraintType
13744 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
13745   if (Constraint.size() == 1) {
13746     switch (Constraint[0]) {
13747     default:  break;
13748     case 'l': return C_RegisterClass;
13749     case 'w': return C_RegisterClass;
13750     case 'h': return C_RegisterClass;
13751     case 'x': return C_RegisterClass;
13752     case 't': return C_RegisterClass;
13753     case 'j': return C_Other; // Constant for movw.
13754       // An address with a single base register. Due to the way we
13755       // currently handle addresses it is the same as an 'r' memory constraint.
13756     case 'Q': return C_Memory;
13757     }
13758   } else if (Constraint.size() == 2) {
13759     switch (Constraint[0]) {
13760     default: break;
13761     // All 'U+' constraints are addresses.
13762     case 'U': return C_Memory;
13763     }
13764   }
13765   return TargetLowering::getConstraintType(Constraint);
13766 }
13767 
13768 /// Examine constraint type and operand type and determine a weight value.
13769 /// This object must already have been set up with the operand type
13770 /// and the current alternative constraint selected.
13771 TargetLowering::ConstraintWeight
13772 ARMTargetLowering::getSingleConstraintMatchWeight(
13773     AsmOperandInfo &info, const char *constraint) const {
13774   ConstraintWeight weight = CW_Invalid;
13775   Value *CallOperandVal = info.CallOperandVal;
13776     // If we don't have a value, we can't do a match,
13777     // but allow it at the lowest weight.
13778   if (!CallOperandVal)
13779     return CW_Default;
13780   Type *type = CallOperandVal->getType();
13781   // Look at the constraint type.
13782   switch (*constraint) {
13783   default:
13784     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13785     break;
13786   case 'l':
13787     if (type->isIntegerTy()) {
13788       if (Subtarget->isThumb())
13789         weight = CW_SpecificReg;
13790       else
13791         weight = CW_Register;
13792     }
13793     break;
13794   case 'w':
13795     if (type->isFloatingPointTy())
13796       weight = CW_Register;
13797     break;
13798   }
13799   return weight;
13800 }
13801 
13802 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
13803 
13804 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
13805     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
13806   if (Constraint.size() == 1) {
13807     // GCC ARM Constraint Letters
13808     switch (Constraint[0]) {
13809     case 'l': // Low regs or general regs.
13810       if (Subtarget->isThumb())
13811         return RCPair(0U, &ARM::tGPRRegClass);
13812       return RCPair(0U, &ARM::GPRRegClass);
13813     case 'h': // High regs or no regs.
13814       if (Subtarget->isThumb())
13815         return RCPair(0U, &ARM::hGPRRegClass);
13816       break;
13817     case 'r':
13818       if (Subtarget->isThumb1Only())
13819         return RCPair(0U, &ARM::tGPRRegClass);
13820       return RCPair(0U, &ARM::GPRRegClass);
13821     case 'w':
13822       if (VT == MVT::Other)
13823         break;
13824       if (VT == MVT::f32)
13825         return RCPair(0U, &ARM::SPRRegClass);
13826       if (VT.getSizeInBits() == 64)
13827         return RCPair(0U, &ARM::DPRRegClass);
13828       if (VT.getSizeInBits() == 128)
13829         return RCPair(0U, &ARM::QPRRegClass);
13830       break;
13831     case 'x':
13832       if (VT == MVT::Other)
13833         break;
13834       if (VT == MVT::f32)
13835         return RCPair(0U, &ARM::SPR_8RegClass);
13836       if (VT.getSizeInBits() == 64)
13837         return RCPair(0U, &ARM::DPR_8RegClass);
13838       if (VT.getSizeInBits() == 128)
13839         return RCPair(0U, &ARM::QPR_8RegClass);
13840       break;
13841     case 't':
13842       if (VT == MVT::Other)
13843         break;
13844       if (VT == MVT::f32 || VT == MVT::i32)
13845         return RCPair(0U, &ARM::SPRRegClass);
13846       if (VT.getSizeInBits() == 64)
13847         return RCPair(0U, &ARM::DPR_VFP2RegClass);
13848       if (VT.getSizeInBits() == 128)
13849         return RCPair(0U, &ARM::QPR_VFP2RegClass);
13850       break;
13851     }
13852   }
13853   if (StringRef("{cc}").equals_lower(Constraint))
13854     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
13855 
13856   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13857 }
13858 
13859 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13860 /// vector.  If it is invalid, don't add anything to Ops.
13861 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13862                                                      std::string &Constraint,
13863                                                      std::vector<SDValue>&Ops,
13864                                                      SelectionDAG &DAG) const {
13865   SDValue Result;
13866 
13867   // Currently only support length 1 constraints.
13868   if (Constraint.length() != 1) return;
13869 
13870   char ConstraintLetter = Constraint[0];
13871   switch (ConstraintLetter) {
13872   default: break;
13873   case 'j':
13874   case 'I': case 'J': case 'K': case 'L':
13875   case 'M': case 'N': case 'O':
13876     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
13877     if (!C)
13878       return;
13879 
13880     int64_t CVal64 = C->getSExtValue();
13881     int CVal = (int) CVal64;
13882     // None of these constraints allow values larger than 32 bits.  Check
13883     // that the value fits in an int.
13884     if (CVal != CVal64)
13885       return;
13886 
13887     switch (ConstraintLetter) {
13888       case 'j':
13889         // Constant suitable for movw, must be between 0 and
13890         // 65535.
13891         if (Subtarget->hasV6T2Ops())
13892           if (CVal >= 0 && CVal <= 65535)
13893             break;
13894         return;
13895       case 'I':
13896         if (Subtarget->isThumb1Only()) {
13897           // This must be a constant between 0 and 255, for ADD
13898           // immediates.
13899           if (CVal >= 0 && CVal <= 255)
13900             break;
13901         } else if (Subtarget->isThumb2()) {
13902           // A constant that can be used as an immediate value in a
13903           // data-processing instruction.
13904           if (ARM_AM::getT2SOImmVal(CVal) != -1)
13905             break;
13906         } else {
13907           // A constant that can be used as an immediate value in a
13908           // data-processing instruction.
13909           if (ARM_AM::getSOImmVal(CVal) != -1)
13910             break;
13911         }
13912         return;
13913 
13914       case 'J':
13915         if (Subtarget->isThumb1Only()) {
13916           // This must be a constant between -255 and -1, for negated ADD
13917           // immediates. This can be used in GCC with an "n" modifier that
13918           // prints the negated value, for use with SUB instructions. It is
13919           // not useful otherwise but is implemented for compatibility.
13920           if (CVal >= -255 && CVal <= -1)
13921             break;
13922         } else {
13923           // This must be a constant between -4095 and 4095. It is not clear
13924           // what this constraint is intended for. Implemented for
13925           // compatibility with GCC.
13926           if (CVal >= -4095 && CVal <= 4095)
13927             break;
13928         }
13929         return;
13930 
13931       case 'K':
13932         if (Subtarget->isThumb1Only()) {
13933           // A 32-bit value where only one byte has a nonzero value. Exclude
13934           // zero to match GCC. This constraint is used by GCC internally for
13935           // constants that can be loaded with a move/shift combination.
13936           // It is not useful otherwise but is implemented for compatibility.
13937           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
13938             break;
13939         } else if (Subtarget->isThumb2()) {
13940           // A constant whose bitwise inverse can be used as an immediate
13941           // value in a data-processing instruction. This can be used in GCC
13942           // with a "B" modifier that prints the inverted value, for use with
13943           // BIC and MVN instructions. It is not useful otherwise but is
13944           // implemented for compatibility.
13945           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
13946             break;
13947         } else {
13948           // A constant whose bitwise inverse can be used as an immediate
13949           // value in a data-processing instruction. This can be used in GCC
13950           // with a "B" modifier that prints the inverted value, for use with
13951           // BIC and MVN instructions. It is not useful otherwise but is
13952           // implemented for compatibility.
13953           if (ARM_AM::getSOImmVal(~CVal) != -1)
13954             break;
13955         }
13956         return;
13957 
13958       case 'L':
13959         if (Subtarget->isThumb1Only()) {
13960           // This must be a constant between -7 and 7,
13961           // for 3-operand ADD/SUB immediate instructions.
13962           if (CVal >= -7 && CVal < 7)
13963             break;
13964         } else if (Subtarget->isThumb2()) {
13965           // A constant whose negation can be used as an immediate value in a
13966           // data-processing instruction. This can be used in GCC with an "n"
13967           // modifier that prints the negated value, for use with SUB
13968           // instructions. It is not useful otherwise but is implemented for
13969           // compatibility.
13970           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
13971             break;
13972         } else {
13973           // A constant whose negation can be used as an immediate value in a
13974           // data-processing instruction. This can be used in GCC with an "n"
13975           // modifier that prints the negated value, for use with SUB
13976           // instructions. It is not useful otherwise but is implemented for
13977           // compatibility.
13978           if (ARM_AM::getSOImmVal(-CVal) != -1)
13979             break;
13980         }
13981         return;
13982 
13983       case 'M':
13984         if (Subtarget->isThumb1Only()) {
13985           // This must be a multiple of 4 between 0 and 1020, for
13986           // ADD sp + immediate.
13987           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
13988             break;
13989         } else {
13990           // A power of two or a constant between 0 and 32.  This is used in
13991           // GCC for the shift amount on shifted register operands, but it is
13992           // useful in general for any shift amounts.
13993           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
13994             break;
13995         }
13996         return;
13997 
13998       case 'N':
13999         if (Subtarget->isThumb()) {  // FIXME thumb2
14000           // This must be a constant between 0 and 31, for shift amounts.
14001           if (CVal >= 0 && CVal <= 31)
14002             break;
14003         }
14004         return;
14005 
14006       case 'O':
14007         if (Subtarget->isThumb()) {  // FIXME thumb2
14008           // This must be a multiple of 4 between -508 and 508, for
14009           // ADD/SUB sp = sp + immediate.
14010           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
14011             break;
14012         }
14013         return;
14014     }
14015     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
14016     break;
14017   }
14018 
14019   if (Result.getNode()) {
14020     Ops.push_back(Result);
14021     return;
14022   }
14023   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14024 }
14025 
14026 static RTLIB::Libcall getDivRemLibcall(
14027     const SDNode *N, MVT::SimpleValueType SVT) {
14028   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
14029           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
14030          "Unhandled Opcode in getDivRemLibcall");
14031   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
14032                   N->getOpcode() == ISD::SREM;
14033   RTLIB::Libcall LC;
14034   switch (SVT) {
14035   default: llvm_unreachable("Unexpected request for libcall!");
14036   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
14037   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
14038   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
14039   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
14040   }
14041   return LC;
14042 }
14043 
14044 static TargetLowering::ArgListTy getDivRemArgList(
14045     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
14046   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
14047           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
14048          "Unhandled Opcode in getDivRemArgList");
14049   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
14050                   N->getOpcode() == ISD::SREM;
14051   TargetLowering::ArgListTy Args;
14052   TargetLowering::ArgListEntry Entry;
14053   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14054     EVT ArgVT = N->getOperand(i).getValueType();
14055     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
14056     Entry.Node = N->getOperand(i);
14057     Entry.Ty = ArgTy;
14058     Entry.IsSExt = isSigned;
14059     Entry.IsZExt = !isSigned;
14060     Args.push_back(Entry);
14061   }
14062   if (Subtarget->isTargetWindows() && Args.size() >= 2)
14063     std::swap(Args[0], Args[1]);
14064   return Args;
14065 }
14066 
14067 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
14068   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
14069           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
14070           Subtarget->isTargetWindows()) &&
14071          "Register-based DivRem lowering only");
14072   unsigned Opcode = Op->getOpcode();
14073   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
14074          "Invalid opcode for Div/Rem lowering");
14075   bool isSigned = (Opcode == ISD::SDIVREM);
14076   EVT VT = Op->getValueType(0);
14077   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
14078   SDLoc dl(Op);
14079 
14080   // If the target has hardware divide, use divide + multiply + subtract:
14081   //     div = a / b
14082   //     rem = a - b * div
14083   //     return {div, rem}
14084   // This should be lowered into UDIV/SDIV + MLS later on.
14085   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
14086                                         : Subtarget->hasDivideInARMMode();
14087   if (hasDivide && Op->getValueType(0).isSimple() &&
14088       Op->getSimpleValueType(0) == MVT::i32) {
14089     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
14090     const SDValue Dividend = Op->getOperand(0);
14091     const SDValue Divisor = Op->getOperand(1);
14092     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
14093     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
14094     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
14095 
14096     SDValue Values[2] = {Div, Rem};
14097     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
14098   }
14099 
14100   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
14101                                        VT.getSimpleVT().SimpleTy);
14102   SDValue InChain = DAG.getEntryNode();
14103 
14104   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
14105                                                     DAG.getContext(),
14106                                                     Subtarget);
14107 
14108   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
14109                                          getPointerTy(DAG.getDataLayout()));
14110 
14111   Type *RetTy = StructType::get(Ty, Ty);
14112 
14113   if (Subtarget->isTargetWindows())
14114     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
14115 
14116   TargetLowering::CallLoweringInfo CLI(DAG);
14117   CLI.setDebugLoc(dl).setChain(InChain)
14118     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
14119     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
14120 
14121   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
14122   return CallInfo.first;
14123 }
14124 
14125 // Lowers REM using divmod helpers
14126 // see RTABI section 4.2/4.3
14127 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
14128   // Build return types (div and rem)
14129   std::vector<Type*> RetTyParams;
14130   Type *RetTyElement;
14131 
14132   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
14133   default: llvm_unreachable("Unexpected request for libcall!");
14134   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
14135   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
14136   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
14137   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
14138   }
14139 
14140   RetTyParams.push_back(RetTyElement);
14141   RetTyParams.push_back(RetTyElement);
14142   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
14143   Type *RetTy = StructType::get(*DAG.getContext(), ret);
14144 
14145   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
14146                                                              SimpleTy);
14147   SDValue InChain = DAG.getEntryNode();
14148   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
14149                                                     Subtarget);
14150   bool isSigned = N->getOpcode() == ISD::SREM;
14151   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
14152                                          getPointerTy(DAG.getDataLayout()));
14153 
14154   if (Subtarget->isTargetWindows())
14155     InChain = WinDBZCheckDenominator(DAG, N, InChain);
14156 
14157   // Lower call
14158   CallLoweringInfo CLI(DAG);
14159   CLI.setChain(InChain)
14160      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
14161      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
14162   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
14163 
14164   // Return second (rem) result operand (first contains div)
14165   SDNode *ResNode = CallResult.first.getNode();
14166   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
14167   return ResNode->getOperand(1);
14168 }
14169 
14170 SDValue
14171 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
14172   assert(Subtarget->isTargetWindows() && "unsupported target platform");
14173   SDLoc DL(Op);
14174 
14175   // Get the inputs.
14176   SDValue Chain = Op.getOperand(0);
14177   SDValue Size  = Op.getOperand(1);
14178 
14179   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
14180           "no-stack-arg-probe")) {
14181     unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14182     SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
14183     Chain = SP.getValue(1);
14184     SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
14185     if (Align)
14186       SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
14187                        DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
14188     Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
14189     SDValue Ops[2] = { SP, Chain };
14190     return DAG.getMergeValues(Ops, DL);
14191   }
14192 
14193   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
14194                               DAG.getConstant(2, DL, MVT::i32));
14195 
14196   SDValue Flag;
14197   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
14198   Flag = Chain.getValue(1);
14199 
14200   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14201   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
14202 
14203   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
14204   Chain = NewSP.getValue(1);
14205 
14206   SDValue Ops[2] = { NewSP, Chain };
14207   return DAG.getMergeValues(Ops, DL);
14208 }
14209 
14210 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
14211   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
14212          "Unexpected type for custom-lowering FP_EXTEND");
14213 
14214   RTLIB::Libcall LC;
14215   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
14216 
14217   SDValue SrcVal = Op.getOperand(0);
14218   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
14219                      SDLoc(Op)).first;
14220 }
14221 
14222 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
14223   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
14224          Subtarget->isFPOnlySP() &&
14225          "Unexpected type for custom-lowering FP_ROUND");
14226 
14227   RTLIB::Libcall LC;
14228   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
14229 
14230   SDValue SrcVal = Op.getOperand(0);
14231   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
14232                      SDLoc(Op)).first;
14233 }
14234 
14235 bool
14236 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14237   // The ARM target isn't yet aware of offsets.
14238   return false;
14239 }
14240 
14241 bool ARM::isBitFieldInvertedMask(unsigned v) {
14242   if (v == 0xffffffff)
14243     return false;
14244 
14245   // there can be 1's on either or both "outsides", all the "inside"
14246   // bits must be 0's
14247   return isShiftedMask_32(~v);
14248 }
14249 
14250 /// isFPImmLegal - Returns true if the target can instruction select the
14251 /// specified FP immediate natively. If false, the legalizer will
14252 /// materialize the FP immediate as a load from a constant pool.
14253 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
14254   if (!Subtarget->hasVFP3())
14255     return false;
14256   if (VT == MVT::f16 && Subtarget->hasFullFP16())
14257     return ARM_AM::getFP16Imm(Imm) != -1;
14258   if (VT == MVT::f32)
14259     return ARM_AM::getFP32Imm(Imm) != -1;
14260   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
14261     return ARM_AM::getFP64Imm(Imm) != -1;
14262   return false;
14263 }
14264 
14265 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
14266 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
14267 /// specified in the intrinsic calls.
14268 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14269                                            const CallInst &I,
14270                                            MachineFunction &MF,
14271                                            unsigned Intrinsic) const {
14272   switch (Intrinsic) {
14273   case Intrinsic::arm_neon_vld1:
14274   case Intrinsic::arm_neon_vld2:
14275   case Intrinsic::arm_neon_vld3:
14276   case Intrinsic::arm_neon_vld4:
14277   case Intrinsic::arm_neon_vld2lane:
14278   case Intrinsic::arm_neon_vld3lane:
14279   case Intrinsic::arm_neon_vld4lane:
14280   case Intrinsic::arm_neon_vld2dup:
14281   case Intrinsic::arm_neon_vld3dup:
14282   case Intrinsic::arm_neon_vld4dup: {
14283     Info.opc = ISD::INTRINSIC_W_CHAIN;
14284     // Conservatively set memVT to the entire set of vectors loaded.
14285     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14286     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
14287     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14288     Info.ptrVal = I.getArgOperand(0);
14289     Info.offset = 0;
14290     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
14291     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
14292     // volatile loads with NEON intrinsics not supported
14293     Info.flags = MachineMemOperand::MOLoad;
14294     return true;
14295   }
14296   case Intrinsic::arm_neon_vld1x2:
14297   case Intrinsic::arm_neon_vld1x3:
14298   case Intrinsic::arm_neon_vld1x4: {
14299     Info.opc = ISD::INTRINSIC_W_CHAIN;
14300     // Conservatively set memVT to the entire set of vectors loaded.
14301     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14302     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
14303     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14304     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
14305     Info.offset = 0;
14306     Info.align = 0;
14307     // volatile loads with NEON intrinsics not supported
14308     Info.flags = MachineMemOperand::MOLoad;
14309     return true;
14310   }
14311   case Intrinsic::arm_neon_vst1:
14312   case Intrinsic::arm_neon_vst2:
14313   case Intrinsic::arm_neon_vst3:
14314   case Intrinsic::arm_neon_vst4:
14315   case Intrinsic::arm_neon_vst2lane:
14316   case Intrinsic::arm_neon_vst3lane:
14317   case Intrinsic::arm_neon_vst4lane: {
14318     Info.opc = ISD::INTRINSIC_VOID;
14319     // Conservatively set memVT to the entire set of vectors stored.
14320     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14321     unsigned NumElts = 0;
14322     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
14323       Type *ArgTy = I.getArgOperand(ArgI)->getType();
14324       if (!ArgTy->isVectorTy())
14325         break;
14326       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
14327     }
14328     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14329     Info.ptrVal = I.getArgOperand(0);
14330     Info.offset = 0;
14331     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
14332     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
14333     // volatile stores with NEON intrinsics not supported
14334     Info.flags = MachineMemOperand::MOStore;
14335     return true;
14336   }
14337   case Intrinsic::arm_neon_vst1x2:
14338   case Intrinsic::arm_neon_vst1x3:
14339   case Intrinsic::arm_neon_vst1x4: {
14340     Info.opc = ISD::INTRINSIC_VOID;
14341     // Conservatively set memVT to the entire set of vectors stored.
14342     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14343     unsigned NumElts = 0;
14344     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
14345       Type *ArgTy = I.getArgOperand(ArgI)->getType();
14346       if (!ArgTy->isVectorTy())
14347         break;
14348       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
14349     }
14350     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14351     Info.ptrVal = I.getArgOperand(0);
14352     Info.offset = 0;
14353     Info.align = 0;
14354     // volatile stores with NEON intrinsics not supported
14355     Info.flags = MachineMemOperand::MOStore;
14356     return true;
14357   }
14358   case Intrinsic::arm_ldaex:
14359   case Intrinsic::arm_ldrex: {
14360     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14361     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
14362     Info.opc = ISD::INTRINSIC_W_CHAIN;
14363     Info.memVT = MVT::getVT(PtrTy->getElementType());
14364     Info.ptrVal = I.getArgOperand(0);
14365     Info.offset = 0;
14366     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
14367     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
14368     return true;
14369   }
14370   case Intrinsic::arm_stlex:
14371   case Intrinsic::arm_strex: {
14372     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14373     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
14374     Info.opc = ISD::INTRINSIC_W_CHAIN;
14375     Info.memVT = MVT::getVT(PtrTy->getElementType());
14376     Info.ptrVal = I.getArgOperand(1);
14377     Info.offset = 0;
14378     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
14379     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
14380     return true;
14381   }
14382   case Intrinsic::arm_stlexd:
14383   case Intrinsic::arm_strexd:
14384     Info.opc = ISD::INTRINSIC_W_CHAIN;
14385     Info.memVT = MVT::i64;
14386     Info.ptrVal = I.getArgOperand(2);
14387     Info.offset = 0;
14388     Info.align = 8;
14389     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
14390     return true;
14391 
14392   case Intrinsic::arm_ldaexd:
14393   case Intrinsic::arm_ldrexd:
14394     Info.opc = ISD::INTRINSIC_W_CHAIN;
14395     Info.memVT = MVT::i64;
14396     Info.ptrVal = I.getArgOperand(0);
14397     Info.offset = 0;
14398     Info.align = 8;
14399     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
14400     return true;
14401 
14402   default:
14403     break;
14404   }
14405 
14406   return false;
14407 }
14408 
14409 /// Returns true if it is beneficial to convert a load of a constant
14410 /// to just the constant itself.
14411 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
14412                                                           Type *Ty) const {
14413   assert(Ty->isIntegerTy());
14414 
14415   unsigned Bits = Ty->getPrimitiveSizeInBits();
14416   if (Bits == 0 || Bits > 32)
14417     return false;
14418   return true;
14419 }
14420 
14421 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
14422                                                 unsigned Index) const {
14423   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
14424     return false;
14425 
14426   return (Index == 0 || Index == ResVT.getVectorNumElements());
14427 }
14428 
14429 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
14430                                         ARM_MB::MemBOpt Domain) const {
14431   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14432 
14433   // First, if the target has no DMB, see what fallback we can use.
14434   if (!Subtarget->hasDataBarrier()) {
14435     // Some ARMv6 cpus can support data barriers with an mcr instruction.
14436     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
14437     // here.
14438     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
14439       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
14440       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
14441                         Builder.getInt32(0), Builder.getInt32(7),
14442                         Builder.getInt32(10), Builder.getInt32(5)};
14443       return Builder.CreateCall(MCR, args);
14444     } else {
14445       // Instead of using barriers, atomic accesses on these subtargets use
14446       // libcalls.
14447       llvm_unreachable("makeDMB on a target so old that it has no barriers");
14448     }
14449   } else {
14450     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
14451     // Only a full system barrier exists in the M-class architectures.
14452     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
14453     Constant *CDomain = Builder.getInt32(Domain);
14454     return Builder.CreateCall(DMB, CDomain);
14455   }
14456 }
14457 
14458 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
14459 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
14460                                                  Instruction *Inst,
14461                                                  AtomicOrdering Ord) const {
14462   switch (Ord) {
14463   case AtomicOrdering::NotAtomic:
14464   case AtomicOrdering::Unordered:
14465     llvm_unreachable("Invalid fence: unordered/non-atomic");
14466   case AtomicOrdering::Monotonic:
14467   case AtomicOrdering::Acquire:
14468     return nullptr; // Nothing to do
14469   case AtomicOrdering::SequentiallyConsistent:
14470     if (!Inst->hasAtomicStore())
14471       return nullptr; // Nothing to do
14472     LLVM_FALLTHROUGH;
14473   case AtomicOrdering::Release:
14474   case AtomicOrdering::AcquireRelease:
14475     if (Subtarget->preferISHSTBarriers())
14476       return makeDMB(Builder, ARM_MB::ISHST);
14477     // FIXME: add a comment with a link to documentation justifying this.
14478     else
14479       return makeDMB(Builder, ARM_MB::ISH);
14480   }
14481   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
14482 }
14483 
14484 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
14485                                                   Instruction *Inst,
14486                                                   AtomicOrdering Ord) const {
14487   switch (Ord) {
14488   case AtomicOrdering::NotAtomic:
14489   case AtomicOrdering::Unordered:
14490     llvm_unreachable("Invalid fence: unordered/not-atomic");
14491   case AtomicOrdering::Monotonic:
14492   case AtomicOrdering::Release:
14493     return nullptr; // Nothing to do
14494   case AtomicOrdering::Acquire:
14495   case AtomicOrdering::AcquireRelease:
14496   case AtomicOrdering::SequentiallyConsistent:
14497     return makeDMB(Builder, ARM_MB::ISH);
14498   }
14499   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
14500 }
14501 
14502 // Loads and stores less than 64-bits are already atomic; ones above that
14503 // are doomed anyway, so defer to the default libcall and blame the OS when
14504 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
14505 // anything for those.
14506 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
14507   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
14508   return (Size == 64) && !Subtarget->isMClass();
14509 }
14510 
14511 // Loads and stores less than 64-bits are already atomic; ones above that
14512 // are doomed anyway, so defer to the default libcall and blame the OS when
14513 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
14514 // anything for those.
14515 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
14516 // guarantee, see DDI0406C ARM architecture reference manual,
14517 // sections A8.8.72-74 LDRD)
14518 TargetLowering::AtomicExpansionKind
14519 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
14520   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
14521   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
14522                                                   : AtomicExpansionKind::None;
14523 }
14524 
14525 // For the real atomic operations, we have ldrex/strex up to 32 bits,
14526 // and up to 64 bits on the non-M profiles
14527 TargetLowering::AtomicExpansionKind
14528 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
14529   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
14530   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
14531   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
14532              ? AtomicExpansionKind::LLSC
14533              : AtomicExpansionKind::None;
14534 }
14535 
14536 TargetLowering::AtomicExpansionKind
14537 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
14538   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
14539   // implement cmpxchg without spilling. If the address being exchanged is also
14540   // on the stack and close enough to the spill slot, this can lead to a
14541   // situation where the monitor always gets cleared and the atomic operation
14542   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
14543   bool HasAtomicCmpXchg =
14544       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
14545   if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
14546     return AtomicExpansionKind::LLSC;
14547   return AtomicExpansionKind::None;
14548 }
14549 
14550 bool ARMTargetLowering::shouldInsertFencesForAtomic(
14551     const Instruction *I) const {
14552   return InsertFencesForAtomic;
14553 }
14554 
14555 // This has so far only been implemented for MachO.
14556 bool ARMTargetLowering::useLoadStackGuardNode() const {
14557   return Subtarget->isTargetMachO();
14558 }
14559 
14560 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
14561                                                   unsigned &Cost) const {
14562   // If we do not have NEON, vector types are not natively supported.
14563   if (!Subtarget->hasNEON())
14564     return false;
14565 
14566   // Floating point values and vector values map to the same register file.
14567   // Therefore, although we could do a store extract of a vector type, this is
14568   // better to leave at float as we have more freedom in the addressing mode for
14569   // those.
14570   if (VectorTy->isFPOrFPVectorTy())
14571     return false;
14572 
14573   // If the index is unknown at compile time, this is very expensive to lower
14574   // and it is not possible to combine the store with the extract.
14575   if (!isa<ConstantInt>(Idx))
14576     return false;
14577 
14578   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
14579   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
14580   // We can do a store + vector extract on any vector that fits perfectly in a D
14581   // or Q register.
14582   if (BitWidth == 64 || BitWidth == 128) {
14583     Cost = 0;
14584     return true;
14585   }
14586   return false;
14587 }
14588 
14589 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
14590   return Subtarget->hasV6T2Ops();
14591 }
14592 
14593 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
14594   return Subtarget->hasV6T2Ops();
14595 }
14596 
14597 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
14598                                          AtomicOrdering Ord) const {
14599   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14600   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
14601   bool IsAcquire = isAcquireOrStronger(Ord);
14602 
14603   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
14604   // intrinsic must return {i32, i32} and we have to recombine them into a
14605   // single i64 here.
14606   if (ValTy->getPrimitiveSizeInBits() == 64) {
14607     Intrinsic::ID Int =
14608         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
14609     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
14610 
14611     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14612     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
14613 
14614     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
14615     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
14616     if (!Subtarget->isLittle())
14617       std::swap (Lo, Hi);
14618     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
14619     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
14620     return Builder.CreateOr(
14621         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
14622   }
14623 
14624   Type *Tys[] = { Addr->getType() };
14625   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
14626   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
14627 
14628   return Builder.CreateTruncOrBitCast(
14629       Builder.CreateCall(Ldrex, Addr),
14630       cast<PointerType>(Addr->getType())->getElementType());
14631 }
14632 
14633 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
14634     IRBuilder<> &Builder) const {
14635   if (!Subtarget->hasV7Ops())
14636     return;
14637   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14638   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
14639 }
14640 
14641 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
14642                                                Value *Addr,
14643                                                AtomicOrdering Ord) const {
14644   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14645   bool IsRelease = isReleaseOrStronger(Ord);
14646 
14647   // Since the intrinsics must have legal type, the i64 intrinsics take two
14648   // parameters: "i32, i32". We must marshal Val into the appropriate form
14649   // before the call.
14650   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
14651     Intrinsic::ID Int =
14652         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
14653     Function *Strex = Intrinsic::getDeclaration(M, Int);
14654     Type *Int32Ty = Type::getInt32Ty(M->getContext());
14655 
14656     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
14657     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
14658     if (!Subtarget->isLittle())
14659       std::swap(Lo, Hi);
14660     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14661     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
14662   }
14663 
14664   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
14665   Type *Tys[] = { Addr->getType() };
14666   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
14667 
14668   return Builder.CreateCall(
14669       Strex, {Builder.CreateZExtOrBitCast(
14670                   Val, Strex->getFunctionType()->getParamType(0)),
14671               Addr});
14672 }
14673 
14674 
14675 bool ARMTargetLowering::alignLoopsWithOptSize() const {
14676   return Subtarget->isMClass();
14677 }
14678 
14679 /// A helper function for determining the number of interleaved accesses we
14680 /// will generate when lowering accesses of the given type.
14681 unsigned
14682 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
14683                                              const DataLayout &DL) const {
14684   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
14685 }
14686 
14687 bool ARMTargetLowering::isLegalInterleavedAccessType(
14688     VectorType *VecTy, const DataLayout &DL) const {
14689 
14690   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
14691   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
14692 
14693   // Ensure the vector doesn't have f16 elements. Even though we could do an
14694   // i16 vldN, we can't hold the f16 vectors and will end up converting via
14695   // f32.
14696   if (VecTy->getElementType()->isHalfTy())
14697     return false;
14698 
14699   // Ensure the number of vector elements is greater than 1.
14700   if (VecTy->getNumElements() < 2)
14701     return false;
14702 
14703   // Ensure the element type is legal.
14704   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
14705     return false;
14706 
14707   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
14708   // 128 will be split into multiple interleaved accesses.
14709   return VecSize == 64 || VecSize % 128 == 0;
14710 }
14711 
14712 /// Lower an interleaved load into a vldN intrinsic.
14713 ///
14714 /// E.g. Lower an interleaved load (Factor = 2):
14715 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
14716 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
14717 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
14718 ///
14719 ///      Into:
14720 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
14721 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
14722 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
14723 bool ARMTargetLowering::lowerInterleavedLoad(
14724     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
14725     ArrayRef<unsigned> Indices, unsigned Factor) const {
14726   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14727          "Invalid interleave factor");
14728   assert(!Shuffles.empty() && "Empty shufflevector input");
14729   assert(Shuffles.size() == Indices.size() &&
14730          "Unmatched number of shufflevectors and indices");
14731 
14732   VectorType *VecTy = Shuffles[0]->getType();
14733   Type *EltTy = VecTy->getVectorElementType();
14734 
14735   const DataLayout &DL = LI->getModule()->getDataLayout();
14736 
14737   // Skip if we do not have NEON and skip illegal vector types. We can
14738   // "legalize" wide vector types into multiple interleaved accesses as long as
14739   // the vector types are divisible by 128.
14740   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
14741     return false;
14742 
14743   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
14744 
14745   // A pointer vector can not be the return type of the ldN intrinsics. Need to
14746   // load integer vectors first and then convert to pointer vectors.
14747   if (EltTy->isPointerTy())
14748     VecTy =
14749         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
14750 
14751   IRBuilder<> Builder(LI);
14752 
14753   // The base address of the load.
14754   Value *BaseAddr = LI->getPointerOperand();
14755 
14756   if (NumLoads > 1) {
14757     // If we're going to generate more than one load, reset the sub-vector type
14758     // to something legal.
14759     VecTy = VectorType::get(VecTy->getVectorElementType(),
14760                             VecTy->getVectorNumElements() / NumLoads);
14761 
14762     // We will compute the pointer operand of each load from the original base
14763     // address using GEPs. Cast the base address to a pointer to the scalar
14764     // element type.
14765     BaseAddr = Builder.CreateBitCast(
14766         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
14767                       LI->getPointerAddressSpace()));
14768   }
14769 
14770   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
14771 
14772   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
14773   Type *Tys[] = {VecTy, Int8Ptr};
14774   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
14775                                             Intrinsic::arm_neon_vld3,
14776                                             Intrinsic::arm_neon_vld4};
14777   Function *VldnFunc =
14778       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
14779 
14780   // Holds sub-vectors extracted from the load intrinsic return values. The
14781   // sub-vectors are associated with the shufflevector instructions they will
14782   // replace.
14783   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
14784 
14785   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
14786     // If we're generating more than one load, compute the base address of
14787     // subsequent loads as an offset from the previous.
14788     if (LoadCount > 0)
14789       BaseAddr = Builder.CreateConstGEP1_32(
14790           BaseAddr, VecTy->getVectorNumElements() * Factor);
14791 
14792     SmallVector<Value *, 2> Ops;
14793     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14794     Ops.push_back(Builder.getInt32(LI->getAlignment()));
14795 
14796     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
14797 
14798     // Replace uses of each shufflevector with the corresponding vector loaded
14799     // by ldN.
14800     for (unsigned i = 0; i < Shuffles.size(); i++) {
14801       ShuffleVectorInst *SV = Shuffles[i];
14802       unsigned Index = Indices[i];
14803 
14804       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
14805 
14806       // Convert the integer vector to pointer vector if the element is pointer.
14807       if (EltTy->isPointerTy())
14808         SubVec = Builder.CreateIntToPtr(
14809             SubVec, VectorType::get(SV->getType()->getVectorElementType(),
14810                                     VecTy->getVectorNumElements()));
14811 
14812       SubVecs[SV].push_back(SubVec);
14813     }
14814   }
14815 
14816   // Replace uses of the shufflevector instructions with the sub-vectors
14817   // returned by the load intrinsic. If a shufflevector instruction is
14818   // associated with more than one sub-vector, those sub-vectors will be
14819   // concatenated into a single wide vector.
14820   for (ShuffleVectorInst *SVI : Shuffles) {
14821     auto &SubVec = SubVecs[SVI];
14822     auto *WideVec =
14823         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
14824     SVI->replaceAllUsesWith(WideVec);
14825   }
14826 
14827   return true;
14828 }
14829 
14830 /// Lower an interleaved store into a vstN intrinsic.
14831 ///
14832 /// E.g. Lower an interleaved store (Factor = 3):
14833 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
14834 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
14835 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
14836 ///
14837 ///      Into:
14838 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
14839 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
14840 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
14841 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14842 ///
14843 /// Note that the new shufflevectors will be removed and we'll only generate one
14844 /// vst3 instruction in CodeGen.
14845 ///
14846 /// Example for a more general valid mask (Factor 3). Lower:
14847 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
14848 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
14849 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
14850 ///
14851 ///      Into:
14852 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
14853 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
14854 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
14855 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14856 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
14857                                               ShuffleVectorInst *SVI,
14858                                               unsigned Factor) const {
14859   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14860          "Invalid interleave factor");
14861 
14862   VectorType *VecTy = SVI->getType();
14863   assert(VecTy->getVectorNumElements() % Factor == 0 &&
14864          "Invalid interleaved store");
14865 
14866   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
14867   Type *EltTy = VecTy->getVectorElementType();
14868   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
14869 
14870   const DataLayout &DL = SI->getModule()->getDataLayout();
14871 
14872   // Skip if we do not have NEON and skip illegal vector types. We can
14873   // "legalize" wide vector types into multiple interleaved accesses as long as
14874   // the vector types are divisible by 128.
14875   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
14876     return false;
14877 
14878   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
14879 
14880   Value *Op0 = SVI->getOperand(0);
14881   Value *Op1 = SVI->getOperand(1);
14882   IRBuilder<> Builder(SI);
14883 
14884   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
14885   // vectors to integer vectors.
14886   if (EltTy->isPointerTy()) {
14887     Type *IntTy = DL.getIntPtrType(EltTy);
14888 
14889     // Convert to the corresponding integer vector.
14890     Type *IntVecTy =
14891         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
14892     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
14893     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
14894 
14895     SubVecTy = VectorType::get(IntTy, LaneLen);
14896   }
14897 
14898   // The base address of the store.
14899   Value *BaseAddr = SI->getPointerOperand();
14900 
14901   if (NumStores > 1) {
14902     // If we're going to generate more than one store, reset the lane length
14903     // and sub-vector type to something legal.
14904     LaneLen /= NumStores;
14905     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
14906 
14907     // We will compute the pointer operand of each store from the original base
14908     // address using GEPs. Cast the base address to a pointer to the scalar
14909     // element type.
14910     BaseAddr = Builder.CreateBitCast(
14911         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
14912                       SI->getPointerAddressSpace()));
14913   }
14914 
14915   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
14916 
14917   auto Mask = SVI->getShuffleMask();
14918 
14919   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
14920   Type *Tys[] = {Int8Ptr, SubVecTy};
14921   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
14922                                              Intrinsic::arm_neon_vst3,
14923                                              Intrinsic::arm_neon_vst4};
14924 
14925   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
14926     // If we generating more than one store, we compute the base address of
14927     // subsequent stores as an offset from the previous.
14928     if (StoreCount > 0)
14929       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
14930 
14931     SmallVector<Value *, 6> Ops;
14932     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14933 
14934     Function *VstNFunc =
14935         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
14936 
14937     // Split the shufflevector operands into sub vectors for the new vstN call.
14938     for (unsigned i = 0; i < Factor; i++) {
14939       unsigned IdxI = StoreCount * LaneLen * Factor + i;
14940       if (Mask[IdxI] >= 0) {
14941         Ops.push_back(Builder.CreateShuffleVector(
14942             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
14943       } else {
14944         unsigned StartMask = 0;
14945         for (unsigned j = 1; j < LaneLen; j++) {
14946           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
14947           if (Mask[IdxJ * Factor + IdxI] >= 0) {
14948             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
14949             break;
14950           }
14951         }
14952         // Note: If all elements in a chunk are undefs, StartMask=0!
14953         // Note: Filling undef gaps with random elements is ok, since
14954         // those elements were being written anyway (with undefs).
14955         // In the case of all undefs we're defaulting to using elems from 0
14956         // Note: StartMask cannot be negative, it's checked in
14957         // isReInterleaveMask
14958         Ops.push_back(Builder.CreateShuffleVector(
14959             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
14960       }
14961     }
14962 
14963     Ops.push_back(Builder.getInt32(SI->getAlignment()));
14964     Builder.CreateCall(VstNFunc, Ops);
14965   }
14966   return true;
14967 }
14968 
14969 enum HABaseType {
14970   HA_UNKNOWN = 0,
14971   HA_FLOAT,
14972   HA_DOUBLE,
14973   HA_VECT64,
14974   HA_VECT128
14975 };
14976 
14977 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
14978                                    uint64_t &Members) {
14979   if (auto *ST = dyn_cast<StructType>(Ty)) {
14980     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
14981       uint64_t SubMembers = 0;
14982       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
14983         return false;
14984       Members += SubMembers;
14985     }
14986   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
14987     uint64_t SubMembers = 0;
14988     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
14989       return false;
14990     Members += SubMembers * AT->getNumElements();
14991   } else if (Ty->isFloatTy()) {
14992     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
14993       return false;
14994     Members = 1;
14995     Base = HA_FLOAT;
14996   } else if (Ty->isDoubleTy()) {
14997     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
14998       return false;
14999     Members = 1;
15000     Base = HA_DOUBLE;
15001   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
15002     Members = 1;
15003     switch (Base) {
15004     case HA_FLOAT:
15005     case HA_DOUBLE:
15006       return false;
15007     case HA_VECT64:
15008       return VT->getBitWidth() == 64;
15009     case HA_VECT128:
15010       return VT->getBitWidth() == 128;
15011     case HA_UNKNOWN:
15012       switch (VT->getBitWidth()) {
15013       case 64:
15014         Base = HA_VECT64;
15015         return true;
15016       case 128:
15017         Base = HA_VECT128;
15018         return true;
15019       default:
15020         return false;
15021       }
15022     }
15023   }
15024 
15025   return (Members > 0 && Members <= 4);
15026 }
15027 
15028 /// Return the correct alignment for the current calling convention.
15029 unsigned
15030 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
15031                                                  DataLayout DL) const {
15032   if (!ArgTy->isVectorTy())
15033     return DL.getABITypeAlignment(ArgTy);
15034 
15035   // Avoid over-aligning vector parameters. It would require realigning the
15036   // stack and waste space for no real benefit.
15037   return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment());
15038 }
15039 
15040 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
15041 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
15042 /// passing according to AAPCS rules.
15043 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
15044     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
15045   if (getEffectiveCallingConv(CallConv, isVarArg) !=
15046       CallingConv::ARM_AAPCS_VFP)
15047     return false;
15048 
15049   HABaseType Base = HA_UNKNOWN;
15050   uint64_t Members = 0;
15051   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
15052   LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
15053 
15054   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
15055   return IsHA || IsIntArray;
15056 }
15057 
15058 unsigned ARMTargetLowering::getExceptionPointerRegister(
15059     const Constant *PersonalityFn) const {
15060   // Platforms which do not use SjLj EH may return values in these registers
15061   // via the personality function.
15062   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
15063 }
15064 
15065 unsigned ARMTargetLowering::getExceptionSelectorRegister(
15066     const Constant *PersonalityFn) const {
15067   // Platforms which do not use SjLj EH may return values in these registers
15068   // via the personality function.
15069   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
15070 }
15071 
15072 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15073   // Update IsSplitCSR in ARMFunctionInfo.
15074   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
15075   AFI->setIsSplitCSR(true);
15076 }
15077 
15078 void ARMTargetLowering::insertCopiesSplitCSR(
15079     MachineBasicBlock *Entry,
15080     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15081   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
15082   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15083   if (!IStart)
15084     return;
15085 
15086   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
15087   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15088   MachineBasicBlock::iterator MBBI = Entry->begin();
15089   for (const MCPhysReg *I = IStart; *I; ++I) {
15090     const TargetRegisterClass *RC = nullptr;
15091     if (ARM::GPRRegClass.contains(*I))
15092       RC = &ARM::GPRRegClass;
15093     else if (ARM::DPRRegClass.contains(*I))
15094       RC = &ARM::DPRRegClass;
15095     else
15096       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15097 
15098     unsigned NewVR = MRI->createVirtualRegister(RC);
15099     // Create copy from CSR to a virtual register.
15100     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15101     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15102     // nounwind. If we want to generalize this later, we may need to emit
15103     // CFI pseudo-instructions.
15104     assert(Entry->getParent()->getFunction().hasFnAttribute(
15105                Attribute::NoUnwind) &&
15106            "Function should be nounwind in insertCopiesSplitCSR!");
15107     Entry->addLiveIn(*I);
15108     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15109         .addReg(*I);
15110 
15111     // Insert the copy-back instructions right before the terminator.
15112     for (auto *Exit : Exits)
15113       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15114               TII->get(TargetOpcode::COPY), *I)
15115           .addReg(NewVR);
15116   }
15117 }
15118 
15119 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
15120   MF.getFrameInfo().computeMaxCallFrameSize(MF);
15121   TargetLoweringBase::finalizeLowering(MF);
15122 }
15123