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->hasAcquireRelease() ||
988         getTargetMachine().getOptLevel() == 0) {
989       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
990       InsertFencesForAtomic = true;
991     }
992   } else {
993     // If there's anything we can use as a barrier, go through custom lowering
994     // for ATOMIC_FENCE.
995     // If target has DMB in thumb, Fences can be inserted.
996     if (Subtarget->hasDataBarrier())
997       InsertFencesForAtomic = true;
998 
999     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1000                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1001 
1002     // Set them all for expansion, which will force libcalls.
1003     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1004     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1005     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1006     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1007     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1008     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1009     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1010     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1011     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1012     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1013     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1014     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1015     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1016     // Unordered/Monotonic case.
1017     if (!InsertFencesForAtomic) {
1018       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1019       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1020     }
1021   }
1022 
1023   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1024 
1025   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1026   if (!Subtarget->hasV6Ops()) {
1027     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1028     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1029   }
1030   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1031 
1032   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1033       !Subtarget->isThumb1Only()) {
1034     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1035     // iff target supports vfp2.
1036     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1037     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1038   }
1039 
1040   // We want to custom lower some of our intrinsics.
1041   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1042   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1043   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1044   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1045   if (Subtarget->useSjLjEH())
1046     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1047 
1048   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1049   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1050   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1051   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1052   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1053   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1054   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1055   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1056   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1057   if (Subtarget->hasFullFP16()) {
1058     setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1059     setOperationAction(ISD::SELECT,    MVT::f16, Custom);
1060     setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1061   }
1062 
1063   setOperationAction(ISD::SETCCCARRY, MVT::i32, Custom);
1064 
1065   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1066   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1067   if (Subtarget->hasFullFP16())
1068       setOperationAction(ISD::BR_CC, MVT::f16,   Custom);
1069   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1070   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1071   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1072 
1073   // We don't support sin/cos/fmod/copysign/pow
1074   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1075   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1076   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1077   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1078   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1079   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1080   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1081   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1082   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1083       !Subtarget->isThumb1Only()) {
1084     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1085     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1086   }
1087   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1088   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1089 
1090   if (!Subtarget->hasVFP4()) {
1091     setOperationAction(ISD::FMA, MVT::f64, Expand);
1092     setOperationAction(ISD::FMA, MVT::f32, Expand);
1093   }
1094 
1095   // Various VFP goodness
1096   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1097     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1098     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1099       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1100       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1101     }
1102 
1103     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1104     if (!Subtarget->hasFP16()) {
1105       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1106       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1107     }
1108   }
1109 
1110   // Use __sincos_stret if available.
1111   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1112       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1113     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1114     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1115   }
1116 
1117   // FP-ARMv8 implements a lot of rounding-like FP operations.
1118   if (Subtarget->hasFPARMv8()) {
1119     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1120     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1121     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1122     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1123     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1124     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1125     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1126     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1127     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1128     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1129     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1130     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1131 
1132     if (!Subtarget->isFPOnlySP()) {
1133       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1134       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1135       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1136       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1137       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1138       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1139       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1140       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1141     }
1142   }
1143 
1144   if (Subtarget->hasNEON()) {
1145     // vmin and vmax aren't available in a scalar form, so we use
1146     // a NEON instruction with an undef lane instead.
1147     setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
1148     setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
1149     setOperationAction(ISD::FMINIMUM, MVT::f32, Legal);
1150     setOperationAction(ISD::FMAXIMUM, MVT::f32, Legal);
1151     setOperationAction(ISD::FMINIMUM, MVT::v2f32, Legal);
1152     setOperationAction(ISD::FMAXIMUM, MVT::v2f32, Legal);
1153     setOperationAction(ISD::FMINIMUM, MVT::v4f32, Legal);
1154     setOperationAction(ISD::FMAXIMUM, MVT::v4f32, Legal);
1155 
1156     if (Subtarget->hasFullFP16()) {
1157       setOperationAction(ISD::FMINNUM, MVT::v4f16, Legal);
1158       setOperationAction(ISD::FMAXNUM, MVT::v4f16, Legal);
1159       setOperationAction(ISD::FMINNUM, MVT::v8f16, Legal);
1160       setOperationAction(ISD::FMAXNUM, MVT::v8f16, Legal);
1161 
1162       setOperationAction(ISD::FMINIMUM, MVT::v4f16, Legal);
1163       setOperationAction(ISD::FMAXIMUM, MVT::v4f16, Legal);
1164       setOperationAction(ISD::FMINIMUM, MVT::v8f16, Legal);
1165       setOperationAction(ISD::FMAXIMUM, MVT::v8f16, Legal);
1166     }
1167   }
1168 
1169   // We have target-specific dag combine patterns for the following nodes:
1170   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1171   setTargetDAGCombine(ISD::ADD);
1172   setTargetDAGCombine(ISD::SUB);
1173   setTargetDAGCombine(ISD::MUL);
1174   setTargetDAGCombine(ISD::AND);
1175   setTargetDAGCombine(ISD::OR);
1176   setTargetDAGCombine(ISD::XOR);
1177 
1178   if (Subtarget->hasV6Ops())
1179     setTargetDAGCombine(ISD::SRL);
1180 
1181   setStackPointerRegisterToSaveRestore(ARM::SP);
1182 
1183   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1184       !Subtarget->hasVFP2())
1185     setSchedulingPreference(Sched::RegPressure);
1186   else
1187     setSchedulingPreference(Sched::Hybrid);
1188 
1189   //// temporary - rewrite interface to use type
1190   MaxStoresPerMemset = 8;
1191   MaxStoresPerMemsetOptSize = 4;
1192   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1193   MaxStoresPerMemcpyOptSize = 2;
1194   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1195   MaxStoresPerMemmoveOptSize = 2;
1196 
1197   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1198   // are at least 4 bytes aligned.
1199   setMinStackArgumentAlignment(4);
1200 
1201   // Prefer likely predicted branches to selects on out-of-order cores.
1202   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1203 
1204   setPrefLoopAlignment(Subtarget->getPrefLoopAlignment());
1205 
1206   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1207 }
1208 
1209 bool ARMTargetLowering::useSoftFloat() const {
1210   return Subtarget->useSoftFloat();
1211 }
1212 
1213 // FIXME: It might make sense to define the representative register class as the
1214 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1215 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1216 // SPR's representative would be DPR_VFP2. This should work well if register
1217 // pressure tracking were modified such that a register use would increment the
1218 // pressure of the register class's representative and all of it's super
1219 // classes' representatives transitively. We have not implemented this because
1220 // of the difficulty prior to coalescing of modeling operand register classes
1221 // due to the common occurrence of cross class copies and subregister insertions
1222 // and extractions.
1223 std::pair<const TargetRegisterClass *, uint8_t>
1224 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1225                                            MVT VT) const {
1226   const TargetRegisterClass *RRC = nullptr;
1227   uint8_t Cost = 1;
1228   switch (VT.SimpleTy) {
1229   default:
1230     return TargetLowering::findRepresentativeClass(TRI, VT);
1231   // Use DPR as representative register class for all floating point
1232   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1233   // the cost is 1 for both f32 and f64.
1234   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1235   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1236     RRC = &ARM::DPRRegClass;
1237     // When NEON is used for SP, only half of the register file is available
1238     // because operations that define both SP and DP results will be constrained
1239     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1240     // coalescing by double-counting the SP regs. See the FIXME above.
1241     if (Subtarget->useNEONForSinglePrecisionFP())
1242       Cost = 2;
1243     break;
1244   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1245   case MVT::v4f32: case MVT::v2f64:
1246     RRC = &ARM::DPRRegClass;
1247     Cost = 2;
1248     break;
1249   case MVT::v4i64:
1250     RRC = &ARM::DPRRegClass;
1251     Cost = 4;
1252     break;
1253   case MVT::v8i64:
1254     RRC = &ARM::DPRRegClass;
1255     Cost = 8;
1256     break;
1257   }
1258   return std::make_pair(RRC, Cost);
1259 }
1260 
1261 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1262   switch ((ARMISD::NodeType)Opcode) {
1263   case ARMISD::FIRST_NUMBER:  break;
1264   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1265   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1266   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1267   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1268   case ARMISD::CALL:          return "ARMISD::CALL";
1269   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1270   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1271   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1272   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1273   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1274   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1275   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1276   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1277   case ARMISD::CMP:           return "ARMISD::CMP";
1278   case ARMISD::CMN:           return "ARMISD::CMN";
1279   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1280   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1281   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1282   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1283   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1284 
1285   case ARMISD::CMOV:          return "ARMISD::CMOV";
1286   case ARMISD::SUBS:          return "ARMISD::SUBS";
1287 
1288   case ARMISD::SSAT:          return "ARMISD::SSAT";
1289   case ARMISD::USAT:          return "ARMISD::USAT";
1290 
1291   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1292   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1293   case ARMISD::RRX:           return "ARMISD::RRX";
1294 
1295   case ARMISD::ADDC:          return "ARMISD::ADDC";
1296   case ARMISD::ADDE:          return "ARMISD::ADDE";
1297   case ARMISD::SUBC:          return "ARMISD::SUBC";
1298   case ARMISD::SUBE:          return "ARMISD::SUBE";
1299 
1300   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1301   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1302   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
1303   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
1304   case ARMISD::VMOVSR:        return "ARMISD::VMOVSR";
1305 
1306   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1307   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1308   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1309 
1310   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1311 
1312   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1313 
1314   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1315 
1316   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1317 
1318   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1319 
1320   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1321   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1322 
1323   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1324   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1325   case ARMISD::VCGE:          return "ARMISD::VCGE";
1326   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1327   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1328   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1329   case ARMISD::VCGT:          return "ARMISD::VCGT";
1330   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1331   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1332   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1333   case ARMISD::VTST:          return "ARMISD::VTST";
1334 
1335   case ARMISD::VSHL:          return "ARMISD::VSHL";
1336   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1337   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1338   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1339   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1340   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1341   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1342   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1343   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1344   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1345   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1346   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1347   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1348   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1349   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1350   case ARMISD::VSLI:          return "ARMISD::VSLI";
1351   case ARMISD::VSRI:          return "ARMISD::VSRI";
1352   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1353   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1354   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1355   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1356   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1357   case ARMISD::VDUP:          return "ARMISD::VDUP";
1358   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1359   case ARMISD::VEXT:          return "ARMISD::VEXT";
1360   case ARMISD::VREV64:        return "ARMISD::VREV64";
1361   case ARMISD::VREV32:        return "ARMISD::VREV32";
1362   case ARMISD::VREV16:        return "ARMISD::VREV16";
1363   case ARMISD::VZIP:          return "ARMISD::VZIP";
1364   case ARMISD::VUZP:          return "ARMISD::VUZP";
1365   case ARMISD::VTRN:          return "ARMISD::VTRN";
1366   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1367   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1368   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1369   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1370   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1371   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1372   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1373   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1374   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1375   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1376   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1377   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1378   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1379   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1380   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1381   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1382   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1383   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1384   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1385   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1386   case ARMISD::BFI:           return "ARMISD::BFI";
1387   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1388   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1389   case ARMISD::VBSL:          return "ARMISD::VBSL";
1390   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1391   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1392   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1393   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1394   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1395   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1396   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1397   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1398   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1399   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1400   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1401   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1402   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1403   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1404   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1405   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1406   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1407   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1408   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1409   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1410   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1411   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1412   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1413   }
1414   return nullptr;
1415 }
1416 
1417 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1418                                           EVT VT) const {
1419   if (!VT.isVector())
1420     return getPointerTy(DL);
1421   return VT.changeVectorElementTypeToInteger();
1422 }
1423 
1424 /// getRegClassFor - Return the register class that should be used for the
1425 /// specified value type.
1426 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1427   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1428   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1429   // load / store 4 to 8 consecutive D registers.
1430   if (Subtarget->hasNEON()) {
1431     if (VT == MVT::v4i64)
1432       return &ARM::QQPRRegClass;
1433     if (VT == MVT::v8i64)
1434       return &ARM::QQQQPRRegClass;
1435   }
1436   return TargetLowering::getRegClassFor(VT);
1437 }
1438 
1439 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1440 // source/dest is aligned and the copy size is large enough. We therefore want
1441 // to align such objects passed to memory intrinsics.
1442 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1443                                                unsigned &PrefAlign) const {
1444   if (!isa<MemIntrinsic>(CI))
1445     return false;
1446   MinSize = 8;
1447   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1448   // cycle faster than 4-byte aligned LDM.
1449   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1450   return true;
1451 }
1452 
1453 // Create a fast isel object.
1454 FastISel *
1455 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1456                                   const TargetLibraryInfo *libInfo) const {
1457   return ARM::createFastISel(funcInfo, libInfo);
1458 }
1459 
1460 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1461   unsigned NumVals = N->getNumValues();
1462   if (!NumVals)
1463     return Sched::RegPressure;
1464 
1465   for (unsigned i = 0; i != NumVals; ++i) {
1466     EVT VT = N->getValueType(i);
1467     if (VT == MVT::Glue || VT == MVT::Other)
1468       continue;
1469     if (VT.isFloatingPoint() || VT.isVector())
1470       return Sched::ILP;
1471   }
1472 
1473   if (!N->isMachineOpcode())
1474     return Sched::RegPressure;
1475 
1476   // Load are scheduled for latency even if there instruction itinerary
1477   // is not available.
1478   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1479   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1480 
1481   if (MCID.getNumDefs() == 0)
1482     return Sched::RegPressure;
1483   if (!Itins->isEmpty() &&
1484       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1485     return Sched::ILP;
1486 
1487   return Sched::RegPressure;
1488 }
1489 
1490 //===----------------------------------------------------------------------===//
1491 // Lowering Code
1492 //===----------------------------------------------------------------------===//
1493 
1494 static bool isSRL16(const SDValue &Op) {
1495   if (Op.getOpcode() != ISD::SRL)
1496     return false;
1497   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1498     return Const->getZExtValue() == 16;
1499   return false;
1500 }
1501 
1502 static bool isSRA16(const SDValue &Op) {
1503   if (Op.getOpcode() != ISD::SRA)
1504     return false;
1505   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1506     return Const->getZExtValue() == 16;
1507   return false;
1508 }
1509 
1510 static bool isSHL16(const SDValue &Op) {
1511   if (Op.getOpcode() != ISD::SHL)
1512     return false;
1513   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1514     return Const->getZExtValue() == 16;
1515   return false;
1516 }
1517 
1518 // Check for a signed 16-bit value. We special case SRA because it makes it
1519 // more simple when also looking for SRAs that aren't sign extending a
1520 // smaller value. Without the check, we'd need to take extra care with
1521 // checking order for some operations.
1522 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1523   if (isSRA16(Op))
1524     return isSHL16(Op.getOperand(0));
1525   return DAG.ComputeNumSignBits(Op) == 17;
1526 }
1527 
1528 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1529 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1530   switch (CC) {
1531   default: llvm_unreachable("Unknown condition code!");
1532   case ISD::SETNE:  return ARMCC::NE;
1533   case ISD::SETEQ:  return ARMCC::EQ;
1534   case ISD::SETGT:  return ARMCC::GT;
1535   case ISD::SETGE:  return ARMCC::GE;
1536   case ISD::SETLT:  return ARMCC::LT;
1537   case ISD::SETLE:  return ARMCC::LE;
1538   case ISD::SETUGT: return ARMCC::HI;
1539   case ISD::SETUGE: return ARMCC::HS;
1540   case ISD::SETULT: return ARMCC::LO;
1541   case ISD::SETULE: return ARMCC::LS;
1542   }
1543 }
1544 
1545 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1546 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1547                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1548   CondCode2 = ARMCC::AL;
1549   InvalidOnQNaN = true;
1550   switch (CC) {
1551   default: llvm_unreachable("Unknown FP condition!");
1552   case ISD::SETEQ:
1553   case ISD::SETOEQ:
1554     CondCode = ARMCC::EQ;
1555     InvalidOnQNaN = false;
1556     break;
1557   case ISD::SETGT:
1558   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1559   case ISD::SETGE:
1560   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1561   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1562   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1563   case ISD::SETONE:
1564     CondCode = ARMCC::MI;
1565     CondCode2 = ARMCC::GT;
1566     InvalidOnQNaN = false;
1567     break;
1568   case ISD::SETO:   CondCode = ARMCC::VC; break;
1569   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1570   case ISD::SETUEQ:
1571     CondCode = ARMCC::EQ;
1572     CondCode2 = ARMCC::VS;
1573     InvalidOnQNaN = false;
1574     break;
1575   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1576   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1577   case ISD::SETLT:
1578   case ISD::SETULT: CondCode = ARMCC::LT; break;
1579   case ISD::SETLE:
1580   case ISD::SETULE: CondCode = ARMCC::LE; break;
1581   case ISD::SETNE:
1582   case ISD::SETUNE:
1583     CondCode = ARMCC::NE;
1584     InvalidOnQNaN = false;
1585     break;
1586   }
1587 }
1588 
1589 //===----------------------------------------------------------------------===//
1590 //                      Calling Convention Implementation
1591 //===----------------------------------------------------------------------===//
1592 
1593 #include "ARMGenCallingConv.inc"
1594 
1595 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1596 /// account presence of floating point hardware and calling convention
1597 /// limitations, such as support for variadic functions.
1598 CallingConv::ID
1599 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1600                                            bool isVarArg) const {
1601   switch (CC) {
1602   default:
1603     report_fatal_error("Unsupported calling convention");
1604   case CallingConv::ARM_AAPCS:
1605   case CallingConv::ARM_APCS:
1606   case CallingConv::GHC:
1607     return CC;
1608   case CallingConv::PreserveMost:
1609     return CallingConv::PreserveMost;
1610   case CallingConv::ARM_AAPCS_VFP:
1611   case CallingConv::Swift:
1612     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1613   case CallingConv::C:
1614     if (!Subtarget->isAAPCS_ABI())
1615       return CallingConv::ARM_APCS;
1616     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1617              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1618              !isVarArg)
1619       return CallingConv::ARM_AAPCS_VFP;
1620     else
1621       return CallingConv::ARM_AAPCS;
1622   case CallingConv::Fast:
1623   case CallingConv::CXX_FAST_TLS:
1624     if (!Subtarget->isAAPCS_ABI()) {
1625       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1626         return CallingConv::Fast;
1627       return CallingConv::ARM_APCS;
1628     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1629       return CallingConv::ARM_AAPCS_VFP;
1630     else
1631       return CallingConv::ARM_AAPCS;
1632   }
1633 }
1634 
1635 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1636                                                  bool isVarArg) const {
1637   return CCAssignFnForNode(CC, false, isVarArg);
1638 }
1639 
1640 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1641                                                    bool isVarArg) const {
1642   return CCAssignFnForNode(CC, true, isVarArg);
1643 }
1644 
1645 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1646 /// CallingConvention.
1647 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1648                                                  bool Return,
1649                                                  bool isVarArg) const {
1650   switch (getEffectiveCallingConv(CC, isVarArg)) {
1651   default:
1652     report_fatal_error("Unsupported calling convention");
1653   case CallingConv::ARM_APCS:
1654     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1655   case CallingConv::ARM_AAPCS:
1656     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1657   case CallingConv::ARM_AAPCS_VFP:
1658     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1659   case CallingConv::Fast:
1660     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1661   case CallingConv::GHC:
1662     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1663   case CallingConv::PreserveMost:
1664     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1665   }
1666 }
1667 
1668 /// LowerCallResult - Lower the result values of a call into the
1669 /// appropriate copies out of appropriate physical registers.
1670 SDValue ARMTargetLowering::LowerCallResult(
1671     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1672     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1673     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1674     SDValue ThisVal) const {
1675   // Assign locations to each value returned by this call.
1676   SmallVector<CCValAssign, 16> RVLocs;
1677   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1678                  *DAG.getContext());
1679   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1680 
1681   // Copy all of the result registers out of their specified physreg.
1682   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1683     CCValAssign VA = RVLocs[i];
1684 
1685     // Pass 'this' value directly from the argument to return value, to avoid
1686     // reg unit interference
1687     if (i == 0 && isThisReturn) {
1688       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1689              "unexpected return calling convention register assignment");
1690       InVals.push_back(ThisVal);
1691       continue;
1692     }
1693 
1694     SDValue Val;
1695     if (VA.needsCustom()) {
1696       // Handle f64 or half of a v2f64.
1697       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1698                                       InFlag);
1699       Chain = Lo.getValue(1);
1700       InFlag = Lo.getValue(2);
1701       VA = RVLocs[++i]; // skip ahead to next loc
1702       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1703                                       InFlag);
1704       Chain = Hi.getValue(1);
1705       InFlag = Hi.getValue(2);
1706       if (!Subtarget->isLittle())
1707         std::swap (Lo, Hi);
1708       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1709 
1710       if (VA.getLocVT() == MVT::v2f64) {
1711         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1712         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1713                           DAG.getConstant(0, dl, MVT::i32));
1714 
1715         VA = RVLocs[++i]; // skip ahead to next loc
1716         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1717         Chain = Lo.getValue(1);
1718         InFlag = Lo.getValue(2);
1719         VA = RVLocs[++i]; // skip ahead to next loc
1720         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1721         Chain = Hi.getValue(1);
1722         InFlag = Hi.getValue(2);
1723         if (!Subtarget->isLittle())
1724           std::swap (Lo, Hi);
1725         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1726         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1727                           DAG.getConstant(1, dl, MVT::i32));
1728       }
1729     } else {
1730       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1731                                InFlag);
1732       Chain = Val.getValue(1);
1733       InFlag = Val.getValue(2);
1734     }
1735 
1736     switch (VA.getLocInfo()) {
1737     default: llvm_unreachable("Unknown loc info!");
1738     case CCValAssign::Full: break;
1739     case CCValAssign::BCvt:
1740       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1741       break;
1742     }
1743 
1744     InVals.push_back(Val);
1745   }
1746 
1747   return Chain;
1748 }
1749 
1750 /// LowerMemOpCallTo - Store the argument to the stack.
1751 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1752                                             SDValue Arg, const SDLoc &dl,
1753                                             SelectionDAG &DAG,
1754                                             const CCValAssign &VA,
1755                                             ISD::ArgFlagsTy Flags) const {
1756   unsigned LocMemOffset = VA.getLocMemOffset();
1757   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1758   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1759                        StackPtr, PtrOff);
1760   return DAG.getStore(
1761       Chain, dl, Arg, PtrOff,
1762       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1763 }
1764 
1765 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1766                                          SDValue Chain, SDValue &Arg,
1767                                          RegsToPassVector &RegsToPass,
1768                                          CCValAssign &VA, CCValAssign &NextVA,
1769                                          SDValue &StackPtr,
1770                                          SmallVectorImpl<SDValue> &MemOpChains,
1771                                          ISD::ArgFlagsTy Flags) const {
1772   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1773                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1774   unsigned id = Subtarget->isLittle() ? 0 : 1;
1775   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1776 
1777   if (NextVA.isRegLoc())
1778     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1779   else {
1780     assert(NextVA.isMemLoc());
1781     if (!StackPtr.getNode())
1782       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1783                                     getPointerTy(DAG.getDataLayout()));
1784 
1785     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1786                                            dl, DAG, NextVA,
1787                                            Flags));
1788   }
1789 }
1790 
1791 /// LowerCall - Lowering a call into a callseq_start <-
1792 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1793 /// nodes.
1794 SDValue
1795 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1796                              SmallVectorImpl<SDValue> &InVals) const {
1797   SelectionDAG &DAG                     = CLI.DAG;
1798   SDLoc &dl                             = CLI.DL;
1799   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1800   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1801   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1802   SDValue Chain                         = CLI.Chain;
1803   SDValue Callee                        = CLI.Callee;
1804   bool &isTailCall                      = CLI.IsTailCall;
1805   CallingConv::ID CallConv              = CLI.CallConv;
1806   bool doesNotRet                       = CLI.DoesNotReturn;
1807   bool isVarArg                         = CLI.IsVarArg;
1808 
1809   MachineFunction &MF = DAG.getMachineFunction();
1810   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1811   bool isThisReturn   = false;
1812   bool isSibCall      = false;
1813   auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
1814 
1815   // Disable tail calls if they're not supported.
1816   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1817     isTailCall = false;
1818 
1819   if (isTailCall) {
1820     // Check if it's really possible to do a tail call.
1821     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1822                     isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(),
1823                                                    Outs, OutVals, Ins, DAG);
1824     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1825       report_fatal_error("failed to perform tail call elimination on a call "
1826                          "site marked musttail");
1827     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1828     // detected sibcalls.
1829     if (isTailCall) {
1830       ++NumTailCalls;
1831       isSibCall = true;
1832     }
1833   }
1834 
1835   // Analyze operands of the call, assigning locations to each operand.
1836   SmallVector<CCValAssign, 16> ArgLocs;
1837   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1838                  *DAG.getContext());
1839   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1840 
1841   // Get a count of how many bytes are to be pushed on the stack.
1842   unsigned NumBytes = CCInfo.getNextStackOffset();
1843 
1844   // For tail calls, memory operands are available in our caller's stack.
1845   if (isSibCall)
1846     NumBytes = 0;
1847 
1848   // Adjust the stack pointer for the new arguments...
1849   // These operations are automatically eliminated by the prolog/epilog pass
1850   if (!isSibCall)
1851     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1852 
1853   SDValue StackPtr =
1854       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1855 
1856   RegsToPassVector RegsToPass;
1857   SmallVector<SDValue, 8> MemOpChains;
1858 
1859   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1860   // of tail call optimization, arguments are handled later.
1861   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1862        i != e;
1863        ++i, ++realArgIdx) {
1864     CCValAssign &VA = ArgLocs[i];
1865     SDValue Arg = OutVals[realArgIdx];
1866     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1867     bool isByVal = Flags.isByVal();
1868 
1869     // Promote the value if needed.
1870     switch (VA.getLocInfo()) {
1871     default: llvm_unreachable("Unknown loc info!");
1872     case CCValAssign::Full: break;
1873     case CCValAssign::SExt:
1874       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1875       break;
1876     case CCValAssign::ZExt:
1877       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1878       break;
1879     case CCValAssign::AExt:
1880       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1881       break;
1882     case CCValAssign::BCvt:
1883       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1884       break;
1885     }
1886 
1887     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1888     if (VA.needsCustom()) {
1889       if (VA.getLocVT() == MVT::v2f64) {
1890         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1891                                   DAG.getConstant(0, dl, MVT::i32));
1892         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1893                                   DAG.getConstant(1, dl, MVT::i32));
1894 
1895         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1896                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1897 
1898         VA = ArgLocs[++i]; // skip ahead to next loc
1899         if (VA.isRegLoc()) {
1900           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1901                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1902         } else {
1903           assert(VA.isMemLoc());
1904 
1905           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1906                                                  dl, DAG, VA, Flags));
1907         }
1908       } else {
1909         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1910                          StackPtr, MemOpChains, Flags);
1911       }
1912     } else if (VA.isRegLoc()) {
1913       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1914           Outs[0].VT == MVT::i32) {
1915         assert(VA.getLocVT() == MVT::i32 &&
1916                "unexpected calling convention register assignment");
1917         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1918                "unexpected use of 'returned'");
1919         isThisReturn = true;
1920       }
1921       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1922     } else if (isByVal) {
1923       assert(VA.isMemLoc());
1924       unsigned offset = 0;
1925 
1926       // True if this byval aggregate will be split between registers
1927       // and memory.
1928       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1929       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1930 
1931       if (CurByValIdx < ByValArgsCount) {
1932 
1933         unsigned RegBegin, RegEnd;
1934         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1935 
1936         EVT PtrVT =
1937             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1938         unsigned int i, j;
1939         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1940           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1941           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1942           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1943                                      MachinePointerInfo(),
1944                                      DAG.InferPtrAlignment(AddArg));
1945           MemOpChains.push_back(Load.getValue(1));
1946           RegsToPass.push_back(std::make_pair(j, Load));
1947         }
1948 
1949         // If parameter size outsides register area, "offset" value
1950         // helps us to calculate stack slot for remained part properly.
1951         offset = RegEnd - RegBegin;
1952 
1953         CCInfo.nextInRegsParam();
1954       }
1955 
1956       if (Flags.getByValSize() > 4*offset) {
1957         auto PtrVT = getPointerTy(DAG.getDataLayout());
1958         unsigned LocMemOffset = VA.getLocMemOffset();
1959         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1960         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1961         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1962         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1963         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1964                                            MVT::i32);
1965         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1966                                             MVT::i32);
1967 
1968         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1969         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1970         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1971                                           Ops));
1972       }
1973     } else if (!isSibCall) {
1974       assert(VA.isMemLoc());
1975 
1976       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1977                                              dl, DAG, VA, Flags));
1978     }
1979   }
1980 
1981   if (!MemOpChains.empty())
1982     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1983 
1984   // Build a sequence of copy-to-reg nodes chained together with token chain
1985   // and flag operands which copy the outgoing args into the appropriate regs.
1986   SDValue InFlag;
1987   // Tail call byval lowering might overwrite argument registers so in case of
1988   // tail call optimization the copies to registers are lowered later.
1989   if (!isTailCall)
1990     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1991       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1992                                RegsToPass[i].second, InFlag);
1993       InFlag = Chain.getValue(1);
1994     }
1995 
1996   // For tail calls lower the arguments to the 'real' stack slot.
1997   if (isTailCall) {
1998     // Force all the incoming stack arguments to be loaded from the stack
1999     // before any new outgoing arguments are stored to the stack, because the
2000     // outgoing stack slots may alias the incoming argument stack slots, and
2001     // the alias isn't otherwise explicit. This is slightly more conservative
2002     // than necessary, because it means that each store effectively depends
2003     // on every argument instead of just those arguments it would clobber.
2004 
2005     // Do not flag preceding copytoreg stuff together with the following stuff.
2006     InFlag = SDValue();
2007     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2008       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2009                                RegsToPass[i].second, InFlag);
2010       InFlag = Chain.getValue(1);
2011     }
2012     InFlag = SDValue();
2013   }
2014 
2015   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2016   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2017   // node so that legalize doesn't hack it.
2018   bool isDirect = false;
2019 
2020   const TargetMachine &TM = getTargetMachine();
2021   const Module *Mod = MF.getFunction().getParent();
2022   const GlobalValue *GV = nullptr;
2023   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2024     GV = G->getGlobal();
2025   bool isStub =
2026       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2027 
2028   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2029   bool isLocalARMFunc = false;
2030   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2031   auto PtrVt = getPointerTy(DAG.getDataLayout());
2032 
2033   if (Subtarget->genLongCalls()) {
2034     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2035            "long-calls codegen is not position independent!");
2036     // Handle a global address or an external symbol. If it's not one of
2037     // those, the target's already in a register, so we don't need to do
2038     // anything extra.
2039     if (isa<GlobalAddressSDNode>(Callee)) {
2040       // Create a constant pool entry for the callee address
2041       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2042       ARMConstantPoolValue *CPV =
2043         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2044 
2045       // Get the address of the callee into a register
2046       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2047       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2048       Callee = DAG.getLoad(
2049           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2050           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2051     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2052       const char *Sym = S->getSymbol();
2053 
2054       // Create a constant pool entry for the callee address
2055       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2056       ARMConstantPoolValue *CPV =
2057         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2058                                       ARMPCLabelIndex, 0);
2059       // Get the address of the callee into a register
2060       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2061       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2062       Callee = DAG.getLoad(
2063           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2064           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2065     }
2066   } else if (isa<GlobalAddressSDNode>(Callee)) {
2067     // If we're optimizing for minimum size and the function is called three or
2068     // more times in this block, we can improve codesize by calling indirectly
2069     // as BLXr has a 16-bit encoding.
2070     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2071     auto *BB = CLI.CS.getParent();
2072     bool PreferIndirect =
2073         Subtarget->isThumb() && MF.getFunction().optForMinSize() &&
2074         count_if(GV->users(), [&BB](const User *U) {
2075           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2076         }) > 2;
2077 
2078     if (!PreferIndirect) {
2079       isDirect = true;
2080       bool isDef = GV->isStrongDefinitionForLinker();
2081 
2082       // ARM call to a local ARM function is predicable.
2083       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2084       // tBX takes a register source operand.
2085       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2086         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2087         Callee = DAG.getNode(
2088             ARMISD::WrapperPIC, dl, PtrVt,
2089             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2090         Callee = DAG.getLoad(
2091             PtrVt, dl, DAG.getEntryNode(), Callee,
2092             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2093             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2094                                      MachineMemOperand::MOInvariant);
2095       } else if (Subtarget->isTargetCOFF()) {
2096         assert(Subtarget->isTargetWindows() &&
2097                "Windows is the only supported COFF target");
2098         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2099                                    ? ARMII::MO_DLLIMPORT
2100                                    : ARMII::MO_NO_FLAG;
2101         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2102                                             TargetFlags);
2103         if (GV->hasDLLImportStorageClass())
2104           Callee =
2105               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2106                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2107                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2108       } else {
2109         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2110       }
2111     }
2112   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2113     isDirect = true;
2114     // tBX takes a register source operand.
2115     const char *Sym = S->getSymbol();
2116     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2117       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2118       ARMConstantPoolValue *CPV =
2119         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2120                                       ARMPCLabelIndex, 4);
2121       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2122       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2123       Callee = DAG.getLoad(
2124           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2125           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2126       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2127       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2128     } else {
2129       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2130     }
2131   }
2132 
2133   // FIXME: handle tail calls differently.
2134   unsigned CallOpc;
2135   if (Subtarget->isThumb()) {
2136     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2137       CallOpc = ARMISD::CALL_NOLINK;
2138     else
2139       CallOpc = ARMISD::CALL;
2140   } else {
2141     if (!isDirect && !Subtarget->hasV5TOps())
2142       CallOpc = ARMISD::CALL_NOLINK;
2143     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2144              // Emit regular call when code size is the priority
2145              !MF.getFunction().optForMinSize())
2146       // "mov lr, pc; b _foo" to avoid confusing the RSP
2147       CallOpc = ARMISD::CALL_NOLINK;
2148     else
2149       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2150   }
2151 
2152   std::vector<SDValue> Ops;
2153   Ops.push_back(Chain);
2154   Ops.push_back(Callee);
2155 
2156   // Add argument registers to the end of the list so that they are known live
2157   // into the call.
2158   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2159     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2160                                   RegsToPass[i].second.getValueType()));
2161 
2162   // Add a register mask operand representing the call-preserved registers.
2163   if (!isTailCall) {
2164     const uint32_t *Mask;
2165     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2166     if (isThisReturn) {
2167       // For 'this' returns, use the R0-preserving mask if applicable
2168       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2169       if (!Mask) {
2170         // Set isThisReturn to false if the calling convention is not one that
2171         // allows 'returned' to be modeled in this way, so LowerCallResult does
2172         // not try to pass 'this' straight through
2173         isThisReturn = false;
2174         Mask = ARI->getCallPreservedMask(MF, CallConv);
2175       }
2176     } else
2177       Mask = ARI->getCallPreservedMask(MF, CallConv);
2178 
2179     assert(Mask && "Missing call preserved mask for calling convention");
2180     Ops.push_back(DAG.getRegisterMask(Mask));
2181   }
2182 
2183   if (InFlag.getNode())
2184     Ops.push_back(InFlag);
2185 
2186   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2187   if (isTailCall) {
2188     MF.getFrameInfo().setHasTailCall();
2189     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2190   }
2191 
2192   // Returns a chain and a flag for retval copy to use.
2193   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2194   InFlag = Chain.getValue(1);
2195 
2196   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2197                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2198   if (!Ins.empty())
2199     InFlag = Chain.getValue(1);
2200 
2201   // Handle result values, copying them out of physregs into vregs that we
2202   // return.
2203   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2204                          InVals, isThisReturn,
2205                          isThisReturn ? OutVals[0] : SDValue());
2206 }
2207 
2208 /// HandleByVal - Every parameter *after* a byval parameter is passed
2209 /// on the stack.  Remember the next parameter register to allocate,
2210 /// and then confiscate the rest of the parameter registers to insure
2211 /// this.
2212 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2213                                     unsigned Align) const {
2214   // Byval (as with any stack) slots are always at least 4 byte aligned.
2215   Align = std::max(Align, 4U);
2216 
2217   unsigned Reg = State->AllocateReg(GPRArgRegs);
2218   if (!Reg)
2219     return;
2220 
2221   unsigned AlignInRegs = Align / 4;
2222   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2223   for (unsigned i = 0; i < Waste; ++i)
2224     Reg = State->AllocateReg(GPRArgRegs);
2225 
2226   if (!Reg)
2227     return;
2228 
2229   unsigned Excess = 4 * (ARM::R4 - Reg);
2230 
2231   // Special case when NSAA != SP and parameter size greater than size of
2232   // all remained GPR regs. In that case we can't split parameter, we must
2233   // send it to stack. We also must set NCRN to R4, so waste all
2234   // remained registers.
2235   const unsigned NSAAOffset = State->getNextStackOffset();
2236   if (NSAAOffset != 0 && Size > Excess) {
2237     while (State->AllocateReg(GPRArgRegs))
2238       ;
2239     return;
2240   }
2241 
2242   // First register for byval parameter is the first register that wasn't
2243   // allocated before this method call, so it would be "reg".
2244   // If parameter is small enough to be saved in range [reg, r4), then
2245   // the end (first after last) register would be reg + param-size-in-regs,
2246   // else parameter would be splitted between registers and stack,
2247   // end register would be r4 in this case.
2248   unsigned ByValRegBegin = Reg;
2249   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2250   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2251   // Note, first register is allocated in the beginning of function already,
2252   // allocate remained amount of registers we need.
2253   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2254     State->AllocateReg(GPRArgRegs);
2255   // A byval parameter that is split between registers and memory needs its
2256   // size truncated here.
2257   // In the case where the entire structure fits in registers, we set the
2258   // size in memory to zero.
2259   Size = std::max<int>(Size - Excess, 0);
2260 }
2261 
2262 /// MatchingStackOffset - Return true if the given stack call argument is
2263 /// already available in the same position (relatively) of the caller's
2264 /// incoming argument stack.
2265 static
2266 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2267                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2268                          const TargetInstrInfo *TII) {
2269   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2270   int FI = std::numeric_limits<int>::max();
2271   if (Arg.getOpcode() == ISD::CopyFromReg) {
2272     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2273     if (!TargetRegisterInfo::isVirtualRegister(VR))
2274       return false;
2275     MachineInstr *Def = MRI->getVRegDef(VR);
2276     if (!Def)
2277       return false;
2278     if (!Flags.isByVal()) {
2279       if (!TII->isLoadFromStackSlot(*Def, FI))
2280         return false;
2281     } else {
2282       return false;
2283     }
2284   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2285     if (Flags.isByVal())
2286       // ByVal argument is passed in as a pointer but it's now being
2287       // dereferenced. e.g.
2288       // define @foo(%struct.X* %A) {
2289       //   tail call @bar(%struct.X* byval %A)
2290       // }
2291       return false;
2292     SDValue Ptr = Ld->getBasePtr();
2293     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2294     if (!FINode)
2295       return false;
2296     FI = FINode->getIndex();
2297   } else
2298     return false;
2299 
2300   assert(FI != std::numeric_limits<int>::max());
2301   if (!MFI.isFixedObjectIndex(FI))
2302     return false;
2303   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2304 }
2305 
2306 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2307 /// for tail call optimization. Targets which want to do tail call
2308 /// optimization should implement this function.
2309 bool
2310 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2311                                                      CallingConv::ID CalleeCC,
2312                                                      bool isVarArg,
2313                                                      bool isCalleeStructRet,
2314                                                      bool isCallerStructRet,
2315                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2316                                     const SmallVectorImpl<SDValue> &OutVals,
2317                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2318                                                      SelectionDAG& DAG) const {
2319   MachineFunction &MF = DAG.getMachineFunction();
2320   const Function &CallerF = MF.getFunction();
2321   CallingConv::ID CallerCC = CallerF.getCallingConv();
2322 
2323   assert(Subtarget->supportsTailCall());
2324 
2325   // Tail calls to function pointers cannot be optimized for Thumb1 if the args
2326   // to the call take up r0-r3. The reason is that there are no legal registers
2327   // left to hold the pointer to the function to be called.
2328   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2329       !isa<GlobalAddressSDNode>(Callee.getNode()))
2330       return false;
2331 
2332   // Look for obvious safe cases to perform tail call optimization that do not
2333   // require ABI changes. This is what gcc calls sibcall.
2334 
2335   // Exception-handling functions need a special set of instructions to indicate
2336   // a return to the hardware. Tail-calling another function would probably
2337   // break this.
2338   if (CallerF.hasFnAttribute("interrupt"))
2339     return false;
2340 
2341   // Also avoid sibcall optimization if either caller or callee uses struct
2342   // return semantics.
2343   if (isCalleeStructRet || isCallerStructRet)
2344     return false;
2345 
2346   // Externally-defined functions with weak linkage should not be
2347   // tail-called on ARM when the OS does not support dynamic
2348   // pre-emption of symbols, as the AAELF spec requires normal calls
2349   // to undefined weak functions to be replaced with a NOP or jump to the
2350   // next instruction. The behaviour of branch instructions in this
2351   // situation (as used for tail calls) is implementation-defined, so we
2352   // cannot rely on the linker replacing the tail call with a return.
2353   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2354     const GlobalValue *GV = G->getGlobal();
2355     const Triple &TT = getTargetMachine().getTargetTriple();
2356     if (GV->hasExternalWeakLinkage() &&
2357         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2358       return false;
2359   }
2360 
2361   // Check that the call results are passed in the same way.
2362   LLVMContext &C = *DAG.getContext();
2363   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2364                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2365                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2366     return false;
2367   // The callee has to preserve all registers the caller needs to preserve.
2368   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2369   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2370   if (CalleeCC != CallerCC) {
2371     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2372     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2373       return false;
2374   }
2375 
2376   // If Caller's vararg or byval argument has been split between registers and
2377   // stack, do not perform tail call, since part of the argument is in caller's
2378   // local frame.
2379   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2380   if (AFI_Caller->getArgRegsSaveSize())
2381     return false;
2382 
2383   // If the callee takes no arguments then go on to check the results of the
2384   // call.
2385   if (!Outs.empty()) {
2386     // Check if stack adjustment is needed. For now, do not do this if any
2387     // argument is passed on the stack.
2388     SmallVector<CCValAssign, 16> ArgLocs;
2389     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2390     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2391     if (CCInfo.getNextStackOffset()) {
2392       // Check if the arguments are already laid out in the right way as
2393       // the caller's fixed stack objects.
2394       MachineFrameInfo &MFI = MF.getFrameInfo();
2395       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2396       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2397       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2398            i != e;
2399            ++i, ++realArgIdx) {
2400         CCValAssign &VA = ArgLocs[i];
2401         EVT RegVT = VA.getLocVT();
2402         SDValue Arg = OutVals[realArgIdx];
2403         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2404         if (VA.getLocInfo() == CCValAssign::Indirect)
2405           return false;
2406         if (VA.needsCustom()) {
2407           // f64 and vector types are split into multiple registers or
2408           // register/stack-slot combinations.  The types will not match
2409           // the registers; give up on memory f64 refs until we figure
2410           // out what to do about this.
2411           if (!VA.isRegLoc())
2412             return false;
2413           if (!ArgLocs[++i].isRegLoc())
2414             return false;
2415           if (RegVT == MVT::v2f64) {
2416             if (!ArgLocs[++i].isRegLoc())
2417               return false;
2418             if (!ArgLocs[++i].isRegLoc())
2419               return false;
2420           }
2421         } else if (!VA.isRegLoc()) {
2422           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2423                                    MFI, MRI, TII))
2424             return false;
2425         }
2426       }
2427     }
2428 
2429     const MachineRegisterInfo &MRI = MF.getRegInfo();
2430     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2431       return false;
2432   }
2433 
2434   return true;
2435 }
2436 
2437 bool
2438 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2439                                   MachineFunction &MF, bool isVarArg,
2440                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2441                                   LLVMContext &Context) const {
2442   SmallVector<CCValAssign, 16> RVLocs;
2443   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2444   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2445 }
2446 
2447 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2448                                     const SDLoc &DL, SelectionDAG &DAG) {
2449   const MachineFunction &MF = DAG.getMachineFunction();
2450   const Function &F = MF.getFunction();
2451 
2452   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2453 
2454   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2455   // version of the "preferred return address". These offsets affect the return
2456   // instruction if this is a return from PL1 without hypervisor extensions.
2457   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2458   //    SWI:     0      "subs pc, lr, #0"
2459   //    ABORT:   +4     "subs pc, lr, #4"
2460   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2461   // UNDEF varies depending on where the exception came from ARM or Thumb
2462   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2463 
2464   int64_t LROffset;
2465   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2466       IntKind == "ABORT")
2467     LROffset = 4;
2468   else if (IntKind == "SWI" || IntKind == "UNDEF")
2469     LROffset = 0;
2470   else
2471     report_fatal_error("Unsupported interrupt attribute. If present, value "
2472                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2473 
2474   RetOps.insert(RetOps.begin() + 1,
2475                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2476 
2477   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2478 }
2479 
2480 SDValue
2481 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2482                                bool isVarArg,
2483                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2484                                const SmallVectorImpl<SDValue> &OutVals,
2485                                const SDLoc &dl, SelectionDAG &DAG) const {
2486   // CCValAssign - represent the assignment of the return value to a location.
2487   SmallVector<CCValAssign, 16> RVLocs;
2488 
2489   // CCState - Info about the registers and stack slots.
2490   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2491                  *DAG.getContext());
2492 
2493   // Analyze outgoing return values.
2494   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2495 
2496   SDValue Flag;
2497   SmallVector<SDValue, 4> RetOps;
2498   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2499   bool isLittleEndian = Subtarget->isLittle();
2500 
2501   MachineFunction &MF = DAG.getMachineFunction();
2502   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2503   AFI->setReturnRegsCount(RVLocs.size());
2504 
2505   // Copy the result values into the output registers.
2506   for (unsigned i = 0, realRVLocIdx = 0;
2507        i != RVLocs.size();
2508        ++i, ++realRVLocIdx) {
2509     CCValAssign &VA = RVLocs[i];
2510     assert(VA.isRegLoc() && "Can only return in registers!");
2511 
2512     SDValue Arg = OutVals[realRVLocIdx];
2513     bool ReturnF16 = false;
2514 
2515     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2516       // Half-precision return values can be returned like this:
2517       //
2518       // t11 f16 = fadd ...
2519       // t12: i16 = bitcast t11
2520       //   t13: i32 = zero_extend t12
2521       // t14: f32 = bitcast t13  <~~~~~~~ Arg
2522       //
2523       // to avoid code generation for bitcasts, we simply set Arg to the node
2524       // that produces the f16 value, t11 in this case.
2525       //
2526       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2527         SDValue ZE = Arg.getOperand(0);
2528         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2529           SDValue BC = ZE.getOperand(0);
2530           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2531             Arg = BC.getOperand(0);
2532             ReturnF16 = true;
2533           }
2534         }
2535       }
2536     }
2537 
2538     switch (VA.getLocInfo()) {
2539     default: llvm_unreachable("Unknown loc info!");
2540     case CCValAssign::Full: break;
2541     case CCValAssign::BCvt:
2542       if (!ReturnF16)
2543         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2544       break;
2545     }
2546 
2547     if (VA.needsCustom()) {
2548       if (VA.getLocVT() == MVT::v2f64) {
2549         // Extract the first half and return it in two registers.
2550         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2551                                    DAG.getConstant(0, dl, MVT::i32));
2552         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2553                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2554 
2555         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2556                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2557                                  Flag);
2558         Flag = Chain.getValue(1);
2559         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2560         VA = RVLocs[++i]; // skip ahead to next loc
2561         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2562                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2563                                  Flag);
2564         Flag = Chain.getValue(1);
2565         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2566         VA = RVLocs[++i]; // skip ahead to next loc
2567 
2568         // Extract the 2nd half and fall through to handle it as an f64 value.
2569         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2570                           DAG.getConstant(1, dl, MVT::i32));
2571       }
2572       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2573       // available.
2574       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2575                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2576       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2577                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2578                                Flag);
2579       Flag = Chain.getValue(1);
2580       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2581       VA = RVLocs[++i]; // skip ahead to next loc
2582       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2583                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2584                                Flag);
2585     } else
2586       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2587 
2588     // Guarantee that all emitted copies are
2589     // stuck together, avoiding something bad.
2590     Flag = Chain.getValue(1);
2591     RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2592                                      ReturnF16 ? MVT::f16 : VA.getLocVT()));
2593   }
2594   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2595   const MCPhysReg *I =
2596       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2597   if (I) {
2598     for (; *I; ++I) {
2599       if (ARM::GPRRegClass.contains(*I))
2600         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2601       else if (ARM::DPRRegClass.contains(*I))
2602         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2603       else
2604         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2605     }
2606   }
2607 
2608   // Update chain and glue.
2609   RetOps[0] = Chain;
2610   if (Flag.getNode())
2611     RetOps.push_back(Flag);
2612 
2613   // CPUs which aren't M-class use a special sequence to return from
2614   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2615   // though we use "subs pc, lr, #N").
2616   //
2617   // M-class CPUs actually use a normal return sequence with a special
2618   // (hardware-provided) value in LR, so the normal code path works.
2619   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2620       !Subtarget->isMClass()) {
2621     if (Subtarget->isThumb1Only())
2622       report_fatal_error("interrupt attribute is not supported in Thumb1");
2623     return LowerInterruptReturn(RetOps, dl, DAG);
2624   }
2625 
2626   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2627 }
2628 
2629 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2630   if (N->getNumValues() != 1)
2631     return false;
2632   if (!N->hasNUsesOfValue(1, 0))
2633     return false;
2634 
2635   SDValue TCChain = Chain;
2636   SDNode *Copy = *N->use_begin();
2637   if (Copy->getOpcode() == ISD::CopyToReg) {
2638     // If the copy has a glue operand, we conservatively assume it isn't safe to
2639     // perform a tail call.
2640     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2641       return false;
2642     TCChain = Copy->getOperand(0);
2643   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2644     SDNode *VMov = Copy;
2645     // f64 returned in a pair of GPRs.
2646     SmallPtrSet<SDNode*, 2> Copies;
2647     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2648          UI != UE; ++UI) {
2649       if (UI->getOpcode() != ISD::CopyToReg)
2650         return false;
2651       Copies.insert(*UI);
2652     }
2653     if (Copies.size() > 2)
2654       return false;
2655 
2656     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2657          UI != UE; ++UI) {
2658       SDValue UseChain = UI->getOperand(0);
2659       if (Copies.count(UseChain.getNode()))
2660         // Second CopyToReg
2661         Copy = *UI;
2662       else {
2663         // We are at the top of this chain.
2664         // If the copy has a glue operand, we conservatively assume it
2665         // isn't safe to perform a tail call.
2666         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2667           return false;
2668         // First CopyToReg
2669         TCChain = UseChain;
2670       }
2671     }
2672   } else if (Copy->getOpcode() == ISD::BITCAST) {
2673     // f32 returned in a single GPR.
2674     if (!Copy->hasOneUse())
2675       return false;
2676     Copy = *Copy->use_begin();
2677     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2678       return false;
2679     // If the copy has a glue operand, we conservatively assume it isn't safe to
2680     // perform a tail call.
2681     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2682       return false;
2683     TCChain = Copy->getOperand(0);
2684   } else {
2685     return false;
2686   }
2687 
2688   bool HasRet = false;
2689   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2690        UI != UE; ++UI) {
2691     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2692         UI->getOpcode() != ARMISD::INTRET_FLAG)
2693       return false;
2694     HasRet = true;
2695   }
2696 
2697   if (!HasRet)
2698     return false;
2699 
2700   Chain = TCChain;
2701   return true;
2702 }
2703 
2704 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2705   if (!Subtarget->supportsTailCall())
2706     return false;
2707 
2708   auto Attr =
2709       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2710   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2711     return false;
2712 
2713   return true;
2714 }
2715 
2716 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2717 // and pass the lower and high parts through.
2718 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2719   SDLoc DL(Op);
2720   SDValue WriteValue = Op->getOperand(2);
2721 
2722   // This function is only supposed to be called for i64 type argument.
2723   assert(WriteValue.getValueType() == MVT::i64
2724           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2725 
2726   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2727                            DAG.getConstant(0, DL, MVT::i32));
2728   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2729                            DAG.getConstant(1, DL, MVT::i32));
2730   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2731   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2732 }
2733 
2734 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2735 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2736 // one of the above mentioned nodes. It has to be wrapped because otherwise
2737 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2738 // be used to form addressing mode. These wrapped nodes will be selected
2739 // into MOVi.
2740 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2741                                              SelectionDAG &DAG) const {
2742   EVT PtrVT = Op.getValueType();
2743   // FIXME there is no actual debug info here
2744   SDLoc dl(Op);
2745   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2746   SDValue Res;
2747 
2748   // When generating execute-only code Constant Pools must be promoted to the
2749   // global data section. It's a bit ugly that we can't share them across basic
2750   // blocks, but this way we guarantee that execute-only behaves correct with
2751   // position-independent addressing modes.
2752   if (Subtarget->genExecuteOnly()) {
2753     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2754     auto T = const_cast<Type*>(CP->getType());
2755     auto C = const_cast<Constant*>(CP->getConstVal());
2756     auto M = const_cast<Module*>(DAG.getMachineFunction().
2757                                  getFunction().getParent());
2758     auto GV = new GlobalVariable(
2759                     *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2760                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2761                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2762                     Twine(AFI->createPICLabelUId())
2763                   );
2764     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2765                                             dl, PtrVT);
2766     return LowerGlobalAddress(GA, DAG);
2767   }
2768 
2769   if (CP->isMachineConstantPoolEntry())
2770     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2771                                     CP->getAlignment());
2772   else
2773     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2774                                     CP->getAlignment());
2775   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2776 }
2777 
2778 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2779   return MachineJumpTableInfo::EK_Inline;
2780 }
2781 
2782 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2783                                              SelectionDAG &DAG) const {
2784   MachineFunction &MF = DAG.getMachineFunction();
2785   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2786   unsigned ARMPCLabelIndex = 0;
2787   SDLoc DL(Op);
2788   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2789   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2790   SDValue CPAddr;
2791   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2792   if (!IsPositionIndependent) {
2793     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2794   } else {
2795     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2796     ARMPCLabelIndex = AFI->createPICLabelUId();
2797     ARMConstantPoolValue *CPV =
2798       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2799                                       ARMCP::CPBlockAddress, PCAdj);
2800     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2801   }
2802   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2803   SDValue Result = DAG.getLoad(
2804       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2805       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2806   if (!IsPositionIndependent)
2807     return Result;
2808   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2809   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2810 }
2811 
2812 /// Convert a TLS address reference into the correct sequence of loads
2813 /// and calls to compute the variable's address for Darwin, and return an
2814 /// SDValue containing the final node.
2815 
2816 /// Darwin only has one TLS scheme which must be capable of dealing with the
2817 /// fully general situation, in the worst case. This means:
2818 ///     + "extern __thread" declaration.
2819 ///     + Defined in a possibly unknown dynamic library.
2820 ///
2821 /// The general system is that each __thread variable has a [3 x i32] descriptor
2822 /// which contains information used by the runtime to calculate the address. The
2823 /// only part of this the compiler needs to know about is the first word, which
2824 /// contains a function pointer that must be called with the address of the
2825 /// entire descriptor in "r0".
2826 ///
2827 /// Since this descriptor may be in a different unit, in general access must
2828 /// proceed along the usual ARM rules. A common sequence to produce is:
2829 ///
2830 ///     movw rT1, :lower16:_var$non_lazy_ptr
2831 ///     movt rT1, :upper16:_var$non_lazy_ptr
2832 ///     ldr r0, [rT1]
2833 ///     ldr rT2, [r0]
2834 ///     blx rT2
2835 ///     [...address now in r0...]
2836 SDValue
2837 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2838                                                SelectionDAG &DAG) const {
2839   assert(Subtarget->isTargetDarwin() &&
2840          "This function expects a Darwin target");
2841   SDLoc DL(Op);
2842 
2843   // First step is to get the address of the actua global symbol. This is where
2844   // the TLS descriptor lives.
2845   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2846 
2847   // The first entry in the descriptor is a function pointer that we must call
2848   // to obtain the address of the variable.
2849   SDValue Chain = DAG.getEntryNode();
2850   SDValue FuncTLVGet = DAG.getLoad(
2851       MVT::i32, DL, Chain, DescAddr,
2852       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2853       /* Alignment = */ 4,
2854       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2855           MachineMemOperand::MOInvariant);
2856   Chain = FuncTLVGet.getValue(1);
2857 
2858   MachineFunction &F = DAG.getMachineFunction();
2859   MachineFrameInfo &MFI = F.getFrameInfo();
2860   MFI.setAdjustsStack(true);
2861 
2862   // TLS calls preserve all registers except those that absolutely must be
2863   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2864   // silly).
2865   auto TRI =
2866       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
2867   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2868   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2869 
2870   // Finally, we can make the call. This is just a degenerate version of a
2871   // normal AArch64 call node: r0 takes the address of the descriptor, and
2872   // returns the address of the variable in this thread.
2873   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2874   Chain =
2875       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2876                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2877                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2878   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2879 }
2880 
2881 SDValue
2882 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2883                                                 SelectionDAG &DAG) const {
2884   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2885 
2886   SDValue Chain = DAG.getEntryNode();
2887   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2888   SDLoc DL(Op);
2889 
2890   // Load the current TEB (thread environment block)
2891   SDValue Ops[] = {Chain,
2892                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2893                    DAG.getConstant(15, DL, MVT::i32),
2894                    DAG.getConstant(0, DL, MVT::i32),
2895                    DAG.getConstant(13, DL, MVT::i32),
2896                    DAG.getConstant(0, DL, MVT::i32),
2897                    DAG.getConstant(2, DL, MVT::i32)};
2898   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2899                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2900 
2901   SDValue TEB = CurrentTEB.getValue(0);
2902   Chain = CurrentTEB.getValue(1);
2903 
2904   // Load the ThreadLocalStoragePointer from the TEB
2905   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2906   SDValue TLSArray =
2907       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2908   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2909 
2910   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2911   // offset into the TLSArray.
2912 
2913   // Load the TLS index from the C runtime
2914   SDValue TLSIndex =
2915       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2916   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2917   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2918 
2919   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2920                               DAG.getConstant(2, DL, MVT::i32));
2921   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2922                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2923                             MachinePointerInfo());
2924 
2925   // Get the offset of the start of the .tls section (section base)
2926   const auto *GA = cast<GlobalAddressSDNode>(Op);
2927   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2928   SDValue Offset = DAG.getLoad(
2929       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2930                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2931       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2932 
2933   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2934 }
2935 
2936 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2937 SDValue
2938 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2939                                                  SelectionDAG &DAG) const {
2940   SDLoc dl(GA);
2941   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2942   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2943   MachineFunction &MF = DAG.getMachineFunction();
2944   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2945   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2946   ARMConstantPoolValue *CPV =
2947     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2948                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2949   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2950   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2951   Argument = DAG.getLoad(
2952       PtrVT, dl, DAG.getEntryNode(), Argument,
2953       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2954   SDValue Chain = Argument.getValue(1);
2955 
2956   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2957   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2958 
2959   // call __tls_get_addr.
2960   ArgListTy Args;
2961   ArgListEntry Entry;
2962   Entry.Node = Argument;
2963   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2964   Args.push_back(Entry);
2965 
2966   // FIXME: is there useful debug info available here?
2967   TargetLowering::CallLoweringInfo CLI(DAG);
2968   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2969       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2970       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2971 
2972   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2973   return CallResult.first;
2974 }
2975 
2976 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2977 // "local exec" model.
2978 SDValue
2979 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2980                                         SelectionDAG &DAG,
2981                                         TLSModel::Model model) const {
2982   const GlobalValue *GV = GA->getGlobal();
2983   SDLoc dl(GA);
2984   SDValue Offset;
2985   SDValue Chain = DAG.getEntryNode();
2986   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2987   // Get the Thread Pointer
2988   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2989 
2990   if (model == TLSModel::InitialExec) {
2991     MachineFunction &MF = DAG.getMachineFunction();
2992     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2993     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2994     // Initial exec model.
2995     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2996     ARMConstantPoolValue *CPV =
2997       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2998                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2999                                       true);
3000     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3001     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3002     Offset = DAG.getLoad(
3003         PtrVT, dl, Chain, Offset,
3004         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3005     Chain = Offset.getValue(1);
3006 
3007     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3008     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
3009 
3010     Offset = DAG.getLoad(
3011         PtrVT, dl, Chain, Offset,
3012         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3013   } else {
3014     // local exec model
3015     assert(model == TLSModel::LocalExec);
3016     ARMConstantPoolValue *CPV =
3017       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
3018     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3019     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3020     Offset = DAG.getLoad(
3021         PtrVT, dl, Chain, Offset,
3022         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3023   }
3024 
3025   // The address of the thread local variable is the add of the thread
3026   // pointer with the offset of the variable.
3027   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3028 }
3029 
3030 SDValue
3031 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3032   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3033   if (DAG.getTarget().useEmulatedTLS())
3034     return LowerToTLSEmulatedModel(GA, DAG);
3035 
3036   if (Subtarget->isTargetDarwin())
3037     return LowerGlobalTLSAddressDarwin(Op, DAG);
3038 
3039   if (Subtarget->isTargetWindows())
3040     return LowerGlobalTLSAddressWindows(Op, DAG);
3041 
3042   // TODO: implement the "local dynamic" model
3043   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3044   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3045 
3046   switch (model) {
3047     case TLSModel::GeneralDynamic:
3048     case TLSModel::LocalDynamic:
3049       return LowerToTLSGeneralDynamicModel(GA, DAG);
3050     case TLSModel::InitialExec:
3051     case TLSModel::LocalExec:
3052       return LowerToTLSExecModels(GA, DAG, model);
3053   }
3054   llvm_unreachable("bogus TLS model");
3055 }
3056 
3057 /// Return true if all users of V are within function F, looking through
3058 /// ConstantExprs.
3059 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3060   SmallVector<const User*,4> Worklist;
3061   for (auto *U : V->users())
3062     Worklist.push_back(U);
3063   while (!Worklist.empty()) {
3064     auto *U = Worklist.pop_back_val();
3065     if (isa<ConstantExpr>(U)) {
3066       for (auto *UU : U->users())
3067         Worklist.push_back(UU);
3068       continue;
3069     }
3070 
3071     auto *I = dyn_cast<Instruction>(U);
3072     if (!I || I->getParent()->getParent() != F)
3073       return false;
3074   }
3075   return true;
3076 }
3077 
3078 static SDValue promoteToConstantPool(const ARMTargetLowering *TLI,
3079                                      const GlobalValue *GV, SelectionDAG &DAG,
3080                                      EVT PtrVT, const SDLoc &dl) {
3081   // If we're creating a pool entry for a constant global with unnamed address,
3082   // and the global is small enough, we can emit it inline into the constant pool
3083   // to save ourselves an indirection.
3084   //
3085   // This is a win if the constant is only used in one function (so it doesn't
3086   // need to be duplicated) or duplicating the constant wouldn't increase code
3087   // size (implying the constant is no larger than 4 bytes).
3088   const Function &F = DAG.getMachineFunction().getFunction();
3089 
3090   // We rely on this decision to inline being idemopotent and unrelated to the
3091   // use-site. We know that if we inline a variable at one use site, we'll
3092   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3093   // doesn't know about this optimization, so bail out if it's enabled else
3094   // we could decide to inline here (and thus never emit the GV) but require
3095   // the GV from fast-isel generated code.
3096   if (!EnableConstpoolPromotion ||
3097       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3098       return SDValue();
3099 
3100   auto *GVar = dyn_cast<GlobalVariable>(GV);
3101   if (!GVar || !GVar->hasInitializer() ||
3102       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3103       !GVar->hasLocalLinkage())
3104     return SDValue();
3105 
3106   // If we inline a value that contains relocations, we move the relocations
3107   // from .data to .text. This is not allowed in position-independent code.
3108   auto *Init = GVar->getInitializer();
3109   if ((TLI->isPositionIndependent() || TLI->getSubtarget()->isROPI()) &&
3110       Init->needsRelocation())
3111     return SDValue();
3112 
3113   // The constant islands pass can only really deal with alignment requests
3114   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3115   // any type wanting greater alignment requirements than 4 bytes. We also
3116   // can only promote constants that are multiples of 4 bytes in size or
3117   // are paddable to a multiple of 4. Currently we only try and pad constants
3118   // that are strings for simplicity.
3119   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3120   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3121   unsigned Align = DAG.getDataLayout().getPreferredAlignment(GVar);
3122   unsigned RequiredPadding = 4 - (Size % 4);
3123   bool PaddingPossible =
3124     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3125   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3126       Size == 0)
3127     return SDValue();
3128 
3129   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3130   MachineFunction &MF = DAG.getMachineFunction();
3131   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3132 
3133   // We can't bloat the constant pool too much, else the ConstantIslands pass
3134   // may fail to converge. If we haven't promoted this global yet (it may have
3135   // multiple uses), and promoting it would increase the constant pool size (Sz
3136   // > 4), ensure we have space to do so up to MaxTotal.
3137   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3138     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3139         ConstpoolPromotionMaxTotal)
3140       return SDValue();
3141 
3142   // This is only valid if all users are in a single function; we can't clone
3143   // the constant in general. The LLVM IR unnamed_addr allows merging
3144   // constants, but not cloning them.
3145   //
3146   // We could potentially allow cloning if we could prove all uses of the
3147   // constant in the current function don't care about the address, like
3148   // printf format strings. But that isn't implemented for now.
3149   if (!allUsersAreInFunction(GVar, &F))
3150     return SDValue();
3151 
3152   // We're going to inline this global. Pad it out if needed.
3153   if (RequiredPadding != 4) {
3154     StringRef S = CDAInit->getAsString();
3155 
3156     SmallVector<uint8_t,16> V(S.size());
3157     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3158     while (RequiredPadding--)
3159       V.push_back(0);
3160     Init = ConstantDataArray::get(*DAG.getContext(), V);
3161   }
3162 
3163   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3164   SDValue CPAddr =
3165     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3166   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3167     AFI->markGlobalAsPromotedToConstantPool(GVar);
3168     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3169                                       PaddedSize - 4);
3170   }
3171   ++NumConstpoolPromoted;
3172   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3173 }
3174 
3175 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3176   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3177     if (!(GV = GA->getBaseObject()))
3178       return false;
3179   if (const auto *V = dyn_cast<GlobalVariable>(GV))
3180     return V->isConstant();
3181   return isa<Function>(GV);
3182 }
3183 
3184 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3185                                               SelectionDAG &DAG) const {
3186   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3187   default: llvm_unreachable("unknown object format");
3188   case Triple::COFF:
3189     return LowerGlobalAddressWindows(Op, DAG);
3190   case Triple::ELF:
3191     return LowerGlobalAddressELF(Op, DAG);
3192   case Triple::MachO:
3193     return LowerGlobalAddressDarwin(Op, DAG);
3194   }
3195 }
3196 
3197 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3198                                                  SelectionDAG &DAG) const {
3199   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3200   SDLoc dl(Op);
3201   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3202   const TargetMachine &TM = getTargetMachine();
3203   bool IsRO = isReadOnly(GV);
3204 
3205   // promoteToConstantPool only if not generating XO text section
3206   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3207     if (SDValue V = promoteToConstantPool(this, GV, DAG, PtrVT, dl))
3208       return V;
3209 
3210   if (isPositionIndependent()) {
3211     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3212     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3213                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3214     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3215     if (UseGOT_PREL)
3216       Result =
3217           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3218                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3219     return Result;
3220   } else if (Subtarget->isROPI() && IsRO) {
3221     // PC-relative.
3222     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3223     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3224     return Result;
3225   } else if (Subtarget->isRWPI() && !IsRO) {
3226     // SB-relative.
3227     SDValue RelAddr;
3228     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3229       ++NumMovwMovt;
3230       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3231       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3232     } else { // use literal pool for address constant
3233       ARMConstantPoolValue *CPV =
3234         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3235       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3236       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3237       RelAddr = DAG.getLoad(
3238           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3239           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3240     }
3241     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3242     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3243     return Result;
3244   }
3245 
3246   // If we have T2 ops, we can materialize the address directly via movt/movw
3247   // pair. This is always cheaper.
3248   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3249     ++NumMovwMovt;
3250     // FIXME: Once remat is capable of dealing with instructions with register
3251     // operands, expand this into two nodes.
3252     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3253                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3254   } else {
3255     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3256     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3257     return DAG.getLoad(
3258         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3259         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3260   }
3261 }
3262 
3263 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3264                                                     SelectionDAG &DAG) const {
3265   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3266          "ROPI/RWPI not currently supported for Darwin");
3267   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3268   SDLoc dl(Op);
3269   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3270 
3271   if (Subtarget->useMovt(DAG.getMachineFunction()))
3272     ++NumMovwMovt;
3273 
3274   // FIXME: Once remat is capable of dealing with instructions with register
3275   // operands, expand this into multiple nodes
3276   unsigned Wrapper =
3277       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3278 
3279   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3280   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3281 
3282   if (Subtarget->isGVIndirectSymbol(GV))
3283     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3284                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3285   return Result;
3286 }
3287 
3288 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3289                                                      SelectionDAG &DAG) const {
3290   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3291   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3292          "Windows on ARM expects to use movw/movt");
3293   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3294          "ROPI/RWPI not currently supported for Windows");
3295 
3296   const TargetMachine &TM = getTargetMachine();
3297   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3298   ARMII::TOF TargetFlags = ARMII::MO_NO_FLAG;
3299   if (GV->hasDLLImportStorageClass())
3300     TargetFlags = ARMII::MO_DLLIMPORT;
3301   else if (!TM.shouldAssumeDSOLocal(*GV->getParent(), GV))
3302     TargetFlags = ARMII::MO_COFFSTUB;
3303   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3304   SDValue Result;
3305   SDLoc DL(Op);
3306 
3307   ++NumMovwMovt;
3308 
3309   // FIXME: Once remat is capable of dealing with instructions with register
3310   // operands, expand this into two nodes.
3311   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3312                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3313                                                   TargetFlags));
3314   if (TargetFlags & (ARMII::MO_DLLIMPORT | ARMII::MO_COFFSTUB))
3315     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3316                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3317   return Result;
3318 }
3319 
3320 SDValue
3321 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3322   SDLoc dl(Op);
3323   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3324   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3325                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3326                      Op.getOperand(1), Val);
3327 }
3328 
3329 SDValue
3330 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3331   SDLoc dl(Op);
3332   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3333                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3334 }
3335 
3336 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3337                                                       SelectionDAG &DAG) const {
3338   SDLoc dl(Op);
3339   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3340                      Op.getOperand(0));
3341 }
3342 
3343 SDValue
3344 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3345                                           const ARMSubtarget *Subtarget) const {
3346   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3347   SDLoc dl(Op);
3348   switch (IntNo) {
3349   default: return SDValue();    // Don't custom lower most intrinsics.
3350   case Intrinsic::thread_pointer: {
3351     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3352     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3353   }
3354   case Intrinsic::eh_sjlj_lsda: {
3355     MachineFunction &MF = DAG.getMachineFunction();
3356     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3357     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3358     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3359     SDValue CPAddr;
3360     bool IsPositionIndependent = isPositionIndependent();
3361     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3362     ARMConstantPoolValue *CPV =
3363       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3364                                       ARMCP::CPLSDA, PCAdj);
3365     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3366     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3367     SDValue Result = DAG.getLoad(
3368         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3369         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3370 
3371     if (IsPositionIndependent) {
3372       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3373       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3374     }
3375     return Result;
3376   }
3377   case Intrinsic::arm_neon_vabs:
3378     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3379                         Op.getOperand(1));
3380   case Intrinsic::arm_neon_vmulls:
3381   case Intrinsic::arm_neon_vmullu: {
3382     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3383       ? ARMISD::VMULLs : ARMISD::VMULLu;
3384     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3385                        Op.getOperand(1), Op.getOperand(2));
3386   }
3387   case Intrinsic::arm_neon_vminnm:
3388   case Intrinsic::arm_neon_vmaxnm: {
3389     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3390       ? ISD::FMINNUM : ISD::FMAXNUM;
3391     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3392                        Op.getOperand(1), Op.getOperand(2));
3393   }
3394   case Intrinsic::arm_neon_vminu:
3395   case Intrinsic::arm_neon_vmaxu: {
3396     if (Op.getValueType().isFloatingPoint())
3397       return SDValue();
3398     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3399       ? ISD::UMIN : ISD::UMAX;
3400     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3401                          Op.getOperand(1), Op.getOperand(2));
3402   }
3403   case Intrinsic::arm_neon_vmins:
3404   case Intrinsic::arm_neon_vmaxs: {
3405     // v{min,max}s is overloaded between signed integers and floats.
3406     if (!Op.getValueType().isFloatingPoint()) {
3407       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3408         ? ISD::SMIN : ISD::SMAX;
3409       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3410                          Op.getOperand(1), Op.getOperand(2));
3411     }
3412     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3413       ? ISD::FMINIMUM : ISD::FMAXIMUM;
3414     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3415                        Op.getOperand(1), Op.getOperand(2));
3416   }
3417   case Intrinsic::arm_neon_vtbl1:
3418     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3419                        Op.getOperand(1), Op.getOperand(2));
3420   case Intrinsic::arm_neon_vtbl2:
3421     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3422                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3423   }
3424 }
3425 
3426 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3427                                  const ARMSubtarget *Subtarget) {
3428   SDLoc dl(Op);
3429   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3430   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3431   if (SSID == SyncScope::SingleThread)
3432     return Op;
3433 
3434   if (!Subtarget->hasDataBarrier()) {
3435     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3436     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3437     // here.
3438     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3439            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3440     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3441                        DAG.getConstant(0, dl, MVT::i32));
3442   }
3443 
3444   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3445   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3446   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3447   if (Subtarget->isMClass()) {
3448     // Only a full system barrier exists in the M-class architectures.
3449     Domain = ARM_MB::SY;
3450   } else if (Subtarget->preferISHSTBarriers() &&
3451              Ord == AtomicOrdering::Release) {
3452     // Swift happens to implement ISHST barriers in a way that's compatible with
3453     // Release semantics but weaker than ISH so we'd be fools not to use
3454     // it. Beware: other processors probably don't!
3455     Domain = ARM_MB::ISHST;
3456   }
3457 
3458   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3459                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3460                      DAG.getConstant(Domain, dl, MVT::i32));
3461 }
3462 
3463 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3464                              const ARMSubtarget *Subtarget) {
3465   // ARM pre v5TE and Thumb1 does not have preload instructions.
3466   if (!(Subtarget->isThumb2() ||
3467         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3468     // Just preserve the chain.
3469     return Op.getOperand(0);
3470 
3471   SDLoc dl(Op);
3472   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3473   if (!isRead &&
3474       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3475     // ARMv7 with MP extension has PLDW.
3476     return Op.getOperand(0);
3477 
3478   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3479   if (Subtarget->isThumb()) {
3480     // Invert the bits.
3481     isRead = ~isRead & 1;
3482     isData = ~isData & 1;
3483   }
3484 
3485   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3486                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3487                      DAG.getConstant(isData, dl, MVT::i32));
3488 }
3489 
3490 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3491   MachineFunction &MF = DAG.getMachineFunction();
3492   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3493 
3494   // vastart just stores the address of the VarArgsFrameIndex slot into the
3495   // memory location argument.
3496   SDLoc dl(Op);
3497   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3498   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3499   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3500   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3501                       MachinePointerInfo(SV));
3502 }
3503 
3504 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3505                                                 CCValAssign &NextVA,
3506                                                 SDValue &Root,
3507                                                 SelectionDAG &DAG,
3508                                                 const SDLoc &dl) const {
3509   MachineFunction &MF = DAG.getMachineFunction();
3510   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3511 
3512   const TargetRegisterClass *RC;
3513   if (AFI->isThumb1OnlyFunction())
3514     RC = &ARM::tGPRRegClass;
3515   else
3516     RC = &ARM::GPRRegClass;
3517 
3518   // Transform the arguments stored in physical registers into virtual ones.
3519   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3520   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3521 
3522   SDValue ArgValue2;
3523   if (NextVA.isMemLoc()) {
3524     MachineFrameInfo &MFI = MF.getFrameInfo();
3525     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3526 
3527     // Create load node to retrieve arguments from the stack.
3528     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3529     ArgValue2 = DAG.getLoad(
3530         MVT::i32, dl, Root, FIN,
3531         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3532   } else {
3533     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3534     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3535   }
3536   if (!Subtarget->isLittle())
3537     std::swap (ArgValue, ArgValue2);
3538   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3539 }
3540 
3541 // The remaining GPRs hold either the beginning of variable-argument
3542 // data, or the beginning of an aggregate passed by value (usually
3543 // byval).  Either way, we allocate stack slots adjacent to the data
3544 // provided by our caller, and store the unallocated registers there.
3545 // If this is a variadic function, the va_list pointer will begin with
3546 // these values; otherwise, this reassembles a (byval) structure that
3547 // was split between registers and memory.
3548 // Return: The frame index registers were stored into.
3549 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3550                                       const SDLoc &dl, SDValue &Chain,
3551                                       const Value *OrigArg,
3552                                       unsigned InRegsParamRecordIdx,
3553                                       int ArgOffset, unsigned ArgSize) const {
3554   // Currently, two use-cases possible:
3555   // Case #1. Non-var-args function, and we meet first byval parameter.
3556   //          Setup first unallocated register as first byval register;
3557   //          eat all remained registers
3558   //          (these two actions are performed by HandleByVal method).
3559   //          Then, here, we initialize stack frame with
3560   //          "store-reg" instructions.
3561   // Case #2. Var-args function, that doesn't contain byval parameters.
3562   //          The same: eat all remained unallocated registers,
3563   //          initialize stack frame.
3564 
3565   MachineFunction &MF = DAG.getMachineFunction();
3566   MachineFrameInfo &MFI = MF.getFrameInfo();
3567   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3568   unsigned RBegin, REnd;
3569   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3570     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3571   } else {
3572     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3573     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3574     REnd = ARM::R4;
3575   }
3576 
3577   if (REnd != RBegin)
3578     ArgOffset = -4 * (ARM::R4 - RBegin);
3579 
3580   auto PtrVT = getPointerTy(DAG.getDataLayout());
3581   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3582   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3583 
3584   SmallVector<SDValue, 4> MemOps;
3585   const TargetRegisterClass *RC =
3586       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3587 
3588   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3589     unsigned VReg = MF.addLiveIn(Reg, RC);
3590     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3591     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3592                                  MachinePointerInfo(OrigArg, 4 * i));
3593     MemOps.push_back(Store);
3594     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3595   }
3596 
3597   if (!MemOps.empty())
3598     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3599   return FrameIndex;
3600 }
3601 
3602 // Setup stack frame, the va_list pointer will start from.
3603 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3604                                              const SDLoc &dl, SDValue &Chain,
3605                                              unsigned ArgOffset,
3606                                              unsigned TotalArgRegsSaveSize,
3607                                              bool ForceMutable) const {
3608   MachineFunction &MF = DAG.getMachineFunction();
3609   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3610 
3611   // Try to store any remaining integer argument regs
3612   // to their spots on the stack so that they may be loaded by dereferencing
3613   // the result of va_next.
3614   // If there is no regs to be stored, just point address after last
3615   // argument passed via stack.
3616   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3617                                   CCInfo.getInRegsParamsCount(),
3618                                   CCInfo.getNextStackOffset(), 4);
3619   AFI->setVarArgsFrameIndex(FrameIndex);
3620 }
3621 
3622 SDValue ARMTargetLowering::LowerFormalArguments(
3623     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3624     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3625     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3626   MachineFunction &MF = DAG.getMachineFunction();
3627   MachineFrameInfo &MFI = MF.getFrameInfo();
3628 
3629   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3630 
3631   // Assign locations to all of the incoming arguments.
3632   SmallVector<CCValAssign, 16> ArgLocs;
3633   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3634                  *DAG.getContext());
3635   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3636 
3637   SmallVector<SDValue, 16> ArgValues;
3638   SDValue ArgValue;
3639   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3640   unsigned CurArgIdx = 0;
3641 
3642   // Initially ArgRegsSaveSize is zero.
3643   // Then we increase this value each time we meet byval parameter.
3644   // We also increase this value in case of varargs function.
3645   AFI->setArgRegsSaveSize(0);
3646 
3647   // Calculate the amount of stack space that we need to allocate to store
3648   // byval and variadic arguments that are passed in registers.
3649   // We need to know this before we allocate the first byval or variadic
3650   // argument, as they will be allocated a stack slot below the CFA (Canonical
3651   // Frame Address, the stack pointer at entry to the function).
3652   unsigned ArgRegBegin = ARM::R4;
3653   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3654     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3655       break;
3656 
3657     CCValAssign &VA = ArgLocs[i];
3658     unsigned Index = VA.getValNo();
3659     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3660     if (!Flags.isByVal())
3661       continue;
3662 
3663     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3664     unsigned RBegin, REnd;
3665     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3666     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3667 
3668     CCInfo.nextInRegsParam();
3669   }
3670   CCInfo.rewindByValRegsInfo();
3671 
3672   int lastInsIndex = -1;
3673   if (isVarArg && MFI.hasVAStart()) {
3674     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3675     if (RegIdx != array_lengthof(GPRArgRegs))
3676       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3677   }
3678 
3679   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3680   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3681   auto PtrVT = getPointerTy(DAG.getDataLayout());
3682 
3683   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3684     CCValAssign &VA = ArgLocs[i];
3685     if (Ins[VA.getValNo()].isOrigArg()) {
3686       std::advance(CurOrigArg,
3687                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3688       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3689     }
3690     // Arguments stored in registers.
3691     if (VA.isRegLoc()) {
3692       EVT RegVT = VA.getLocVT();
3693 
3694       if (VA.needsCustom()) {
3695         // f64 and vector types are split up into multiple registers or
3696         // combinations of registers and stack slots.
3697         if (VA.getLocVT() == MVT::v2f64) {
3698           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3699                                                    Chain, DAG, dl);
3700           VA = ArgLocs[++i]; // skip ahead to next loc
3701           SDValue ArgValue2;
3702           if (VA.isMemLoc()) {
3703             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3704             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3705             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3706                                     MachinePointerInfo::getFixedStack(
3707                                         DAG.getMachineFunction(), FI));
3708           } else {
3709             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3710                                              Chain, DAG, dl);
3711           }
3712           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3713           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3714                                  ArgValue, ArgValue1,
3715                                  DAG.getIntPtrConstant(0, dl));
3716           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3717                                  ArgValue, ArgValue2,
3718                                  DAG.getIntPtrConstant(1, dl));
3719         } else
3720           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3721       } else {
3722         const TargetRegisterClass *RC;
3723 
3724 
3725         if (RegVT == MVT::f16)
3726           RC = &ARM::HPRRegClass;
3727         else if (RegVT == MVT::f32)
3728           RC = &ARM::SPRRegClass;
3729         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3730           RC = &ARM::DPRRegClass;
3731         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3732           RC = &ARM::QPRRegClass;
3733         else if (RegVT == MVT::i32)
3734           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3735                                            : &ARM::GPRRegClass;
3736         else
3737           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3738 
3739         // Transform the arguments in physical registers into virtual ones.
3740         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3741         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3742       }
3743 
3744       // If this is an 8 or 16-bit value, it is really passed promoted
3745       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3746       // truncate to the right size.
3747       switch (VA.getLocInfo()) {
3748       default: llvm_unreachable("Unknown loc info!");
3749       case CCValAssign::Full: break;
3750       case CCValAssign::BCvt:
3751         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3752         break;
3753       case CCValAssign::SExt:
3754         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3755                                DAG.getValueType(VA.getValVT()));
3756         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3757         break;
3758       case CCValAssign::ZExt:
3759         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3760                                DAG.getValueType(VA.getValVT()));
3761         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3762         break;
3763       }
3764 
3765       InVals.push_back(ArgValue);
3766     } else { // VA.isRegLoc()
3767       // sanity check
3768       assert(VA.isMemLoc());
3769       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3770 
3771       int index = VA.getValNo();
3772 
3773       // Some Ins[] entries become multiple ArgLoc[] entries.
3774       // Process them only once.
3775       if (index != lastInsIndex)
3776         {
3777           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3778           // FIXME: For now, all byval parameter objects are marked mutable.
3779           // This can be changed with more analysis.
3780           // In case of tail call optimization mark all arguments mutable.
3781           // Since they could be overwritten by lowering of arguments in case of
3782           // a tail call.
3783           if (Flags.isByVal()) {
3784             assert(Ins[index].isOrigArg() &&
3785                    "Byval arguments cannot be implicit");
3786             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3787 
3788             int FrameIndex = StoreByValRegs(
3789                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3790                 VA.getLocMemOffset(), Flags.getByValSize());
3791             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3792             CCInfo.nextInRegsParam();
3793           } else {
3794             unsigned FIOffset = VA.getLocMemOffset();
3795             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3796                                            FIOffset, true);
3797 
3798             // Create load nodes to retrieve arguments from the stack.
3799             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3800             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3801                                          MachinePointerInfo::getFixedStack(
3802                                              DAG.getMachineFunction(), FI)));
3803           }
3804           lastInsIndex = index;
3805         }
3806     }
3807   }
3808 
3809   // varargs
3810   if (isVarArg && MFI.hasVAStart())
3811     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3812                          CCInfo.getNextStackOffset(),
3813                          TotalArgRegsSaveSize);
3814 
3815   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3816 
3817   return Chain;
3818 }
3819 
3820 /// isFloatingPointZero - Return true if this is +0.0.
3821 static bool isFloatingPointZero(SDValue Op) {
3822   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3823     return CFP->getValueAPF().isPosZero();
3824   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3825     // Maybe this has already been legalized into the constant pool?
3826     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3827       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3828       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3829         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3830           return CFP->getValueAPF().isPosZero();
3831     }
3832   } else if (Op->getOpcode() == ISD::BITCAST &&
3833              Op->getValueType(0) == MVT::f64) {
3834     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3835     // created by LowerConstantFP().
3836     SDValue BitcastOp = Op->getOperand(0);
3837     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3838         isNullConstant(BitcastOp->getOperand(0)))
3839       return true;
3840   }
3841   return false;
3842 }
3843 
3844 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3845 /// the given operands.
3846 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3847                                      SDValue &ARMcc, SelectionDAG &DAG,
3848                                      const SDLoc &dl) const {
3849   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3850     unsigned C = RHSC->getZExtValue();
3851     if (!isLegalICmpImmediate((int32_t)C)) {
3852       // Constant does not fit, try adjusting it by one.
3853       switch (CC) {
3854       default: break;
3855       case ISD::SETLT:
3856       case ISD::SETGE:
3857         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3858           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3859           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3860         }
3861         break;
3862       case ISD::SETULT:
3863       case ISD::SETUGE:
3864         if (C != 0 && isLegalICmpImmediate(C-1)) {
3865           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3866           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3867         }
3868         break;
3869       case ISD::SETLE:
3870       case ISD::SETGT:
3871         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3872           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3873           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3874         }
3875         break;
3876       case ISD::SETULE:
3877       case ISD::SETUGT:
3878         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3879           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3880           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3881         }
3882         break;
3883       }
3884     }
3885   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
3886              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
3887     // In ARM and Thumb-2, the compare instructions can shift their second
3888     // operand.
3889     CC = ISD::getSetCCSwappedOperands(CC);
3890     std::swap(LHS, RHS);
3891   }
3892 
3893   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3894   ARMISD::NodeType CompareType;
3895   switch (CondCode) {
3896   default:
3897     CompareType = ARMISD::CMP;
3898     break;
3899   case ARMCC::EQ:
3900   case ARMCC::NE:
3901     // Uses only Z Flag
3902     CompareType = ARMISD::CMPZ;
3903     break;
3904   }
3905   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3906   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3907 }
3908 
3909 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3910 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3911                                      SelectionDAG &DAG, const SDLoc &dl,
3912                                      bool InvalidOnQNaN) const {
3913   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3914   SDValue Cmp;
3915   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3916   if (!isFloatingPointZero(RHS))
3917     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3918   else
3919     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3920   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3921 }
3922 
3923 /// duplicateCmp - Glue values can have only one use, so this function
3924 /// duplicates a comparison node.
3925 SDValue
3926 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3927   unsigned Opc = Cmp.getOpcode();
3928   SDLoc DL(Cmp);
3929   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3930     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3931 
3932   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3933   Cmp = Cmp.getOperand(0);
3934   Opc = Cmp.getOpcode();
3935   if (Opc == ARMISD::CMPFP)
3936     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3937                       Cmp.getOperand(1), Cmp.getOperand(2));
3938   else {
3939     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3940     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3941                       Cmp.getOperand(1));
3942   }
3943   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3944 }
3945 
3946 // This function returns three things: the arithmetic computation itself
3947 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
3948 // comparison and the condition code define the case in which the arithmetic
3949 // computation *does not* overflow.
3950 std::pair<SDValue, SDValue>
3951 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3952                                  SDValue &ARMcc) const {
3953   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3954 
3955   SDValue Value, OverflowCmp;
3956   SDValue LHS = Op.getOperand(0);
3957   SDValue RHS = Op.getOperand(1);
3958   SDLoc dl(Op);
3959 
3960   // FIXME: We are currently always generating CMPs because we don't support
3961   // generating CMN through the backend. This is not as good as the natural
3962   // CMP case because it causes a register dependency and cannot be folded
3963   // later.
3964 
3965   switch (Op.getOpcode()) {
3966   default:
3967     llvm_unreachable("Unknown overflow instruction!");
3968   case ISD::SADDO:
3969     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3970     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3971     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3972     break;
3973   case ISD::UADDO:
3974     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3975     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
3976     // We do not use it in the USUBO case as Value may not be used.
3977     Value = DAG.getNode(ARMISD::ADDC, dl,
3978                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
3979                 .getValue(0);
3980     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3981     break;
3982   case ISD::SSUBO:
3983     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3984     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3985     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3986     break;
3987   case ISD::USUBO:
3988     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3989     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3990     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3991     break;
3992   case ISD::UMULO:
3993     // We generate a UMUL_LOHI and then check if the high word is 0.
3994     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
3995     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
3996                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
3997                         LHS, RHS);
3998     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
3999                               DAG.getConstant(0, dl, MVT::i32));
4000     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4001     break;
4002   case ISD::SMULO:
4003     // We generate a SMUL_LOHI and then check if all the bits of the high word
4004     // are the same as the sign bit of the low word.
4005     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4006     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4007                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4008                         LHS, RHS);
4009     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4010                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4011                                           Value.getValue(0),
4012                                           DAG.getConstant(31, dl, MVT::i32)));
4013     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4014     break;
4015   } // switch (...)
4016 
4017   return std::make_pair(Value, OverflowCmp);
4018 }
4019 
4020 SDValue
4021 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4022   // Let legalize expand this if it isn't a legal type yet.
4023   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4024     return SDValue();
4025 
4026   SDValue Value, OverflowCmp;
4027   SDValue ARMcc;
4028   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4029   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4030   SDLoc dl(Op);
4031   // We use 0 and 1 as false and true values.
4032   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4033   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4034   EVT VT = Op.getValueType();
4035 
4036   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4037                                  ARMcc, CCR, OverflowCmp);
4038 
4039   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4040   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4041 }
4042 
4043 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4044                                               SelectionDAG &DAG) {
4045   SDLoc DL(BoolCarry);
4046   EVT CarryVT = BoolCarry.getValueType();
4047 
4048   // This converts the boolean value carry into the carry flag by doing
4049   // ARMISD::SUBC Carry, 1
4050   SDValue Carry = DAG.getNode(ARMISD::SUBC, DL,
4051                               DAG.getVTList(CarryVT, MVT::i32),
4052                               BoolCarry, DAG.getConstant(1, DL, CarryVT));
4053   return Carry.getValue(1);
4054 }
4055 
4056 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4057                                               SelectionDAG &DAG) {
4058   SDLoc DL(Flags);
4059 
4060   // Now convert the carry flag into a boolean carry. We do this
4061   // using ARMISD:ADDE 0, 0, Carry
4062   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4063                      DAG.getConstant(0, DL, MVT::i32),
4064                      DAG.getConstant(0, DL, MVT::i32), Flags);
4065 }
4066 
4067 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4068                                              SelectionDAG &DAG) const {
4069   // Let legalize expand this if it isn't a legal type yet.
4070   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4071     return SDValue();
4072 
4073   SDValue LHS = Op.getOperand(0);
4074   SDValue RHS = Op.getOperand(1);
4075   SDLoc dl(Op);
4076 
4077   EVT VT = Op.getValueType();
4078   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4079   SDValue Value;
4080   SDValue Overflow;
4081   switch (Op.getOpcode()) {
4082   default:
4083     llvm_unreachable("Unknown overflow instruction!");
4084   case ISD::UADDO:
4085     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4086     // Convert the carry flag into a boolean value.
4087     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4088     break;
4089   case ISD::USUBO: {
4090     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4091     // Convert the carry flag into a boolean value.
4092     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4093     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4094     // value. So compute 1 - C.
4095     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4096                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4097     break;
4098   }
4099   }
4100 
4101   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4102 }
4103 
4104 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4105   SDValue Cond = Op.getOperand(0);
4106   SDValue SelectTrue = Op.getOperand(1);
4107   SDValue SelectFalse = Op.getOperand(2);
4108   SDLoc dl(Op);
4109   unsigned Opc = Cond.getOpcode();
4110 
4111   if (Cond.getResNo() == 1 &&
4112       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4113        Opc == ISD::USUBO)) {
4114     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4115       return SDValue();
4116 
4117     SDValue Value, OverflowCmp;
4118     SDValue ARMcc;
4119     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4120     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4121     EVT VT = Op.getValueType();
4122 
4123     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4124                    OverflowCmp, DAG);
4125   }
4126 
4127   // Convert:
4128   //
4129   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4130   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4131   //
4132   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4133     const ConstantSDNode *CMOVTrue =
4134       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4135     const ConstantSDNode *CMOVFalse =
4136       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4137 
4138     if (CMOVTrue && CMOVFalse) {
4139       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4140       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4141 
4142       SDValue True;
4143       SDValue False;
4144       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4145         True = SelectTrue;
4146         False = SelectFalse;
4147       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4148         True = SelectFalse;
4149         False = SelectTrue;
4150       }
4151 
4152       if (True.getNode() && False.getNode()) {
4153         EVT VT = Op.getValueType();
4154         SDValue ARMcc = Cond.getOperand(2);
4155         SDValue CCR = Cond.getOperand(3);
4156         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4157         assert(True.getValueType() == VT);
4158         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4159       }
4160     }
4161   }
4162 
4163   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4164   // undefined bits before doing a full-word comparison with zero.
4165   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4166                      DAG.getConstant(1, dl, Cond.getValueType()));
4167 
4168   return DAG.getSelectCC(dl, Cond,
4169                          DAG.getConstant(0, dl, Cond.getValueType()),
4170                          SelectTrue, SelectFalse, ISD::SETNE);
4171 }
4172 
4173 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4174                                  bool &swpCmpOps, bool &swpVselOps) {
4175   // Start by selecting the GE condition code for opcodes that return true for
4176   // 'equality'
4177   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4178       CC == ISD::SETULE)
4179     CondCode = ARMCC::GE;
4180 
4181   // and GT for opcodes that return false for 'equality'.
4182   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4183            CC == ISD::SETULT)
4184     CondCode = ARMCC::GT;
4185 
4186   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4187   // to swap the compare operands.
4188   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4189       CC == ISD::SETULT)
4190     swpCmpOps = true;
4191 
4192   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4193   // If we have an unordered opcode, we need to swap the operands to the VSEL
4194   // instruction (effectively negating the condition).
4195   //
4196   // This also has the effect of swapping which one of 'less' or 'greater'
4197   // returns true, so we also swap the compare operands. It also switches
4198   // whether we return true for 'equality', so we compensate by picking the
4199   // opposite condition code to our original choice.
4200   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4201       CC == ISD::SETUGT) {
4202     swpCmpOps = !swpCmpOps;
4203     swpVselOps = !swpVselOps;
4204     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4205   }
4206 
4207   // 'ordered' is 'anything but unordered', so use the VS condition code and
4208   // swap the VSEL operands.
4209   if (CC == ISD::SETO) {
4210     CondCode = ARMCC::VS;
4211     swpVselOps = true;
4212   }
4213 
4214   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4215   // code and swap the VSEL operands.
4216   if (CC == ISD::SETUNE) {
4217     CondCode = ARMCC::EQ;
4218     swpVselOps = true;
4219   }
4220 }
4221 
4222 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4223                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4224                                    SDValue Cmp, SelectionDAG &DAG) const {
4225   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4226     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4227                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4228     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4229                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4230 
4231     SDValue TrueLow = TrueVal.getValue(0);
4232     SDValue TrueHigh = TrueVal.getValue(1);
4233     SDValue FalseLow = FalseVal.getValue(0);
4234     SDValue FalseHigh = FalseVal.getValue(1);
4235 
4236     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4237                               ARMcc, CCR, Cmp);
4238     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4239                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4240 
4241     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4242   } else {
4243     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4244                        Cmp);
4245   }
4246 }
4247 
4248 static bool isGTorGE(ISD::CondCode CC) {
4249   return CC == ISD::SETGT || CC == ISD::SETGE;
4250 }
4251 
4252 static bool isLTorLE(ISD::CondCode CC) {
4253   return CC == ISD::SETLT || CC == ISD::SETLE;
4254 }
4255 
4256 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4257 // All of these conditions (and their <= and >= counterparts) will do:
4258 //          x < k ? k : x
4259 //          x > k ? x : k
4260 //          k < x ? x : k
4261 //          k > x ? k : x
4262 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4263                             const SDValue TrueVal, const SDValue FalseVal,
4264                             const ISD::CondCode CC, const SDValue K) {
4265   return (isGTorGE(CC) &&
4266           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4267          (isLTorLE(CC) &&
4268           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4269 }
4270 
4271 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4272 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4273                             const SDValue TrueVal, const SDValue FalseVal,
4274                             const ISD::CondCode CC, const SDValue K) {
4275   return (isGTorGE(CC) &&
4276           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4277          (isLTorLE(CC) &&
4278           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4279 }
4280 
4281 // Check if two chained conditionals could be converted into SSAT or USAT.
4282 //
4283 // SSAT can replace a set of two conditional selectors that bound a number to an
4284 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4285 //
4286 //     x < -k ? -k : (x > k ? k : x)
4287 //     x < -k ? -k : (x < k ? x : k)
4288 //     x > -k ? (x > k ? k : x) : -k
4289 //     x < k ? (x < -k ? -k : x) : k
4290 //     etc.
4291 //
4292 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4293 // a power of 2.
4294 //
4295 // It returns true if the conversion can be done, false otherwise.
4296 // Additionally, the variable is returned in parameter V, the constant in K and
4297 // usat is set to true if the conditional represents an unsigned saturation
4298 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4299                                     uint64_t &K, bool &usat) {
4300   SDValue LHS1 = Op.getOperand(0);
4301   SDValue RHS1 = Op.getOperand(1);
4302   SDValue TrueVal1 = Op.getOperand(2);
4303   SDValue FalseVal1 = Op.getOperand(3);
4304   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4305 
4306   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4307   if (Op2.getOpcode() != ISD::SELECT_CC)
4308     return false;
4309 
4310   SDValue LHS2 = Op2.getOperand(0);
4311   SDValue RHS2 = Op2.getOperand(1);
4312   SDValue TrueVal2 = Op2.getOperand(2);
4313   SDValue FalseVal2 = Op2.getOperand(3);
4314   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4315 
4316   // Find out which are the constants and which are the variables
4317   // in each conditional
4318   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4319                                                         ? &RHS1
4320                                                         : nullptr;
4321   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4322                                                         ? &RHS2
4323                                                         : nullptr;
4324   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4325   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4326   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4327   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4328 
4329   // We must detect cases where the original operations worked with 16- or
4330   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4331   // must work with sign-extended values but the select operations return
4332   // the original non-extended value.
4333   SDValue V2TmpReg = V2Tmp;
4334   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4335     V2TmpReg = V2Tmp->getOperand(0);
4336 
4337   // Check that the registers and the constants have the correct values
4338   // in both conditionals
4339   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4340       V2TmpReg != V2)
4341     return false;
4342 
4343   // Figure out which conditional is saturating the lower/upper bound.
4344   const SDValue *LowerCheckOp =
4345       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4346           ? &Op
4347           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4348                 ? &Op2
4349                 : nullptr;
4350   const SDValue *UpperCheckOp =
4351       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4352           ? &Op
4353           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4354                 ? &Op2
4355                 : nullptr;
4356 
4357   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4358     return false;
4359 
4360   // Check that the constant in the lower-bound check is
4361   // the opposite of the constant in the upper-bound check
4362   // in 1's complement.
4363   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4364   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4365   int64_t PosVal = std::max(Val1, Val2);
4366   int64_t NegVal = std::min(Val1, Val2);
4367 
4368   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4369        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4370       isPowerOf2_64(PosVal + 1)) {
4371 
4372     // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4373     if (Val1 == ~Val2)
4374       usat = false;
4375     else if (NegVal == 0)
4376       usat = true;
4377     else
4378       return false;
4379 
4380     V = V2;
4381     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4382 
4383     return true;
4384   }
4385 
4386   return false;
4387 }
4388 
4389 // Check if a condition of the type x < k ? k : x can be converted into a
4390 // bit operation instead of conditional moves.
4391 // Currently this is allowed given:
4392 // - The conditions and values match up
4393 // - k is 0 or -1 (all ones)
4394 // This function will not check the last condition, thats up to the caller
4395 // It returns true if the transformation can be made, and in such case
4396 // returns x in V, and k in SatK.
4397 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4398                                          SDValue &SatK)
4399 {
4400   SDValue LHS = Op.getOperand(0);
4401   SDValue RHS = Op.getOperand(1);
4402   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4403   SDValue TrueVal = Op.getOperand(2);
4404   SDValue FalseVal = Op.getOperand(3);
4405 
4406   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4407                                                ? &RHS
4408                                                : nullptr;
4409 
4410   // No constant operation in comparison, early out
4411   if (!K)
4412     return false;
4413 
4414   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4415   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4416   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4417 
4418   // If the constant on left and right side, or variable on left and right,
4419   // does not match, early out
4420   if (*K != KTmp || V != VTmp)
4421     return false;
4422 
4423   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4424     SatK = *K;
4425     return true;
4426   }
4427 
4428   return false;
4429 }
4430 
4431 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4432   EVT VT = Op.getValueType();
4433   SDLoc dl(Op);
4434 
4435   // Try to convert two saturating conditional selects into a single SSAT
4436   SDValue SatValue;
4437   uint64_t SatConstant;
4438   bool SatUSat;
4439   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4440       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4441     if (SatUSat)
4442       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4443                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4444     else
4445       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4446                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4447   }
4448 
4449   // Try to convert expressions of the form x < k ? k : x (and similar forms)
4450   // into more efficient bit operations, which is possible when k is 0 or -1
4451   // On ARM and Thumb-2 which have flexible operand 2 this will result in
4452   // single instructions. On Thumb the shift and the bit operation will be two
4453   // instructions.
4454   // Only allow this transformation on full-width (32-bit) operations
4455   SDValue LowerSatConstant;
4456   if (VT == MVT::i32 &&
4457       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4458     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4459                                  DAG.getConstant(31, dl, VT));
4460     if (isNullConstant(LowerSatConstant)) {
4461       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4462                                       DAG.getAllOnesConstant(dl, VT));
4463       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4464     } else if (isAllOnesConstant(LowerSatConstant))
4465       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4466   }
4467 
4468   SDValue LHS = Op.getOperand(0);
4469   SDValue RHS = Op.getOperand(1);
4470   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4471   SDValue TrueVal = Op.getOperand(2);
4472   SDValue FalseVal = Op.getOperand(3);
4473 
4474   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4475     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4476                                                     dl);
4477 
4478     // If softenSetCCOperands only returned one value, we should compare it to
4479     // zero.
4480     if (!RHS.getNode()) {
4481       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4482       CC = ISD::SETNE;
4483     }
4484   }
4485 
4486   if (LHS.getValueType() == MVT::i32) {
4487     // Try to generate VSEL on ARMv8.
4488     // The VSEL instruction can't use all the usual ARM condition
4489     // codes: it only has two bits to select the condition code, so it's
4490     // constrained to use only GE, GT, VS and EQ.
4491     //
4492     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4493     // swap the operands of the previous compare instruction (effectively
4494     // inverting the compare condition, swapping 'less' and 'greater') and
4495     // sometimes need to swap the operands to the VSEL (which inverts the
4496     // condition in the sense of firing whenever the previous condition didn't)
4497     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4498                                     TrueVal.getValueType() == MVT::f64)) {
4499       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4500       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4501           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4502         CC = ISD::getSetCCInverse(CC, true);
4503         std::swap(TrueVal, FalseVal);
4504       }
4505     }
4506 
4507     SDValue ARMcc;
4508     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4509     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4510     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4511   }
4512 
4513   ARMCC::CondCodes CondCode, CondCode2;
4514   bool InvalidOnQNaN;
4515   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4516 
4517   // Normalize the fp compare. If RHS is zero we keep it there so we match
4518   // CMPFPw0 instead of CMPFP.
4519   if (Subtarget->hasFPARMv8() && !isFloatingPointZero(RHS) &&
4520      (TrueVal.getValueType() == MVT::f16 ||
4521       TrueVal.getValueType() == MVT::f32 ||
4522       TrueVal.getValueType() == MVT::f64)) {
4523     bool swpCmpOps = false;
4524     bool swpVselOps = false;
4525     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4526 
4527     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4528         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4529       if (swpCmpOps)
4530         std::swap(LHS, RHS);
4531       if (swpVselOps)
4532         std::swap(TrueVal, FalseVal);
4533     }
4534   }
4535 
4536   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4537   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4538   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4539   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4540   if (CondCode2 != ARMCC::AL) {
4541     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4542     // FIXME: Needs another CMP because flag can have but one use.
4543     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4544     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4545   }
4546   return Result;
4547 }
4548 
4549 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4550 /// to morph to an integer compare sequence.
4551 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4552                            const ARMSubtarget *Subtarget) {
4553   SDNode *N = Op.getNode();
4554   if (!N->hasOneUse())
4555     // Otherwise it requires moving the value from fp to integer registers.
4556     return false;
4557   if (!N->getNumValues())
4558     return false;
4559   EVT VT = Op.getValueType();
4560   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4561     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4562     // vmrs are very slow, e.g. cortex-a8.
4563     return false;
4564 
4565   if (isFloatingPointZero(Op)) {
4566     SeenZero = true;
4567     return true;
4568   }
4569   return ISD::isNormalLoad(N);
4570 }
4571 
4572 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4573   if (isFloatingPointZero(Op))
4574     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4575 
4576   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4577     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4578                        Ld->getPointerInfo(), Ld->getAlignment(),
4579                        Ld->getMemOperand()->getFlags());
4580 
4581   llvm_unreachable("Unknown VFP cmp argument!");
4582 }
4583 
4584 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4585                            SDValue &RetVal1, SDValue &RetVal2) {
4586   SDLoc dl(Op);
4587 
4588   if (isFloatingPointZero(Op)) {
4589     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4590     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4591     return;
4592   }
4593 
4594   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4595     SDValue Ptr = Ld->getBasePtr();
4596     RetVal1 =
4597         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4598                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4599 
4600     EVT PtrType = Ptr.getValueType();
4601     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4602     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4603                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4604     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4605                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4606                           Ld->getMemOperand()->getFlags());
4607     return;
4608   }
4609 
4610   llvm_unreachable("Unknown VFP cmp argument!");
4611 }
4612 
4613 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4614 /// f32 and even f64 comparisons to integer ones.
4615 SDValue
4616 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4617   SDValue Chain = Op.getOperand(0);
4618   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4619   SDValue LHS = Op.getOperand(2);
4620   SDValue RHS = Op.getOperand(3);
4621   SDValue Dest = Op.getOperand(4);
4622   SDLoc dl(Op);
4623 
4624   bool LHSSeenZero = false;
4625   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4626   bool RHSSeenZero = false;
4627   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4628   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4629     // If unsafe fp math optimization is enabled and there are no other uses of
4630     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4631     // to an integer comparison.
4632     if (CC == ISD::SETOEQ)
4633       CC = ISD::SETEQ;
4634     else if (CC == ISD::SETUNE)
4635       CC = ISD::SETNE;
4636 
4637     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4638     SDValue ARMcc;
4639     if (LHS.getValueType() == MVT::f32) {
4640       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4641                         bitcastf32Toi32(LHS, DAG), Mask);
4642       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4643                         bitcastf32Toi32(RHS, DAG), Mask);
4644       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4645       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4646       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4647                          Chain, Dest, ARMcc, CCR, Cmp);
4648     }
4649 
4650     SDValue LHS1, LHS2;
4651     SDValue RHS1, RHS2;
4652     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4653     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4654     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4655     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4656     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4657     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4658     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4659     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4660     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4661   }
4662 
4663   return SDValue();
4664 }
4665 
4666 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4667   SDValue Chain = Op.getOperand(0);
4668   SDValue Cond = Op.getOperand(1);
4669   SDValue Dest = Op.getOperand(2);
4670   SDLoc dl(Op);
4671 
4672   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4673   // instruction.
4674   unsigned Opc = Cond.getOpcode();
4675   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4676                       !Subtarget->isThumb1Only();
4677   if (Cond.getResNo() == 1 &&
4678       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4679        Opc == ISD::USUBO || OptimizeMul)) {
4680     // Only lower legal XALUO ops.
4681     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4682       return SDValue();
4683 
4684     // The actual operation with overflow check.
4685     SDValue Value, OverflowCmp;
4686     SDValue ARMcc;
4687     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4688 
4689     // Reverse the condition code.
4690     ARMCC::CondCodes CondCode =
4691         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4692     CondCode = ARMCC::getOppositeCondition(CondCode);
4693     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4694     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4695 
4696     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4697                        OverflowCmp);
4698   }
4699 
4700   return SDValue();
4701 }
4702 
4703 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4704   SDValue Chain = Op.getOperand(0);
4705   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4706   SDValue LHS = Op.getOperand(2);
4707   SDValue RHS = Op.getOperand(3);
4708   SDValue Dest = Op.getOperand(4);
4709   SDLoc dl(Op);
4710 
4711   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4712     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4713                                                     dl);
4714 
4715     // If softenSetCCOperands only returned one value, we should compare it to
4716     // zero.
4717     if (!RHS.getNode()) {
4718       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4719       CC = ISD::SETNE;
4720     }
4721   }
4722 
4723   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4724   // instruction.
4725   unsigned Opc = LHS.getOpcode();
4726   bool OptimizeMul = (Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4727                       !Subtarget->isThumb1Only();
4728   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
4729       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4730        Opc == ISD::USUBO || OptimizeMul) &&
4731       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4732     // Only lower legal XALUO ops.
4733     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4734       return SDValue();
4735 
4736     // The actual operation with overflow check.
4737     SDValue Value, OverflowCmp;
4738     SDValue ARMcc;
4739     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
4740 
4741     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
4742       // Reverse the condition code.
4743       ARMCC::CondCodes CondCode =
4744           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4745       CondCode = ARMCC::getOppositeCondition(CondCode);
4746       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4747     }
4748     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4749 
4750     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4751                        OverflowCmp);
4752   }
4753 
4754   if (LHS.getValueType() == MVT::i32) {
4755     SDValue ARMcc;
4756     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4757     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4758     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4759                        Chain, Dest, ARMcc, CCR, Cmp);
4760   }
4761 
4762   if (getTargetMachine().Options.UnsafeFPMath &&
4763       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4764        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4765     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4766       return Result;
4767   }
4768 
4769   ARMCC::CondCodes CondCode, CondCode2;
4770   bool InvalidOnQNaN;
4771   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4772 
4773   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4774   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4775   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4776   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4777   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4778   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4779   if (CondCode2 != ARMCC::AL) {
4780     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4781     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4782     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4783   }
4784   return Res;
4785 }
4786 
4787 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4788   SDValue Chain = Op.getOperand(0);
4789   SDValue Table = Op.getOperand(1);
4790   SDValue Index = Op.getOperand(2);
4791   SDLoc dl(Op);
4792 
4793   EVT PTy = getPointerTy(DAG.getDataLayout());
4794   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4795   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4796   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4797   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4798   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
4799   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4800     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4801     // which does another jump to the destination. This also makes it easier
4802     // to translate it to TBB / TBH later (Thumb2 only).
4803     // FIXME: This might not work if the function is extremely large.
4804     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4805                        Addr, Op.getOperand(2), JTI);
4806   }
4807   if (isPositionIndependent() || Subtarget->isROPI()) {
4808     Addr =
4809         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4810                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4811     Chain = Addr.getValue(1);
4812     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
4813     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4814   } else {
4815     Addr =
4816         DAG.getLoad(PTy, dl, Chain, Addr,
4817                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4818     Chain = Addr.getValue(1);
4819     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4820   }
4821 }
4822 
4823 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4824   EVT VT = Op.getValueType();
4825   SDLoc dl(Op);
4826 
4827   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4828     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4829       return Op;
4830     return DAG.UnrollVectorOp(Op.getNode());
4831   }
4832 
4833   const bool HasFullFP16 =
4834     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
4835 
4836   EVT NewTy;
4837   const EVT OpTy = Op.getOperand(0).getValueType();
4838   if (OpTy == MVT::v4f32)
4839     NewTy = MVT::v4i32;
4840   else if (OpTy == MVT::v4f16 && HasFullFP16)
4841     NewTy = MVT::v4i16;
4842   else if (OpTy == MVT::v8f16 && HasFullFP16)
4843     NewTy = MVT::v8i16;
4844   else
4845     llvm_unreachable("Invalid type for custom lowering!");
4846 
4847   if (VT != MVT::v4i16 && VT != MVT::v8i16)
4848     return DAG.UnrollVectorOp(Op.getNode());
4849 
4850   Op = DAG.getNode(Op.getOpcode(), dl, NewTy, Op.getOperand(0));
4851   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4852 }
4853 
4854 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4855   EVT VT = Op.getValueType();
4856   if (VT.isVector())
4857     return LowerVectorFP_TO_INT(Op, DAG);
4858   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4859     RTLIB::Libcall LC;
4860     if (Op.getOpcode() == ISD::FP_TO_SINT)
4861       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4862                               Op.getValueType());
4863     else
4864       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4865                               Op.getValueType());
4866     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4867                        /*isSigned*/ false, SDLoc(Op)).first;
4868   }
4869 
4870   return Op;
4871 }
4872 
4873 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4874   EVT VT = Op.getValueType();
4875   SDLoc dl(Op);
4876 
4877   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4878     if (VT.getVectorElementType() == MVT::f32)
4879       return Op;
4880     return DAG.UnrollVectorOp(Op.getNode());
4881   }
4882 
4883   assert((Op.getOperand(0).getValueType() == MVT::v4i16 ||
4884           Op.getOperand(0).getValueType() == MVT::v8i16) &&
4885          "Invalid type for custom lowering!");
4886 
4887   const bool HasFullFP16 =
4888     static_cast<const ARMSubtarget&>(DAG.getSubtarget()).hasFullFP16();
4889 
4890   EVT DestVecType;
4891   if (VT == MVT::v4f32)
4892     DestVecType = MVT::v4i32;
4893   else if (VT == MVT::v4f16 && HasFullFP16)
4894     DestVecType = MVT::v4i16;
4895   else if (VT == MVT::v8f16 && HasFullFP16)
4896     DestVecType = MVT::v8i16;
4897   else
4898     return DAG.UnrollVectorOp(Op.getNode());
4899 
4900   unsigned CastOpc;
4901   unsigned Opc;
4902   switch (Op.getOpcode()) {
4903   default: llvm_unreachable("Invalid opcode!");
4904   case ISD::SINT_TO_FP:
4905     CastOpc = ISD::SIGN_EXTEND;
4906     Opc = ISD::SINT_TO_FP;
4907     break;
4908   case ISD::UINT_TO_FP:
4909     CastOpc = ISD::ZERO_EXTEND;
4910     Opc = ISD::UINT_TO_FP;
4911     break;
4912   }
4913 
4914   Op = DAG.getNode(CastOpc, dl, DestVecType, Op.getOperand(0));
4915   return DAG.getNode(Opc, dl, VT, Op);
4916 }
4917 
4918 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4919   EVT VT = Op.getValueType();
4920   if (VT.isVector())
4921     return LowerVectorINT_TO_FP(Op, DAG);
4922   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4923     RTLIB::Libcall LC;
4924     if (Op.getOpcode() == ISD::SINT_TO_FP)
4925       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4926                               Op.getValueType());
4927     else
4928       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4929                               Op.getValueType());
4930     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4931                        /*isSigned*/ false, SDLoc(Op)).first;
4932   }
4933 
4934   return Op;
4935 }
4936 
4937 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4938   // Implement fcopysign with a fabs and a conditional fneg.
4939   SDValue Tmp0 = Op.getOperand(0);
4940   SDValue Tmp1 = Op.getOperand(1);
4941   SDLoc dl(Op);
4942   EVT VT = Op.getValueType();
4943   EVT SrcVT = Tmp1.getValueType();
4944   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4945     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4946   bool UseNEON = !InGPR && Subtarget->hasNEON();
4947 
4948   if (UseNEON) {
4949     // Use VBSL to copy the sign bit.
4950     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4951     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4952                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4953     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4954     if (VT == MVT::f64)
4955       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4956                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4957                          DAG.getConstant(32, dl, MVT::i32));
4958     else /*if (VT == MVT::f32)*/
4959       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4960     if (SrcVT == MVT::f32) {
4961       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4962       if (VT == MVT::f64)
4963         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4964                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4965                            DAG.getConstant(32, dl, MVT::i32));
4966     } else if (VT == MVT::f32)
4967       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4968                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4969                          DAG.getConstant(32, dl, MVT::i32));
4970     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4971     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4972 
4973     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4974                                             dl, MVT::i32);
4975     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4976     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4977                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4978 
4979     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4980                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4981                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4982     if (VT == MVT::f32) {
4983       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4984       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4985                         DAG.getConstant(0, dl, MVT::i32));
4986     } else {
4987       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4988     }
4989 
4990     return Res;
4991   }
4992 
4993   // Bitcast operand 1 to i32.
4994   if (SrcVT == MVT::f64)
4995     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4996                        Tmp1).getValue(1);
4997   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4998 
4999   // Or in the signbit with integer operations.
5000   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
5001   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
5002   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
5003   if (VT == MVT::f32) {
5004     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
5005                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
5006     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
5007                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
5008   }
5009 
5010   // f64: Or the high part with signbit and then combine two parts.
5011   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
5012                      Tmp0);
5013   SDValue Lo = Tmp0.getValue(0);
5014   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
5015   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
5016   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
5017 }
5018 
5019 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
5020   MachineFunction &MF = DAG.getMachineFunction();
5021   MachineFrameInfo &MFI = MF.getFrameInfo();
5022   MFI.setReturnAddressIsTaken(true);
5023 
5024   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
5025     return SDValue();
5026 
5027   EVT VT = Op.getValueType();
5028   SDLoc dl(Op);
5029   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5030   if (Depth) {
5031     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5032     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5033     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5034                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5035                        MachinePointerInfo());
5036   }
5037 
5038   // Return LR, which contains the return address. Mark it an implicit live-in.
5039   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5040   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5041 }
5042 
5043 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5044   const ARMBaseRegisterInfo &ARI =
5045     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5046   MachineFunction &MF = DAG.getMachineFunction();
5047   MachineFrameInfo &MFI = MF.getFrameInfo();
5048   MFI.setFrameAddressIsTaken(true);
5049 
5050   EVT VT = Op.getValueType();
5051   SDLoc dl(Op);  // FIXME probably not meaningful
5052   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5053   unsigned FrameReg = ARI.getFrameRegister(MF);
5054   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5055   while (Depth--)
5056     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5057                             MachinePointerInfo());
5058   return FrameAddr;
5059 }
5060 
5061 // FIXME? Maybe this could be a TableGen attribute on some registers and
5062 // this table could be generated automatically from RegInfo.
5063 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5064                                               SelectionDAG &DAG) const {
5065   unsigned Reg = StringSwitch<unsigned>(RegName)
5066                        .Case("sp", ARM::SP)
5067                        .Default(0);
5068   if (Reg)
5069     return Reg;
5070   report_fatal_error(Twine("Invalid register name \""
5071                               + StringRef(RegName)  + "\"."));
5072 }
5073 
5074 // Result is 64 bit value so split into two 32 bit values and return as a
5075 // pair of values.
5076 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5077                                 SelectionDAG &DAG) {
5078   SDLoc DL(N);
5079 
5080   // This function is only supposed to be called for i64 type destination.
5081   assert(N->getValueType(0) == MVT::i64
5082           && "ExpandREAD_REGISTER called for non-i64 type result.");
5083 
5084   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5085                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5086                              N->getOperand(0),
5087                              N->getOperand(1));
5088 
5089   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5090                     Read.getValue(1)));
5091   Results.push_back(Read.getOperand(0));
5092 }
5093 
5094 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5095 /// When \p DstVT, the destination type of \p BC, is on the vector
5096 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5097 /// it might be possible to combine them, such that everything stays on the
5098 /// vector register bank.
5099 /// \p return The node that would replace \p BT, if the combine
5100 /// is possible.
5101 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5102                                                 SelectionDAG &DAG) {
5103   SDValue Op = BC->getOperand(0);
5104   EVT DstVT = BC->getValueType(0);
5105 
5106   // The only vector instruction that can produce a scalar (remember,
5107   // since the bitcast was about to be turned into VMOVDRR, the source
5108   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5109   // Moreover, we can do this combine only if there is one use.
5110   // Finally, if the destination type is not a vector, there is not
5111   // much point on forcing everything on the vector bank.
5112   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5113       !Op.hasOneUse())
5114     return SDValue();
5115 
5116   // If the index is not constant, we will introduce an additional
5117   // multiply that will stick.
5118   // Give up in that case.
5119   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5120   if (!Index)
5121     return SDValue();
5122   unsigned DstNumElt = DstVT.getVectorNumElements();
5123 
5124   // Compute the new index.
5125   const APInt &APIntIndex = Index->getAPIntValue();
5126   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5127   NewIndex *= APIntIndex;
5128   // Check if the new constant index fits into i32.
5129   if (NewIndex.getBitWidth() > 32)
5130     return SDValue();
5131 
5132   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5133   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5134   SDLoc dl(Op);
5135   SDValue ExtractSrc = Op.getOperand(0);
5136   EVT VecVT = EVT::getVectorVT(
5137       *DAG.getContext(), DstVT.getScalarType(),
5138       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5139   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5140   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5141                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5142 }
5143 
5144 /// ExpandBITCAST - If the target supports VFP, this function is called to
5145 /// expand a bit convert where either the source or destination type is i64 to
5146 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5147 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5148 /// vectors), since the legalizer won't know what to do with that.
5149 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5150                              const ARMSubtarget *Subtarget) {
5151   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5152   SDLoc dl(N);
5153   SDValue Op = N->getOperand(0);
5154 
5155   // This function is only supposed to be called for i64 types, either as the
5156   // source or destination of the bit convert.
5157   EVT SrcVT = Op.getValueType();
5158   EVT DstVT = N->getValueType(0);
5159   const bool HasFullFP16 = Subtarget->hasFullFP16();
5160 
5161   if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5162      // FullFP16: half values are passed in S-registers, and we don't
5163      // need any of the bitcast and moves:
5164      //
5165      // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5166      //   t5: i32 = bitcast t2
5167      // t18: f16 = ARMISD::VMOVhr t5
5168      if (Op.getOpcode() != ISD::CopyFromReg ||
5169          Op.getValueType() != MVT::f32)
5170        return SDValue();
5171 
5172      auto Move = N->use_begin();
5173      if (Move->getOpcode() != ARMISD::VMOVhr)
5174        return SDValue();
5175 
5176      SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5177      SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5178      DAG.ReplaceAllUsesWith(*Move, &Copy);
5179      return Copy;
5180   }
5181 
5182   if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5183     if (!HasFullFP16)
5184       return SDValue();
5185     // SoftFP: read half-precision arguments:
5186     //
5187     // t2: i32,ch = ...
5188     //        t7: i16 = truncate t2 <~~~~ Op
5189     //      t8: f16 = bitcast t7    <~~~~ N
5190     //
5191     if (Op.getOperand(0).getValueType() == MVT::i32)
5192       return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5193                          MVT::f16, Op.getOperand(0));
5194 
5195     return SDValue();
5196   }
5197 
5198   // Half-precision return values
5199   if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5200     if (!HasFullFP16)
5201       return SDValue();
5202     //
5203     //          t11: f16 = fadd t8, t10
5204     //        t12: i16 = bitcast t11       <~~~ SDNode N
5205     //      t13: i32 = zero_extend t12
5206     //    t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5207     //  t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5208     //
5209     // transform this into:
5210     //
5211     //    t20: i32 = ARMISD::VMOVrh t11
5212     //  t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5213     //
5214     auto ZeroExtend = N->use_begin();
5215     if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5216         ZeroExtend->getValueType(0) != MVT::i32)
5217       return SDValue();
5218 
5219     auto Copy = ZeroExtend->use_begin();
5220     if (Copy->getOpcode() == ISD::CopyToReg &&
5221         Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5222       SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5223       DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5224       return Cvt;
5225     }
5226     return SDValue();
5227   }
5228 
5229   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5230     return SDValue();
5231 
5232   // Turn i64->f64 into VMOVDRR.
5233   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5234     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5235     // if we can combine the bitcast with its source.
5236     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5237       return Val;
5238 
5239     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5240                              DAG.getConstant(0, dl, MVT::i32));
5241     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5242                              DAG.getConstant(1, dl, MVT::i32));
5243     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5244                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5245   }
5246 
5247   // Turn f64->i64 into VMOVRRD.
5248   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5249     SDValue Cvt;
5250     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5251         SrcVT.getVectorNumElements() > 1)
5252       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5253                         DAG.getVTList(MVT::i32, MVT::i32),
5254                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5255     else
5256       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5257                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5258     // Merge the pieces into a single i64 value.
5259     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5260   }
5261 
5262   return SDValue();
5263 }
5264 
5265 /// getZeroVector - Returns a vector of specified type with all zero elements.
5266 /// Zero vectors are used to represent vector negation and in those cases
5267 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
5268 /// not support i64 elements, so sometimes the zero vectors will need to be
5269 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
5270 /// zero vector.
5271 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5272   assert(VT.isVector() && "Expected a vector type");
5273   // The canonical modified immediate encoding of a zero vector is....0!
5274   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5275   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5276   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5277   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5278 }
5279 
5280 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5281 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5282 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5283                                                 SelectionDAG &DAG) const {
5284   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5285   EVT VT = Op.getValueType();
5286   unsigned VTBits = VT.getSizeInBits();
5287   SDLoc dl(Op);
5288   SDValue ShOpLo = Op.getOperand(0);
5289   SDValue ShOpHi = Op.getOperand(1);
5290   SDValue ShAmt  = Op.getOperand(2);
5291   SDValue ARMcc;
5292   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5293   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5294 
5295   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5296 
5297   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5298                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5299   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5300   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5301                                    DAG.getConstant(VTBits, dl, MVT::i32));
5302   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5303   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5304   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5305   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5306                             ISD::SETGE, ARMcc, DAG, dl);
5307   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5308                            ARMcc, CCR, CmpLo);
5309 
5310   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5311   SDValue HiBigShift = Opc == ISD::SRA
5312                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5313                                          DAG.getConstant(VTBits - 1, dl, VT))
5314                            : DAG.getConstant(0, dl, VT);
5315   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5316                             ISD::SETGE, ARMcc, DAG, dl);
5317   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5318                            ARMcc, CCR, CmpHi);
5319 
5320   SDValue Ops[2] = { Lo, Hi };
5321   return DAG.getMergeValues(Ops, dl);
5322 }
5323 
5324 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5325 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5326 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5327                                                SelectionDAG &DAG) const {
5328   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5329   EVT VT = Op.getValueType();
5330   unsigned VTBits = VT.getSizeInBits();
5331   SDLoc dl(Op);
5332   SDValue ShOpLo = Op.getOperand(0);
5333   SDValue ShOpHi = Op.getOperand(1);
5334   SDValue ShAmt  = Op.getOperand(2);
5335   SDValue ARMcc;
5336   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5337 
5338   assert(Op.getOpcode() == ISD::SHL_PARTS);
5339   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5340                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5341   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5342   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5343   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5344 
5345   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5346                                    DAG.getConstant(VTBits, dl, MVT::i32));
5347   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5348   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5349                             ISD::SETGE, ARMcc, DAG, dl);
5350   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5351                            ARMcc, CCR, CmpHi);
5352 
5353   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5354                           ISD::SETGE, ARMcc, DAG, dl);
5355   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5356   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5357                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5358 
5359   SDValue Ops[2] = { Lo, Hi };
5360   return DAG.getMergeValues(Ops, dl);
5361 }
5362 
5363 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5364                                             SelectionDAG &DAG) const {
5365   // The rounding mode is in bits 23:22 of the FPSCR.
5366   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5367   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5368   // so that the shift + and get folded into a bitfield extract.
5369   SDLoc dl(Op);
5370   SDValue Ops[] = { DAG.getEntryNode(),
5371                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5372 
5373   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5374   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5375                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5376   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5377                               DAG.getConstant(22, dl, MVT::i32));
5378   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5379                      DAG.getConstant(3, dl, MVT::i32));
5380 }
5381 
5382 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5383                          const ARMSubtarget *ST) {
5384   SDLoc dl(N);
5385   EVT VT = N->getValueType(0);
5386   if (VT.isVector()) {
5387     assert(ST->hasNEON());
5388 
5389     // Compute the least significant set bit: LSB = X & -X
5390     SDValue X = N->getOperand(0);
5391     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5392     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5393 
5394     EVT ElemTy = VT.getVectorElementType();
5395 
5396     if (ElemTy == MVT::i8) {
5397       // Compute with: cttz(x) = ctpop(lsb - 1)
5398       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5399                                 DAG.getTargetConstant(1, dl, ElemTy));
5400       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5401       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5402     }
5403 
5404     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5405         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5406       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5407       unsigned NumBits = ElemTy.getSizeInBits();
5408       SDValue WidthMinus1 =
5409           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5410                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5411       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5412       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5413     }
5414 
5415     // Compute with: cttz(x) = ctpop(lsb - 1)
5416 
5417     // Compute LSB - 1.
5418     SDValue Bits;
5419     if (ElemTy == MVT::i64) {
5420       // Load constant 0xffff'ffff'ffff'ffff to register.
5421       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5422                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5423       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5424     } else {
5425       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5426                                 DAG.getTargetConstant(1, dl, ElemTy));
5427       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5428     }
5429     return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5430   }
5431 
5432   if (!ST->hasV6T2Ops())
5433     return SDValue();
5434 
5435   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5436   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5437 }
5438 
5439 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5440                           const ARMSubtarget *ST) {
5441   EVT VT = N->getValueType(0);
5442   SDLoc DL(N);
5443 
5444   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5445   assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
5446           VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
5447          "Unexpected type for custom ctpop lowering");
5448 
5449   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5450   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5451   SDValue Res = DAG.getBitcast(VT8Bit, N->getOperand(0));
5452   Res = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Res);
5453 
5454   // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
5455   unsigned EltSize = 8;
5456   unsigned NumElts = VT.is64BitVector() ? 8 : 16;
5457   while (EltSize != VT.getScalarSizeInBits()) {
5458     SmallVector<SDValue, 8> Ops;
5459     Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddlu, DL,
5460                                   TLI.getPointerTy(DAG.getDataLayout())));
5461     Ops.push_back(Res);
5462 
5463     EltSize *= 2;
5464     NumElts /= 2;
5465     MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
5466     Res = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, WidenVT, Ops);
5467   }
5468 
5469   return Res;
5470 }
5471 
5472 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5473                           const ARMSubtarget *ST) {
5474   EVT VT = N->getValueType(0);
5475   SDLoc dl(N);
5476 
5477   if (!VT.isVector())
5478     return SDValue();
5479 
5480   // Lower vector shifts on NEON to use VSHL.
5481   assert(ST->hasNEON() && "unexpected vector shift");
5482 
5483   // Left shifts translate directly to the vshiftu intrinsic.
5484   if (N->getOpcode() == ISD::SHL)
5485     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5486                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5487                                        MVT::i32),
5488                        N->getOperand(0), N->getOperand(1));
5489 
5490   assert((N->getOpcode() == ISD::SRA ||
5491           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5492 
5493   // NEON uses the same intrinsics for both left and right shifts.  For
5494   // right shifts, the shift amounts are negative, so negate the vector of
5495   // shift amounts.
5496   EVT ShiftVT = N->getOperand(1).getValueType();
5497   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5498                                      getZeroVector(ShiftVT, DAG, dl),
5499                                      N->getOperand(1));
5500   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5501                              Intrinsic::arm_neon_vshifts :
5502                              Intrinsic::arm_neon_vshiftu);
5503   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5504                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5505                      N->getOperand(0), NegatedCount);
5506 }
5507 
5508 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5509                                 const ARMSubtarget *ST) {
5510   EVT VT = N->getValueType(0);
5511   SDLoc dl(N);
5512 
5513   // We can get here for a node like i32 = ISD::SHL i32, i64
5514   if (VT != MVT::i64)
5515     return SDValue();
5516 
5517   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5518          "Unknown shift to lower!");
5519 
5520   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5521   if (!isOneConstant(N->getOperand(1)))
5522     return SDValue();
5523 
5524   // If we are in thumb mode, we don't have RRX.
5525   if (ST->isThumb1Only()) return SDValue();
5526 
5527   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5528   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5529                            DAG.getConstant(0, dl, MVT::i32));
5530   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5531                            DAG.getConstant(1, dl, MVT::i32));
5532 
5533   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5534   // captures the result into a carry flag.
5535   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5536   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5537 
5538   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5539   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5540 
5541   // Merge the pieces into a single i64 value.
5542  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5543 }
5544 
5545 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5546   SDValue TmpOp0, TmpOp1;
5547   bool Invert = false;
5548   bool Swap = false;
5549   unsigned Opc = 0;
5550 
5551   SDValue Op0 = Op.getOperand(0);
5552   SDValue Op1 = Op.getOperand(1);
5553   SDValue CC = Op.getOperand(2);
5554   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5555   EVT VT = Op.getValueType();
5556   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5557   SDLoc dl(Op);
5558 
5559   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5560       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5561     // Special-case integer 64-bit equality comparisons. They aren't legal,
5562     // but they can be lowered with a few vector instructions.
5563     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5564     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5565     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5566     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5567     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5568                               DAG.getCondCode(ISD::SETEQ));
5569     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5570     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5571     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5572     if (SetCCOpcode == ISD::SETNE)
5573       Merged = DAG.getNOT(dl, Merged, CmpVT);
5574     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5575     return Merged;
5576   }
5577 
5578   if (CmpVT.getVectorElementType() == MVT::i64)
5579     // 64-bit comparisons are not legal in general.
5580     return SDValue();
5581 
5582   if (Op1.getValueType().isFloatingPoint()) {
5583     switch (SetCCOpcode) {
5584     default: llvm_unreachable("Illegal FP comparison");
5585     case ISD::SETUNE:
5586     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5587     case ISD::SETOEQ:
5588     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5589     case ISD::SETOLT:
5590     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5591     case ISD::SETOGT:
5592     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5593     case ISD::SETOLE:
5594     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5595     case ISD::SETOGE:
5596     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5597     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5598     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5599     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5600     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5601     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5602     case ISD::SETONE:
5603       // Expand this to (OLT | OGT).
5604       TmpOp0 = Op0;
5605       TmpOp1 = Op1;
5606       Opc = ISD::OR;
5607       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5608       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5609       break;
5610     case ISD::SETUO:
5611       Invert = true;
5612       LLVM_FALLTHROUGH;
5613     case ISD::SETO:
5614       // Expand this to (OLT | OGE).
5615       TmpOp0 = Op0;
5616       TmpOp1 = Op1;
5617       Opc = ISD::OR;
5618       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5619       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5620       break;
5621     }
5622   } else {
5623     // Integer comparisons.
5624     switch (SetCCOpcode) {
5625     default: llvm_unreachable("Illegal integer comparison");
5626     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5627     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5628     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
5629     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5630     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5631     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5632     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5633     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5634     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5635     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5636     }
5637 
5638     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5639     if (Opc == ARMISD::VCEQ) {
5640       SDValue AndOp;
5641       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5642         AndOp = Op0;
5643       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5644         AndOp = Op1;
5645 
5646       // Ignore bitconvert.
5647       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5648         AndOp = AndOp.getOperand(0);
5649 
5650       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5651         Opc = ARMISD::VTST;
5652         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5653         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5654         Invert = !Invert;
5655       }
5656     }
5657   }
5658 
5659   if (Swap)
5660     std::swap(Op0, Op1);
5661 
5662   // If one of the operands is a constant vector zero, attempt to fold the
5663   // comparison to a specialized compare-against-zero form.
5664   SDValue SingleOp;
5665   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5666     SingleOp = Op0;
5667   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5668     if (Opc == ARMISD::VCGE)
5669       Opc = ARMISD::VCLEZ;
5670     else if (Opc == ARMISD::VCGT)
5671       Opc = ARMISD::VCLTZ;
5672     SingleOp = Op1;
5673   }
5674 
5675   SDValue Result;
5676   if (SingleOp.getNode()) {
5677     switch (Opc) {
5678     case ARMISD::VCEQ:
5679       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5680     case ARMISD::VCGE:
5681       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5682     case ARMISD::VCLEZ:
5683       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5684     case ARMISD::VCGT:
5685       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5686     case ARMISD::VCLTZ:
5687       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5688     default:
5689       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5690     }
5691   } else {
5692      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5693   }
5694 
5695   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5696 
5697   if (Invert)
5698     Result = DAG.getNOT(dl, Result, VT);
5699 
5700   return Result;
5701 }
5702 
5703 static SDValue LowerSETCCCARRY(SDValue Op, SelectionDAG &DAG) {
5704   SDValue LHS = Op.getOperand(0);
5705   SDValue RHS = Op.getOperand(1);
5706   SDValue Carry = Op.getOperand(2);
5707   SDValue Cond = Op.getOperand(3);
5708   SDLoc DL(Op);
5709 
5710   assert(LHS.getSimpleValueType().isInteger() && "SETCCCARRY is integer only.");
5711 
5712   // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
5713   // have to invert the carry first.
5714   Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
5715                       DAG.getConstant(1, DL, MVT::i32), Carry);
5716   // This converts the boolean value carry into the carry flag.
5717   Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
5718 
5719   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5720   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5721 
5722   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5723   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5724   SDValue ARMcc = DAG.getConstant(
5725       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5726   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5727   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5728                                    Cmp.getValue(1), SDValue());
5729   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5730                      CCR, Chain.getValue(1));
5731 }
5732 
5733 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5734 /// valid vector constant for a NEON instruction with a "modified immediate"
5735 /// operand (e.g., VMOV).  If so, return the encoded value.
5736 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5737                                  unsigned SplatBitSize, SelectionDAG &DAG,
5738                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5739                                  NEONModImmType type) {
5740   unsigned OpCmode, Imm;
5741 
5742   // SplatBitSize is set to the smallest size that splats the vector, so a
5743   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5744   // immediate instructions others than VMOV do not support the 8-bit encoding
5745   // of a zero vector, and the default encoding of zero is supposed to be the
5746   // 32-bit version.
5747   if (SplatBits == 0)
5748     SplatBitSize = 32;
5749 
5750   switch (SplatBitSize) {
5751   case 8:
5752     if (type != VMOVModImm)
5753       return SDValue();
5754     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5755     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5756     OpCmode = 0xe;
5757     Imm = SplatBits;
5758     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5759     break;
5760 
5761   case 16:
5762     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5763     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5764     if ((SplatBits & ~0xff) == 0) {
5765       // Value = 0x00nn: Op=x, Cmode=100x.
5766       OpCmode = 0x8;
5767       Imm = SplatBits;
5768       break;
5769     }
5770     if ((SplatBits & ~0xff00) == 0) {
5771       // Value = 0xnn00: Op=x, Cmode=101x.
5772       OpCmode = 0xa;
5773       Imm = SplatBits >> 8;
5774       break;
5775     }
5776     return SDValue();
5777 
5778   case 32:
5779     // NEON's 32-bit VMOV supports splat values where:
5780     // * only one byte is nonzero, or
5781     // * the least significant byte is 0xff and the second byte is nonzero, or
5782     // * the least significant 2 bytes are 0xff and the third is nonzero.
5783     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5784     if ((SplatBits & ~0xff) == 0) {
5785       // Value = 0x000000nn: Op=x, Cmode=000x.
5786       OpCmode = 0;
5787       Imm = SplatBits;
5788       break;
5789     }
5790     if ((SplatBits & ~0xff00) == 0) {
5791       // Value = 0x0000nn00: Op=x, Cmode=001x.
5792       OpCmode = 0x2;
5793       Imm = SplatBits >> 8;
5794       break;
5795     }
5796     if ((SplatBits & ~0xff0000) == 0) {
5797       // Value = 0x00nn0000: Op=x, Cmode=010x.
5798       OpCmode = 0x4;
5799       Imm = SplatBits >> 16;
5800       break;
5801     }
5802     if ((SplatBits & ~0xff000000) == 0) {
5803       // Value = 0xnn000000: Op=x, Cmode=011x.
5804       OpCmode = 0x6;
5805       Imm = SplatBits >> 24;
5806       break;
5807     }
5808 
5809     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5810     if (type == OtherModImm) return SDValue();
5811 
5812     if ((SplatBits & ~0xffff) == 0 &&
5813         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5814       // Value = 0x0000nnff: Op=x, Cmode=1100.
5815       OpCmode = 0xc;
5816       Imm = SplatBits >> 8;
5817       break;
5818     }
5819 
5820     if ((SplatBits & ~0xffffff) == 0 &&
5821         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5822       // Value = 0x00nnffff: Op=x, Cmode=1101.
5823       OpCmode = 0xd;
5824       Imm = SplatBits >> 16;
5825       break;
5826     }
5827 
5828     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5829     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5830     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5831     // and fall through here to test for a valid 64-bit splat.  But, then the
5832     // caller would also need to check and handle the change in size.
5833     return SDValue();
5834 
5835   case 64: {
5836     if (type != VMOVModImm)
5837       return SDValue();
5838     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5839     uint64_t BitMask = 0xff;
5840     uint64_t Val = 0;
5841     unsigned ImmMask = 1;
5842     Imm = 0;
5843     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5844       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5845         Val |= BitMask;
5846         Imm |= ImmMask;
5847       } else if ((SplatBits & BitMask) != 0) {
5848         return SDValue();
5849       }
5850       BitMask <<= 8;
5851       ImmMask <<= 1;
5852     }
5853 
5854     if (DAG.getDataLayout().isBigEndian())
5855       // swap higher and lower 32 bit word
5856       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5857 
5858     // Op=1, Cmode=1110.
5859     OpCmode = 0x1e;
5860     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5861     break;
5862   }
5863 
5864   default:
5865     llvm_unreachable("unexpected size for isNEONModifiedImm");
5866   }
5867 
5868   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5869   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5870 }
5871 
5872 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5873                                            const ARMSubtarget *ST) const {
5874   EVT VT = Op.getValueType();
5875   bool IsDouble = (VT == MVT::f64);
5876   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5877   const APFloat &FPVal = CFP->getValueAPF();
5878 
5879   // Prevent floating-point constants from using literal loads
5880   // when execute-only is enabled.
5881   if (ST->genExecuteOnly()) {
5882     // If we can represent the constant as an immediate, don't lower it
5883     if (isFPImmLegal(FPVal, VT))
5884       return Op;
5885     // Otherwise, construct as integer, and move to float register
5886     APInt INTVal = FPVal.bitcastToAPInt();
5887     SDLoc DL(CFP);
5888     switch (VT.getSimpleVT().SimpleTy) {
5889       default:
5890         llvm_unreachable("Unknown floating point type!");
5891         break;
5892       case MVT::f64: {
5893         SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5894         SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5895         if (!ST->isLittle())
5896           std::swap(Lo, Hi);
5897         return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5898       }
5899       case MVT::f32:
5900           return DAG.getNode(ARMISD::VMOVSR, DL, VT,
5901               DAG.getConstant(INTVal, DL, MVT::i32));
5902     }
5903   }
5904 
5905   if (!ST->hasVFP3())
5906     return SDValue();
5907 
5908   // Use the default (constant pool) lowering for double constants when we have
5909   // an SP-only FPU
5910   if (IsDouble && Subtarget->isFPOnlySP())
5911     return SDValue();
5912 
5913   // Try splatting with a VMOV.f32...
5914   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5915 
5916   if (ImmVal != -1) {
5917     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5918       // We have code in place to select a valid ConstantFP already, no need to
5919       // do any mangling.
5920       return Op;
5921     }
5922 
5923     // It's a float and we are trying to use NEON operations where
5924     // possible. Lower it to a splat followed by an extract.
5925     SDLoc DL(Op);
5926     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5927     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5928                                       NewVal);
5929     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5930                        DAG.getConstant(0, DL, MVT::i32));
5931   }
5932 
5933   // The rest of our options are NEON only, make sure that's allowed before
5934   // proceeding..
5935   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5936     return SDValue();
5937 
5938   EVT VMovVT;
5939   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5940 
5941   // It wouldn't really be worth bothering for doubles except for one very
5942   // important value, which does happen to match: 0.0. So make sure we don't do
5943   // anything stupid.
5944   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5945     return SDValue();
5946 
5947   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5948   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5949                                      VMovVT, false, VMOVModImm);
5950   if (NewVal != SDValue()) {
5951     SDLoc DL(Op);
5952     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5953                                       NewVal);
5954     if (IsDouble)
5955       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5956 
5957     // It's a float: cast and extract a vector element.
5958     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5959                                        VecConstant);
5960     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5961                        DAG.getConstant(0, DL, MVT::i32));
5962   }
5963 
5964   // Finally, try a VMVN.i32
5965   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5966                              false, VMVNModImm);
5967   if (NewVal != SDValue()) {
5968     SDLoc DL(Op);
5969     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5970 
5971     if (IsDouble)
5972       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5973 
5974     // It's a float: cast and extract a vector element.
5975     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5976                                        VecConstant);
5977     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5978                        DAG.getConstant(0, DL, MVT::i32));
5979   }
5980 
5981   return SDValue();
5982 }
5983 
5984 // check if an VEXT instruction can handle the shuffle mask when the
5985 // vector sources of the shuffle are the same.
5986 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5987   unsigned NumElts = VT.getVectorNumElements();
5988 
5989   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5990   if (M[0] < 0)
5991     return false;
5992 
5993   Imm = M[0];
5994 
5995   // If this is a VEXT shuffle, the immediate value is the index of the first
5996   // element.  The other shuffle indices must be the successive elements after
5997   // the first one.
5998   unsigned ExpectedElt = Imm;
5999   for (unsigned i = 1; i < NumElts; ++i) {
6000     // Increment the expected index.  If it wraps around, just follow it
6001     // back to index zero and keep going.
6002     ++ExpectedElt;
6003     if (ExpectedElt == NumElts)
6004       ExpectedElt = 0;
6005 
6006     if (M[i] < 0) continue; // ignore UNDEF indices
6007     if (ExpectedElt != static_cast<unsigned>(M[i]))
6008       return false;
6009   }
6010 
6011   return true;
6012 }
6013 
6014 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6015                        bool &ReverseVEXT, unsigned &Imm) {
6016   unsigned NumElts = VT.getVectorNumElements();
6017   ReverseVEXT = false;
6018 
6019   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6020   if (M[0] < 0)
6021     return false;
6022 
6023   Imm = M[0];
6024 
6025   // If this is a VEXT shuffle, the immediate value is the index of the first
6026   // element.  The other shuffle indices must be the successive elements after
6027   // the first one.
6028   unsigned ExpectedElt = Imm;
6029   for (unsigned i = 1; i < NumElts; ++i) {
6030     // Increment the expected index.  If it wraps around, it may still be
6031     // a VEXT but the source vectors must be swapped.
6032     ExpectedElt += 1;
6033     if (ExpectedElt == NumElts * 2) {
6034       ExpectedElt = 0;
6035       ReverseVEXT = true;
6036     }
6037 
6038     if (M[i] < 0) continue; // ignore UNDEF indices
6039     if (ExpectedElt != static_cast<unsigned>(M[i]))
6040       return false;
6041   }
6042 
6043   // Adjust the index value if the source operands will be swapped.
6044   if (ReverseVEXT)
6045     Imm -= NumElts;
6046 
6047   return true;
6048 }
6049 
6050 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6051 /// instruction with the specified blocksize.  (The order of the elements
6052 /// within each block of the vector is reversed.)
6053 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6054   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6055          "Only possible block sizes for VREV are: 16, 32, 64");
6056 
6057   unsigned EltSz = VT.getScalarSizeInBits();
6058   if (EltSz == 64)
6059     return false;
6060 
6061   unsigned NumElts = VT.getVectorNumElements();
6062   unsigned BlockElts = M[0] + 1;
6063   // If the first shuffle index is UNDEF, be optimistic.
6064   if (M[0] < 0)
6065     BlockElts = BlockSize / EltSz;
6066 
6067   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6068     return false;
6069 
6070   for (unsigned i = 0; i < NumElts; ++i) {
6071     if (M[i] < 0) continue; // ignore UNDEF indices
6072     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6073       return false;
6074   }
6075 
6076   return true;
6077 }
6078 
6079 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6080   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6081   // range, then 0 is placed into the resulting vector. So pretty much any mask
6082   // of 8 elements can work here.
6083   return VT == MVT::v8i8 && M.size() == 8;
6084 }
6085 
6086 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6087                                unsigned Index) {
6088   if (Mask.size() == Elements * 2)
6089     return Index / Elements;
6090   return Mask[Index] == 0 ? 0 : 1;
6091 }
6092 
6093 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6094 // checking that pairs of elements in the shuffle mask represent the same index
6095 // in each vector, incrementing the expected index by 2 at each step.
6096 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6097 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6098 //  v2={e,f,g,h}
6099 // WhichResult gives the offset for each element in the mask based on which
6100 // of the two results it belongs to.
6101 //
6102 // The transpose can be represented either as:
6103 // result1 = shufflevector v1, v2, result1_shuffle_mask
6104 // result2 = shufflevector v1, v2, result2_shuffle_mask
6105 // where v1/v2 and the shuffle masks have the same number of elements
6106 // (here WhichResult (see below) indicates which result is being checked)
6107 //
6108 // or as:
6109 // results = shufflevector v1, v2, shuffle_mask
6110 // where both results are returned in one vector and the shuffle mask has twice
6111 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6112 // want to check the low half and high half of the shuffle mask as if it were
6113 // the other case
6114 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6115   unsigned EltSz = VT.getScalarSizeInBits();
6116   if (EltSz == 64)
6117     return false;
6118 
6119   unsigned NumElts = VT.getVectorNumElements();
6120   if (M.size() != NumElts && M.size() != NumElts*2)
6121     return false;
6122 
6123   // If the mask is twice as long as the input vector then we need to check the
6124   // upper and lower parts of the mask with a matching value for WhichResult
6125   // FIXME: A mask with only even values will be rejected in case the first
6126   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6127   // M[0] is used to determine WhichResult
6128   for (unsigned i = 0; i < M.size(); i += NumElts) {
6129     WhichResult = SelectPairHalf(NumElts, M, i);
6130     for (unsigned j = 0; j < NumElts; j += 2) {
6131       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6132           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6133         return false;
6134     }
6135   }
6136 
6137   if (M.size() == NumElts*2)
6138     WhichResult = 0;
6139 
6140   return true;
6141 }
6142 
6143 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6144 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6145 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6146 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6147   unsigned EltSz = VT.getScalarSizeInBits();
6148   if (EltSz == 64)
6149     return false;
6150 
6151   unsigned NumElts = VT.getVectorNumElements();
6152   if (M.size() != NumElts && M.size() != NumElts*2)
6153     return false;
6154 
6155   for (unsigned i = 0; i < M.size(); i += NumElts) {
6156     WhichResult = SelectPairHalf(NumElts, M, i);
6157     for (unsigned j = 0; j < NumElts; j += 2) {
6158       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6159           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6160         return false;
6161     }
6162   }
6163 
6164   if (M.size() == NumElts*2)
6165     WhichResult = 0;
6166 
6167   return true;
6168 }
6169 
6170 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6171 // that the mask elements are either all even and in steps of size 2 or all odd
6172 // and in steps of size 2.
6173 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6174 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6175 //  v2={e,f,g,h}
6176 // Requires similar checks to that of isVTRNMask with
6177 // respect the how results are returned.
6178 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6179   unsigned EltSz = VT.getScalarSizeInBits();
6180   if (EltSz == 64)
6181     return false;
6182 
6183   unsigned NumElts = VT.getVectorNumElements();
6184   if (M.size() != NumElts && M.size() != NumElts*2)
6185     return false;
6186 
6187   for (unsigned i = 0; i < M.size(); i += NumElts) {
6188     WhichResult = SelectPairHalf(NumElts, M, i);
6189     for (unsigned j = 0; j < NumElts; ++j) {
6190       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6191         return false;
6192     }
6193   }
6194 
6195   if (M.size() == NumElts*2)
6196     WhichResult = 0;
6197 
6198   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6199   if (VT.is64BitVector() && EltSz == 32)
6200     return false;
6201 
6202   return true;
6203 }
6204 
6205 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6206 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6207 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6208 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6209   unsigned EltSz = VT.getScalarSizeInBits();
6210   if (EltSz == 64)
6211     return false;
6212 
6213   unsigned NumElts = VT.getVectorNumElements();
6214   if (M.size() != NumElts && M.size() != NumElts*2)
6215     return false;
6216 
6217   unsigned Half = NumElts / 2;
6218   for (unsigned i = 0; i < M.size(); i += NumElts) {
6219     WhichResult = SelectPairHalf(NumElts, M, i);
6220     for (unsigned j = 0; j < NumElts; j += Half) {
6221       unsigned Idx = WhichResult;
6222       for (unsigned k = 0; k < Half; ++k) {
6223         int MIdx = M[i + j + k];
6224         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6225           return false;
6226         Idx += 2;
6227       }
6228     }
6229   }
6230 
6231   if (M.size() == NumElts*2)
6232     WhichResult = 0;
6233 
6234   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6235   if (VT.is64BitVector() && EltSz == 32)
6236     return false;
6237 
6238   return true;
6239 }
6240 
6241 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6242 // that pairs of elements of the shufflemask represent the same index in each
6243 // vector incrementing sequentially through the vectors.
6244 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6245 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6246 //  v2={e,f,g,h}
6247 // Requires similar checks to that of isVTRNMask with respect the how results
6248 // are returned.
6249 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6250   unsigned EltSz = VT.getScalarSizeInBits();
6251   if (EltSz == 64)
6252     return false;
6253 
6254   unsigned NumElts = VT.getVectorNumElements();
6255   if (M.size() != NumElts && M.size() != NumElts*2)
6256     return false;
6257 
6258   for (unsigned i = 0; i < M.size(); i += NumElts) {
6259     WhichResult = SelectPairHalf(NumElts, M, i);
6260     unsigned Idx = WhichResult * NumElts / 2;
6261     for (unsigned j = 0; j < NumElts; j += 2) {
6262       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6263           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6264         return false;
6265       Idx += 1;
6266     }
6267   }
6268 
6269   if (M.size() == NumElts*2)
6270     WhichResult = 0;
6271 
6272   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6273   if (VT.is64BitVector() && EltSz == 32)
6274     return false;
6275 
6276   return true;
6277 }
6278 
6279 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6280 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6281 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6282 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6283   unsigned EltSz = VT.getScalarSizeInBits();
6284   if (EltSz == 64)
6285     return false;
6286 
6287   unsigned NumElts = VT.getVectorNumElements();
6288   if (M.size() != NumElts && M.size() != NumElts*2)
6289     return false;
6290 
6291   for (unsigned i = 0; i < M.size(); i += NumElts) {
6292     WhichResult = SelectPairHalf(NumElts, M, i);
6293     unsigned Idx = WhichResult * NumElts / 2;
6294     for (unsigned j = 0; j < NumElts; j += 2) {
6295       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6296           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6297         return false;
6298       Idx += 1;
6299     }
6300   }
6301 
6302   if (M.size() == NumElts*2)
6303     WhichResult = 0;
6304 
6305   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6306   if (VT.is64BitVector() && EltSz == 32)
6307     return false;
6308 
6309   return true;
6310 }
6311 
6312 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6313 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6314 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6315                                            unsigned &WhichResult,
6316                                            bool &isV_UNDEF) {
6317   isV_UNDEF = false;
6318   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6319     return ARMISD::VTRN;
6320   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6321     return ARMISD::VUZP;
6322   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6323     return ARMISD::VZIP;
6324 
6325   isV_UNDEF = true;
6326   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6327     return ARMISD::VTRN;
6328   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6329     return ARMISD::VUZP;
6330   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6331     return ARMISD::VZIP;
6332 
6333   return 0;
6334 }
6335 
6336 /// \return true if this is a reverse operation on an vector.
6337 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6338   unsigned NumElts = VT.getVectorNumElements();
6339   // Make sure the mask has the right size.
6340   if (NumElts != M.size())
6341       return false;
6342 
6343   // Look for <15, ..., 3, -1, 1, 0>.
6344   for (unsigned i = 0; i != NumElts; ++i)
6345     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6346       return false;
6347 
6348   return true;
6349 }
6350 
6351 // If N is an integer constant that can be moved into a register in one
6352 // instruction, return an SDValue of such a constant (will become a MOV
6353 // instruction).  Otherwise return null.
6354 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6355                                      const ARMSubtarget *ST, const SDLoc &dl) {
6356   uint64_t Val;
6357   if (!isa<ConstantSDNode>(N))
6358     return SDValue();
6359   Val = cast<ConstantSDNode>(N)->getZExtValue();
6360 
6361   if (ST->isThumb1Only()) {
6362     if (Val <= 255 || ~Val <= 255)
6363       return DAG.getConstant(Val, dl, MVT::i32);
6364   } else {
6365     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6366       return DAG.getConstant(Val, dl, MVT::i32);
6367   }
6368   return SDValue();
6369 }
6370 
6371 // If this is a case we can't handle, return null and let the default
6372 // expansion code take care of it.
6373 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6374                                              const ARMSubtarget *ST) const {
6375   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6376   SDLoc dl(Op);
6377   EVT VT = Op.getValueType();
6378 
6379   APInt SplatBits, SplatUndef;
6380   unsigned SplatBitSize;
6381   bool HasAnyUndefs;
6382   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6383     if (SplatUndef.isAllOnesValue())
6384       return DAG.getUNDEF(VT);
6385 
6386     if (SplatBitSize <= 64) {
6387       // Check if an immediate VMOV works.
6388       EVT VmovVT;
6389       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6390                                       SplatUndef.getZExtValue(), SplatBitSize,
6391                                       DAG, dl, VmovVT, VT.is128BitVector(),
6392                                       VMOVModImm);
6393       if (Val.getNode()) {
6394         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6395         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6396       }
6397 
6398       // Try an immediate VMVN.
6399       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6400       Val = isNEONModifiedImm(NegatedImm,
6401                                       SplatUndef.getZExtValue(), SplatBitSize,
6402                                       DAG, dl, VmovVT, VT.is128BitVector(),
6403                                       VMVNModImm);
6404       if (Val.getNode()) {
6405         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6406         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6407       }
6408 
6409       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6410       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6411         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6412         if (ImmVal != -1) {
6413           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6414           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6415         }
6416       }
6417     }
6418   }
6419 
6420   // Scan through the operands to see if only one value is used.
6421   //
6422   // As an optimisation, even if more than one value is used it may be more
6423   // profitable to splat with one value then change some lanes.
6424   //
6425   // Heuristically we decide to do this if the vector has a "dominant" value,
6426   // defined as splatted to more than half of the lanes.
6427   unsigned NumElts = VT.getVectorNumElements();
6428   bool isOnlyLowElement = true;
6429   bool usesOnlyOneValue = true;
6430   bool hasDominantValue = false;
6431   bool isConstant = true;
6432 
6433   // Map of the number of times a particular SDValue appears in the
6434   // element list.
6435   DenseMap<SDValue, unsigned> ValueCounts;
6436   SDValue Value;
6437   for (unsigned i = 0; i < NumElts; ++i) {
6438     SDValue V = Op.getOperand(i);
6439     if (V.isUndef())
6440       continue;
6441     if (i > 0)
6442       isOnlyLowElement = false;
6443     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6444       isConstant = false;
6445 
6446     ValueCounts.insert(std::make_pair(V, 0));
6447     unsigned &Count = ValueCounts[V];
6448 
6449     // Is this value dominant? (takes up more than half of the lanes)
6450     if (++Count > (NumElts / 2)) {
6451       hasDominantValue = true;
6452       Value = V;
6453     }
6454   }
6455   if (ValueCounts.size() != 1)
6456     usesOnlyOneValue = false;
6457   if (!Value.getNode() && !ValueCounts.empty())
6458     Value = ValueCounts.begin()->first;
6459 
6460   if (ValueCounts.empty())
6461     return DAG.getUNDEF(VT);
6462 
6463   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6464   // Keep going if we are hitting this case.
6465   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6466     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6467 
6468   unsigned EltSize = VT.getScalarSizeInBits();
6469 
6470   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6471   // i32 and try again.
6472   if (hasDominantValue && EltSize <= 32) {
6473     if (!isConstant) {
6474       SDValue N;
6475 
6476       // If we are VDUPing a value that comes directly from a vector, that will
6477       // cause an unnecessary move to and from a GPR, where instead we could
6478       // just use VDUPLANE. We can only do this if the lane being extracted
6479       // is at a constant index, as the VDUP from lane instructions only have
6480       // constant-index forms.
6481       ConstantSDNode *constIndex;
6482       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6483           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6484         // We need to create a new undef vector to use for the VDUPLANE if the
6485         // size of the vector from which we get the value is different than the
6486         // size of the vector that we need to create. We will insert the element
6487         // such that the register coalescer will remove unnecessary copies.
6488         if (VT != Value->getOperand(0).getValueType()) {
6489           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6490                              VT.getVectorNumElements();
6491           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6492                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6493                         Value, DAG.getConstant(index, dl, MVT::i32)),
6494                            DAG.getConstant(index, dl, MVT::i32));
6495         } else
6496           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6497                         Value->getOperand(0), Value->getOperand(1));
6498       } else
6499         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6500 
6501       if (!usesOnlyOneValue) {
6502         // The dominant value was splatted as 'N', but we now have to insert
6503         // all differing elements.
6504         for (unsigned I = 0; I < NumElts; ++I) {
6505           if (Op.getOperand(I) == Value)
6506             continue;
6507           SmallVector<SDValue, 3> Ops;
6508           Ops.push_back(N);
6509           Ops.push_back(Op.getOperand(I));
6510           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6511           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6512         }
6513       }
6514       return N;
6515     }
6516     if (VT.getVectorElementType().isFloatingPoint()) {
6517       SmallVector<SDValue, 8> Ops;
6518       for (unsigned i = 0; i < NumElts; ++i)
6519         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6520                                   Op.getOperand(i)));
6521       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6522       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6523       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6524       if (Val.getNode())
6525         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6526     }
6527     if (usesOnlyOneValue) {
6528       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6529       if (isConstant && Val.getNode())
6530         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6531     }
6532   }
6533 
6534   // If all elements are constants and the case above didn't get hit, fall back
6535   // to the default expansion, which will generate a load from the constant
6536   // pool.
6537   if (isConstant)
6538     return SDValue();
6539 
6540   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6541   if (NumElts >= 4) {
6542     SDValue shuffle = ReconstructShuffle(Op, DAG);
6543     if (shuffle != SDValue())
6544       return shuffle;
6545   }
6546 
6547   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6548     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6549     // into two 64-bit vectors; we might discover a better way to lower it.
6550     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6551     EVT ExtVT = VT.getVectorElementType();
6552     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6553     SDValue Lower =
6554         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6555     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6556       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6557     SDValue Upper = DAG.getBuildVector(
6558         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6559     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6560       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6561     if (Lower && Upper)
6562       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6563   }
6564 
6565   // Vectors with 32- or 64-bit elements can be built by directly assigning
6566   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6567   // will be legalized.
6568   if (EltSize >= 32) {
6569     // Do the expansion with floating-point types, since that is what the VFP
6570     // registers are defined to use, and since i64 is not legal.
6571     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6572     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6573     SmallVector<SDValue, 8> Ops;
6574     for (unsigned i = 0; i < NumElts; ++i)
6575       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6576     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6577     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6578   }
6579 
6580   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6581   // know the default expansion would otherwise fall back on something even
6582   // worse. For a vector with one or two non-undef values, that's
6583   // scalar_to_vector for the elements followed by a shuffle (provided the
6584   // shuffle is valid for the target) and materialization element by element
6585   // on the stack followed by a load for everything else.
6586   if (!isConstant && !usesOnlyOneValue) {
6587     SDValue Vec = DAG.getUNDEF(VT);
6588     for (unsigned i = 0 ; i < NumElts; ++i) {
6589       SDValue V = Op.getOperand(i);
6590       if (V.isUndef())
6591         continue;
6592       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6593       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6594     }
6595     return Vec;
6596   }
6597 
6598   return SDValue();
6599 }
6600 
6601 // Gather data to see if the operation can be modelled as a
6602 // shuffle in combination with VEXTs.
6603 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6604                                               SelectionDAG &DAG) const {
6605   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6606   SDLoc dl(Op);
6607   EVT VT = Op.getValueType();
6608   unsigned NumElts = VT.getVectorNumElements();
6609 
6610   struct ShuffleSourceInfo {
6611     SDValue Vec;
6612     unsigned MinElt = std::numeric_limits<unsigned>::max();
6613     unsigned MaxElt = 0;
6614 
6615     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6616     // be compatible with the shuffle we intend to construct. As a result
6617     // ShuffleVec will be some sliding window into the original Vec.
6618     SDValue ShuffleVec;
6619 
6620     // Code should guarantee that element i in Vec starts at element "WindowBase
6621     // + i * WindowScale in ShuffleVec".
6622     int WindowBase = 0;
6623     int WindowScale = 1;
6624 
6625     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6626 
6627     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6628   };
6629 
6630   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6631   // node.
6632   SmallVector<ShuffleSourceInfo, 2> Sources;
6633   for (unsigned i = 0; i < NumElts; ++i) {
6634     SDValue V = Op.getOperand(i);
6635     if (V.isUndef())
6636       continue;
6637     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6638       // A shuffle can only come from building a vector from various
6639       // elements of other vectors.
6640       return SDValue();
6641     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6642       // Furthermore, shuffles require a constant mask, whereas extractelts
6643       // accept variable indices.
6644       return SDValue();
6645     }
6646 
6647     // Add this element source to the list if it's not already there.
6648     SDValue SourceVec = V.getOperand(0);
6649     auto Source = llvm::find(Sources, SourceVec);
6650     if (Source == Sources.end())
6651       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6652 
6653     // Update the minimum and maximum lane number seen.
6654     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6655     Source->MinElt = std::min(Source->MinElt, EltNo);
6656     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6657   }
6658 
6659   // Currently only do something sane when at most two source vectors
6660   // are involved.
6661   if (Sources.size() > 2)
6662     return SDValue();
6663 
6664   // Find out the smallest element size among result and two sources, and use
6665   // it as element size to build the shuffle_vector.
6666   EVT SmallestEltTy = VT.getVectorElementType();
6667   for (auto &Source : Sources) {
6668     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6669     if (SrcEltTy.bitsLT(SmallestEltTy))
6670       SmallestEltTy = SrcEltTy;
6671   }
6672   unsigned ResMultiplier =
6673       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6674   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6675   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6676 
6677   // If the source vector is too wide or too narrow, we may nevertheless be able
6678   // to construct a compatible shuffle either by concatenating it with UNDEF or
6679   // extracting a suitable range of elements.
6680   for (auto &Src : Sources) {
6681     EVT SrcVT = Src.ShuffleVec.getValueType();
6682 
6683     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6684       continue;
6685 
6686     // This stage of the search produces a source with the same element type as
6687     // the original, but with a total width matching the BUILD_VECTOR output.
6688     EVT EltVT = SrcVT.getVectorElementType();
6689     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6690     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6691 
6692     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6693       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6694         return SDValue();
6695       // We can pad out the smaller vector for free, so if it's part of a
6696       // shuffle...
6697       Src.ShuffleVec =
6698           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6699                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6700       continue;
6701     }
6702 
6703     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6704       return SDValue();
6705 
6706     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6707       // Span too large for a VEXT to cope
6708       return SDValue();
6709     }
6710 
6711     if (Src.MinElt >= NumSrcElts) {
6712       // The extraction can just take the second half
6713       Src.ShuffleVec =
6714           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6715                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6716       Src.WindowBase = -NumSrcElts;
6717     } else if (Src.MaxElt < NumSrcElts) {
6718       // The extraction can just take the first half
6719       Src.ShuffleVec =
6720           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6721                       DAG.getConstant(0, dl, MVT::i32));
6722     } else {
6723       // An actual VEXT is needed
6724       SDValue VEXTSrc1 =
6725           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6726                       DAG.getConstant(0, dl, MVT::i32));
6727       SDValue VEXTSrc2 =
6728           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6729                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6730 
6731       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6732                                    VEXTSrc2,
6733                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6734       Src.WindowBase = -Src.MinElt;
6735     }
6736   }
6737 
6738   // Another possible incompatibility occurs from the vector element types. We
6739   // can fix this by bitcasting the source vectors to the same type we intend
6740   // for the shuffle.
6741   for (auto &Src : Sources) {
6742     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6743     if (SrcEltTy == SmallestEltTy)
6744       continue;
6745     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6746     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6747     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6748     Src.WindowBase *= Src.WindowScale;
6749   }
6750 
6751   // Final sanity check before we try to actually produce a shuffle.
6752   LLVM_DEBUG(for (auto Src
6753                   : Sources)
6754                  assert(Src.ShuffleVec.getValueType() == ShuffleVT););
6755 
6756   // The stars all align, our next step is to produce the mask for the shuffle.
6757   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6758   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6759   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6760     SDValue Entry = Op.getOperand(i);
6761     if (Entry.isUndef())
6762       continue;
6763 
6764     auto Src = llvm::find(Sources, Entry.getOperand(0));
6765     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6766 
6767     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6768     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6769     // segment.
6770     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6771     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6772                                VT.getScalarSizeInBits());
6773     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6774 
6775     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6776     // starting at the appropriate offset.
6777     int *LaneMask = &Mask[i * ResMultiplier];
6778 
6779     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6780     ExtractBase += NumElts * (Src - Sources.begin());
6781     for (int j = 0; j < LanesDefined; ++j)
6782       LaneMask[j] = ExtractBase + j;
6783   }
6784 
6785   // Final check before we try to produce nonsense...
6786   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6787     return SDValue();
6788 
6789   // We can't handle more than two sources. This should have already
6790   // been checked before this point.
6791   assert(Sources.size() <= 2 && "Too many sources!");
6792 
6793   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6794   for (unsigned i = 0; i < Sources.size(); ++i)
6795     ShuffleOps[i] = Sources[i].ShuffleVec;
6796 
6797   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6798                                          ShuffleOps[1], Mask);
6799   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6800 }
6801 
6802 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6803 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6804 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6805 /// are assumed to be legal.
6806 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
6807   if (VT.getVectorNumElements() == 4 &&
6808       (VT.is128BitVector() || VT.is64BitVector())) {
6809     unsigned PFIndexes[4];
6810     for (unsigned i = 0; i != 4; ++i) {
6811       if (M[i] < 0)
6812         PFIndexes[i] = 8;
6813       else
6814         PFIndexes[i] = M[i];
6815     }
6816 
6817     // Compute the index in the perfect shuffle table.
6818     unsigned PFTableIndex =
6819       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6820     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6821     unsigned Cost = (PFEntry >> 30);
6822 
6823     if (Cost <= 4)
6824       return true;
6825   }
6826 
6827   bool ReverseVEXT, isV_UNDEF;
6828   unsigned Imm, WhichResult;
6829 
6830   unsigned EltSize = VT.getScalarSizeInBits();
6831   return (EltSize >= 32 ||
6832           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6833           isVREVMask(M, VT, 64) ||
6834           isVREVMask(M, VT, 32) ||
6835           isVREVMask(M, VT, 16) ||
6836           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6837           isVTBLMask(M, VT) ||
6838           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6839           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6840 }
6841 
6842 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6843 /// the specified operations to build the shuffle.
6844 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6845                                       SDValue RHS, SelectionDAG &DAG,
6846                                       const SDLoc &dl) {
6847   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6848   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6849   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6850 
6851   enum {
6852     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6853     OP_VREV,
6854     OP_VDUP0,
6855     OP_VDUP1,
6856     OP_VDUP2,
6857     OP_VDUP3,
6858     OP_VEXT1,
6859     OP_VEXT2,
6860     OP_VEXT3,
6861     OP_VUZPL, // VUZP, left result
6862     OP_VUZPR, // VUZP, right result
6863     OP_VZIPL, // VZIP, left result
6864     OP_VZIPR, // VZIP, right result
6865     OP_VTRNL, // VTRN, left result
6866     OP_VTRNR  // VTRN, right result
6867   };
6868 
6869   if (OpNum == OP_COPY) {
6870     if (LHSID == (1*9+2)*9+3) return LHS;
6871     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6872     return RHS;
6873   }
6874 
6875   SDValue OpLHS, OpRHS;
6876   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6877   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6878   EVT VT = OpLHS.getValueType();
6879 
6880   switch (OpNum) {
6881   default: llvm_unreachable("Unknown shuffle opcode!");
6882   case OP_VREV:
6883     // VREV divides the vector in half and swaps within the half.
6884     if (VT.getVectorElementType() == MVT::i32 ||
6885         VT.getVectorElementType() == MVT::f32)
6886       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6887     // vrev <4 x i16> -> VREV32
6888     if (VT.getVectorElementType() == MVT::i16)
6889       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6890     // vrev <4 x i8> -> VREV16
6891     assert(VT.getVectorElementType() == MVT::i8);
6892     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6893   case OP_VDUP0:
6894   case OP_VDUP1:
6895   case OP_VDUP2:
6896   case OP_VDUP3:
6897     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6898                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6899   case OP_VEXT1:
6900   case OP_VEXT2:
6901   case OP_VEXT3:
6902     return DAG.getNode(ARMISD::VEXT, dl, VT,
6903                        OpLHS, OpRHS,
6904                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6905   case OP_VUZPL:
6906   case OP_VUZPR:
6907     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6908                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6909   case OP_VZIPL:
6910   case OP_VZIPR:
6911     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6912                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6913   case OP_VTRNL:
6914   case OP_VTRNR:
6915     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6916                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6917   }
6918 }
6919 
6920 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6921                                        ArrayRef<int> ShuffleMask,
6922                                        SelectionDAG &DAG) {
6923   // Check to see if we can use the VTBL instruction.
6924   SDValue V1 = Op.getOperand(0);
6925   SDValue V2 = Op.getOperand(1);
6926   SDLoc DL(Op);
6927 
6928   SmallVector<SDValue, 8> VTBLMask;
6929   for (ArrayRef<int>::iterator
6930          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6931     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6932 
6933   if (V2.getNode()->isUndef())
6934     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6935                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6936 
6937   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6938                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6939 }
6940 
6941 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6942                                                       SelectionDAG &DAG) {
6943   SDLoc DL(Op);
6944   SDValue OpLHS = Op.getOperand(0);
6945   EVT VT = OpLHS.getValueType();
6946 
6947   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6948          "Expect an v8i16/v16i8 type");
6949   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6950   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6951   // extract the first 8 bytes into the top double word and the last 8 bytes
6952   // into the bottom double word. The v8i16 case is similar.
6953   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6954   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6955                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6956 }
6957 
6958 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6959   SDValue V1 = Op.getOperand(0);
6960   SDValue V2 = Op.getOperand(1);
6961   SDLoc dl(Op);
6962   EVT VT = Op.getValueType();
6963   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6964 
6965   // Convert shuffles that are directly supported on NEON to target-specific
6966   // DAG nodes, instead of keeping them as shuffles and matching them again
6967   // during code selection.  This is more efficient and avoids the possibility
6968   // of inconsistencies between legalization and selection.
6969   // FIXME: floating-point vectors should be canonicalized to integer vectors
6970   // of the same time so that they get CSEd properly.
6971   ArrayRef<int> ShuffleMask = SVN->getMask();
6972 
6973   unsigned EltSize = VT.getScalarSizeInBits();
6974   if (EltSize <= 32) {
6975     if (SVN->isSplat()) {
6976       int Lane = SVN->getSplatIndex();
6977       // If this is undef splat, generate it via "just" vdup, if possible.
6978       if (Lane == -1) Lane = 0;
6979 
6980       // Test if V1 is a SCALAR_TO_VECTOR.
6981       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6982         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6983       }
6984       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6985       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6986       // reaches it).
6987       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6988           !isa<ConstantSDNode>(V1.getOperand(0))) {
6989         bool IsScalarToVector = true;
6990         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6991           if (!V1.getOperand(i).isUndef()) {
6992             IsScalarToVector = false;
6993             break;
6994           }
6995         if (IsScalarToVector)
6996           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6997       }
6998       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6999                          DAG.getConstant(Lane, dl, MVT::i32));
7000     }
7001 
7002     bool ReverseVEXT;
7003     unsigned Imm;
7004     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7005       if (ReverseVEXT)
7006         std::swap(V1, V2);
7007       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7008                          DAG.getConstant(Imm, dl, MVT::i32));
7009     }
7010 
7011     if (isVREVMask(ShuffleMask, VT, 64))
7012       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7013     if (isVREVMask(ShuffleMask, VT, 32))
7014       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7015     if (isVREVMask(ShuffleMask, VT, 16))
7016       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7017 
7018     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7019       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7020                          DAG.getConstant(Imm, dl, MVT::i32));
7021     }
7022 
7023     // Check for Neon shuffles that modify both input vectors in place.
7024     // If both results are used, i.e., if there are two shuffles with the same
7025     // source operands and with masks corresponding to both results of one of
7026     // these operations, DAG memoization will ensure that a single node is
7027     // used for both shuffles.
7028     unsigned WhichResult;
7029     bool isV_UNDEF;
7030     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7031             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7032       if (isV_UNDEF)
7033         V2 = V1;
7034       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7035           .getValue(WhichResult);
7036     }
7037 
7038     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7039     // shuffles that produce a result larger than their operands with:
7040     //   shuffle(concat(v1, undef), concat(v2, undef))
7041     // ->
7042     //   shuffle(concat(v1, v2), undef)
7043     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7044     //
7045     // This is useful in the general case, but there are special cases where
7046     // native shuffles produce larger results: the two-result ops.
7047     //
7048     // Look through the concat when lowering them:
7049     //   shuffle(concat(v1, v2), undef)
7050     // ->
7051     //   concat(VZIP(v1, v2):0, :1)
7052     //
7053     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7054       SDValue SubV1 = V1->getOperand(0);
7055       SDValue SubV2 = V1->getOperand(1);
7056       EVT SubVT = SubV1.getValueType();
7057 
7058       // We expect these to have been canonicalized to -1.
7059       assert(llvm::all_of(ShuffleMask, [&](int i) {
7060         return i < (int)VT.getVectorNumElements();
7061       }) && "Unexpected shuffle index into UNDEF operand!");
7062 
7063       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7064               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7065         if (isV_UNDEF)
7066           SubV2 = SubV1;
7067         assert((WhichResult == 0) &&
7068                "In-place shuffle of concat can only have one result!");
7069         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7070                                   SubV1, SubV2);
7071         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7072                            Res.getValue(1));
7073       }
7074     }
7075   }
7076 
7077   // If the shuffle is not directly supported and it has 4 elements, use
7078   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7079   unsigned NumElts = VT.getVectorNumElements();
7080   if (NumElts == 4) {
7081     unsigned PFIndexes[4];
7082     for (unsigned i = 0; i != 4; ++i) {
7083       if (ShuffleMask[i] < 0)
7084         PFIndexes[i] = 8;
7085       else
7086         PFIndexes[i] = ShuffleMask[i];
7087     }
7088 
7089     // Compute the index in the perfect shuffle table.
7090     unsigned PFTableIndex =
7091       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7092     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7093     unsigned Cost = (PFEntry >> 30);
7094 
7095     if (Cost <= 4)
7096       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7097   }
7098 
7099   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7100   if (EltSize >= 32) {
7101     // Do the expansion with floating-point types, since that is what the VFP
7102     // registers are defined to use, and since i64 is not legal.
7103     EVT EltVT = EVT::getFloatingPointVT(EltSize);
7104     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7105     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7106     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7107     SmallVector<SDValue, 8> Ops;
7108     for (unsigned i = 0; i < NumElts; ++i) {
7109       if (ShuffleMask[i] < 0)
7110         Ops.push_back(DAG.getUNDEF(EltVT));
7111       else
7112         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7113                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
7114                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7115                                                   dl, MVT::i32)));
7116     }
7117     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7118     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7119   }
7120 
7121   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7122     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7123 
7124   if (VT == MVT::v8i8)
7125     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7126       return NewOp;
7127 
7128   return SDValue();
7129 }
7130 
7131 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7132   // INSERT_VECTOR_ELT is legal only for immediate indexes.
7133   SDValue Lane = Op.getOperand(2);
7134   if (!isa<ConstantSDNode>(Lane))
7135     return SDValue();
7136 
7137   return Op;
7138 }
7139 
7140 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7141   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7142   SDValue Lane = Op.getOperand(1);
7143   if (!isa<ConstantSDNode>(Lane))
7144     return SDValue();
7145 
7146   SDValue Vec = Op.getOperand(0);
7147   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7148     SDLoc dl(Op);
7149     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7150   }
7151 
7152   return Op;
7153 }
7154 
7155 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7156   // The only time a CONCAT_VECTORS operation can have legal types is when
7157   // two 64-bit vectors are concatenated to a 128-bit vector.
7158   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
7159          "unexpected CONCAT_VECTORS");
7160   SDLoc dl(Op);
7161   SDValue Val = DAG.getUNDEF(MVT::v2f64);
7162   SDValue Op0 = Op.getOperand(0);
7163   SDValue Op1 = Op.getOperand(1);
7164   if (!Op0.isUndef())
7165     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7166                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
7167                       DAG.getIntPtrConstant(0, dl));
7168   if (!Op1.isUndef())
7169     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7170                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
7171                       DAG.getIntPtrConstant(1, dl));
7172   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
7173 }
7174 
7175 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
7176 /// element has been zero/sign-extended, depending on the isSigned parameter,
7177 /// from an integer type half its size.
7178 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
7179                                    bool isSigned) {
7180   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
7181   EVT VT = N->getValueType(0);
7182   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
7183     SDNode *BVN = N->getOperand(0).getNode();
7184     if (BVN->getValueType(0) != MVT::v4i32 ||
7185         BVN->getOpcode() != ISD::BUILD_VECTOR)
7186       return false;
7187     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7188     unsigned HiElt = 1 - LoElt;
7189     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
7190     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
7191     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
7192     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
7193     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
7194       return false;
7195     if (isSigned) {
7196       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
7197           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
7198         return true;
7199     } else {
7200       if (Hi0->isNullValue() && Hi1->isNullValue())
7201         return true;
7202     }
7203     return false;
7204   }
7205 
7206   if (N->getOpcode() != ISD::BUILD_VECTOR)
7207     return false;
7208 
7209   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
7210     SDNode *Elt = N->getOperand(i).getNode();
7211     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
7212       unsigned EltSize = VT.getScalarSizeInBits();
7213       unsigned HalfSize = EltSize / 2;
7214       if (isSigned) {
7215         if (!isIntN(HalfSize, C->getSExtValue()))
7216           return false;
7217       } else {
7218         if (!isUIntN(HalfSize, C->getZExtValue()))
7219           return false;
7220       }
7221       continue;
7222     }
7223     return false;
7224   }
7225 
7226   return true;
7227 }
7228 
7229 /// isSignExtended - Check if a node is a vector value that is sign-extended
7230 /// or a constant BUILD_VECTOR with sign-extended elements.
7231 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7232   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7233     return true;
7234   if (isExtendedBUILD_VECTOR(N, DAG, true))
7235     return true;
7236   return false;
7237 }
7238 
7239 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7240 /// or a constant BUILD_VECTOR with zero-extended elements.
7241 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7242   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7243     return true;
7244   if (isExtendedBUILD_VECTOR(N, DAG, false))
7245     return true;
7246   return false;
7247 }
7248 
7249 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7250   if (OrigVT.getSizeInBits() >= 64)
7251     return OrigVT;
7252 
7253   assert(OrigVT.isSimple() && "Expecting a simple value type");
7254 
7255   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7256   switch (OrigSimpleTy) {
7257   default: llvm_unreachable("Unexpected Vector Type");
7258   case MVT::v2i8:
7259   case MVT::v2i16:
7260      return MVT::v2i32;
7261   case MVT::v4i8:
7262     return  MVT::v4i16;
7263   }
7264 }
7265 
7266 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7267 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7268 /// We insert the required extension here to get the vector to fill a D register.
7269 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7270                                             const EVT &OrigTy,
7271                                             const EVT &ExtTy,
7272                                             unsigned ExtOpcode) {
7273   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7274   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7275   // 64-bits we need to insert a new extension so that it will be 64-bits.
7276   assert(ExtTy.is128BitVector() && "Unexpected extension size");
7277   if (OrigTy.getSizeInBits() >= 64)
7278     return N;
7279 
7280   // Must extend size to at least 64 bits to be used as an operand for VMULL.
7281   EVT NewVT = getExtensionTo64Bits(OrigTy);
7282 
7283   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7284 }
7285 
7286 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7287 /// does not do any sign/zero extension. If the original vector is less
7288 /// than 64 bits, an appropriate extension will be added after the load to
7289 /// reach a total size of 64 bits. We have to add the extension separately
7290 /// because ARM does not have a sign/zero extending load for vectors.
7291 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7292   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7293 
7294   // The load already has the right type.
7295   if (ExtendedTy == LD->getMemoryVT())
7296     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7297                        LD->getBasePtr(), LD->getPointerInfo(),
7298                        LD->getAlignment(), LD->getMemOperand()->getFlags());
7299 
7300   // We need to create a zextload/sextload. We cannot just create a load
7301   // followed by a zext/zext node because LowerMUL is also run during normal
7302   // operation legalization where we can't create illegal types.
7303   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7304                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7305                         LD->getMemoryVT(), LD->getAlignment(),
7306                         LD->getMemOperand()->getFlags());
7307 }
7308 
7309 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7310 /// extending load, or BUILD_VECTOR with extended elements, return the
7311 /// unextended value. The unextended vector should be 64 bits so that it can
7312 /// be used as an operand to a VMULL instruction. If the original vector size
7313 /// before extension is less than 64 bits we add a an extension to resize
7314 /// the vector to 64 bits.
7315 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7316   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7317     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7318                                         N->getOperand(0)->getValueType(0),
7319                                         N->getValueType(0),
7320                                         N->getOpcode());
7321 
7322   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7323     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7324            "Expected extending load");
7325 
7326     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7327     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7328     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7329     SDValue extLoad =
7330         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7331     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7332 
7333     return newLoad;
7334   }
7335 
7336   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7337   // have been legalized as a BITCAST from v4i32.
7338   if (N->getOpcode() == ISD::BITCAST) {
7339     SDNode *BVN = N->getOperand(0).getNode();
7340     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7341            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7342     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7343     return DAG.getBuildVector(
7344         MVT::v2i32, SDLoc(N),
7345         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7346   }
7347   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7348   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7349   EVT VT = N->getValueType(0);
7350   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7351   unsigned NumElts = VT.getVectorNumElements();
7352   MVT TruncVT = MVT::getIntegerVT(EltSize);
7353   SmallVector<SDValue, 8> Ops;
7354   SDLoc dl(N);
7355   for (unsigned i = 0; i != NumElts; ++i) {
7356     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7357     const APInt &CInt = C->getAPIntValue();
7358     // Element types smaller than 32 bits are not legal, so use i32 elements.
7359     // The values are implicitly truncated so sext vs. zext doesn't matter.
7360     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7361   }
7362   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7363 }
7364 
7365 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7366   unsigned Opcode = N->getOpcode();
7367   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7368     SDNode *N0 = N->getOperand(0).getNode();
7369     SDNode *N1 = N->getOperand(1).getNode();
7370     return N0->hasOneUse() && N1->hasOneUse() &&
7371       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7372   }
7373   return false;
7374 }
7375 
7376 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7377   unsigned Opcode = N->getOpcode();
7378   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7379     SDNode *N0 = N->getOperand(0).getNode();
7380     SDNode *N1 = N->getOperand(1).getNode();
7381     return N0->hasOneUse() && N1->hasOneUse() &&
7382       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7383   }
7384   return false;
7385 }
7386 
7387 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7388   // Multiplications are only custom-lowered for 128-bit vectors so that
7389   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7390   EVT VT = Op.getValueType();
7391   assert(VT.is128BitVector() && VT.isInteger() &&
7392          "unexpected type for custom-lowering ISD::MUL");
7393   SDNode *N0 = Op.getOperand(0).getNode();
7394   SDNode *N1 = Op.getOperand(1).getNode();
7395   unsigned NewOpc = 0;
7396   bool isMLA = false;
7397   bool isN0SExt = isSignExtended(N0, DAG);
7398   bool isN1SExt = isSignExtended(N1, DAG);
7399   if (isN0SExt && isN1SExt)
7400     NewOpc = ARMISD::VMULLs;
7401   else {
7402     bool isN0ZExt = isZeroExtended(N0, DAG);
7403     bool isN1ZExt = isZeroExtended(N1, DAG);
7404     if (isN0ZExt && isN1ZExt)
7405       NewOpc = ARMISD::VMULLu;
7406     else if (isN1SExt || isN1ZExt) {
7407       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7408       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7409       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7410         NewOpc = ARMISD::VMULLs;
7411         isMLA = true;
7412       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7413         NewOpc = ARMISD::VMULLu;
7414         isMLA = true;
7415       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7416         std::swap(N0, N1);
7417         NewOpc = ARMISD::VMULLu;
7418         isMLA = true;
7419       }
7420     }
7421 
7422     if (!NewOpc) {
7423       if (VT == MVT::v2i64)
7424         // Fall through to expand this.  It is not legal.
7425         return SDValue();
7426       else
7427         // Other vector multiplications are legal.
7428         return Op;
7429     }
7430   }
7431 
7432   // Legalize to a VMULL instruction.
7433   SDLoc DL(Op);
7434   SDValue Op0;
7435   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7436   if (!isMLA) {
7437     Op0 = SkipExtensionForVMULL(N0, DAG);
7438     assert(Op0.getValueType().is64BitVector() &&
7439            Op1.getValueType().is64BitVector() &&
7440            "unexpected types for extended operands to VMULL");
7441     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7442   }
7443 
7444   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7445   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7446   //   vmull q0, d4, d6
7447   //   vmlal q0, d5, d6
7448   // is faster than
7449   //   vaddl q0, d4, d5
7450   //   vmovl q1, d6
7451   //   vmul  q0, q0, q1
7452   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7453   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7454   EVT Op1VT = Op1.getValueType();
7455   return DAG.getNode(N0->getOpcode(), DL, VT,
7456                      DAG.getNode(NewOpc, DL, VT,
7457                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7458                      DAG.getNode(NewOpc, DL, VT,
7459                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7460 }
7461 
7462 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7463                               SelectionDAG &DAG) {
7464   // TODO: Should this propagate fast-math-flags?
7465 
7466   // Convert to float
7467   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7468   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7469   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7470   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7471   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7472   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7473   // Get reciprocal estimate.
7474   // float4 recip = vrecpeq_f32(yf);
7475   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7476                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7477                    Y);
7478   // Because char has a smaller range than uchar, we can actually get away
7479   // without any newton steps.  This requires that we use a weird bias
7480   // of 0xb000, however (again, this has been exhaustively tested).
7481   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7482   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7483   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7484   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7485   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7486   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7487   // Convert back to short.
7488   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7489   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7490   return X;
7491 }
7492 
7493 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7494                                SelectionDAG &DAG) {
7495   // TODO: Should this propagate fast-math-flags?
7496 
7497   SDValue N2;
7498   // Convert to float.
7499   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7500   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7501   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7502   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7503   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7504   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7505 
7506   // Use reciprocal estimate and one refinement step.
7507   // float4 recip = vrecpeq_f32(yf);
7508   // recip *= vrecpsq_f32(yf, recip);
7509   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7510                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7511                    N1);
7512   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7513                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7514                    N1, N2);
7515   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7516   // Because short has a smaller range than ushort, we can actually get away
7517   // with only a single newton step.  This requires that we use a weird bias
7518   // of 89, however (again, this has been exhaustively tested).
7519   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7520   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7521   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7522   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7523   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7524   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7525   // Convert back to integer and return.
7526   // return vmovn_s32(vcvt_s32_f32(result));
7527   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7528   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7529   return N0;
7530 }
7531 
7532 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7533   EVT VT = Op.getValueType();
7534   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7535          "unexpected type for custom-lowering ISD::SDIV");
7536 
7537   SDLoc dl(Op);
7538   SDValue N0 = Op.getOperand(0);
7539   SDValue N1 = Op.getOperand(1);
7540   SDValue N2, N3;
7541 
7542   if (VT == MVT::v8i8) {
7543     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7544     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7545 
7546     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7547                      DAG.getIntPtrConstant(4, dl));
7548     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7549                      DAG.getIntPtrConstant(4, dl));
7550     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7551                      DAG.getIntPtrConstant(0, dl));
7552     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7553                      DAG.getIntPtrConstant(0, dl));
7554 
7555     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7556     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7557 
7558     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7559     N0 = LowerCONCAT_VECTORS(N0, DAG);
7560 
7561     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7562     return N0;
7563   }
7564   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7565 }
7566 
7567 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7568   // TODO: Should this propagate fast-math-flags?
7569   EVT VT = Op.getValueType();
7570   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7571          "unexpected type for custom-lowering ISD::UDIV");
7572 
7573   SDLoc dl(Op);
7574   SDValue N0 = Op.getOperand(0);
7575   SDValue N1 = Op.getOperand(1);
7576   SDValue N2, N3;
7577 
7578   if (VT == MVT::v8i8) {
7579     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7580     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7581 
7582     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7583                      DAG.getIntPtrConstant(4, dl));
7584     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7585                      DAG.getIntPtrConstant(4, dl));
7586     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7587                      DAG.getIntPtrConstant(0, dl));
7588     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7589                      DAG.getIntPtrConstant(0, dl));
7590 
7591     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7592     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7593 
7594     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7595     N0 = LowerCONCAT_VECTORS(N0, DAG);
7596 
7597     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7598                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7599                                      MVT::i32),
7600                      N0);
7601     return N0;
7602   }
7603 
7604   // v4i16 sdiv ... Convert to float.
7605   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7606   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7607   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7608   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7609   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7610   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7611 
7612   // Use reciprocal estimate and two refinement steps.
7613   // float4 recip = vrecpeq_f32(yf);
7614   // recip *= vrecpsq_f32(yf, recip);
7615   // recip *= vrecpsq_f32(yf, recip);
7616   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7617                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7618                    BN1);
7619   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7620                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7621                    BN1, N2);
7622   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7623   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7624                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7625                    BN1, N2);
7626   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7627   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7628   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7629   // and that it will never cause us to return an answer too large).
7630   // float4 result = as_float4(as_int4(xf*recip) + 2);
7631   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7632   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7633   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7634   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7635   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7636   // Convert back to integer and return.
7637   // return vmovn_u32(vcvt_s32_f32(result));
7638   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7639   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7640   return N0;
7641 }
7642 
7643 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
7644   SDNode *N = Op.getNode();
7645   EVT VT = N->getValueType(0);
7646   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7647 
7648   SDValue Carry = Op.getOperand(2);
7649 
7650   SDLoc DL(Op);
7651 
7652   SDValue Result;
7653   if (Op.getOpcode() == ISD::ADDCARRY) {
7654     // This converts the boolean value carry into the carry flag.
7655     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7656 
7657     // Do the addition proper using the carry flag we wanted.
7658     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
7659                          Op.getOperand(1), Carry);
7660 
7661     // Now convert the carry flag into a boolean value.
7662     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7663   } else {
7664     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
7665     // have to invert the carry first.
7666     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7667                         DAG.getConstant(1, DL, MVT::i32), Carry);
7668     // This converts the boolean value carry into the carry flag.
7669     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7670 
7671     // Do the subtraction proper using the carry flag we wanted.
7672     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
7673                          Op.getOperand(1), Carry);
7674 
7675     // Now convert the carry flag into a boolean value.
7676     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7677     // But the carry returned by ARMISD::SUBE is not a borrow as expected
7678     // by ISD::SUBCARRY, so compute 1 - C.
7679     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7680                         DAG.getConstant(1, DL, MVT::i32), Carry);
7681   }
7682 
7683   // Return both values.
7684   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
7685 }
7686 
7687 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7688   assert(Subtarget->isTargetDarwin());
7689 
7690   // For iOS, we want to call an alternative entry point: __sincos_stret,
7691   // return values are passed via sret.
7692   SDLoc dl(Op);
7693   SDValue Arg = Op.getOperand(0);
7694   EVT ArgVT = Arg.getValueType();
7695   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7696   auto PtrVT = getPointerTy(DAG.getDataLayout());
7697 
7698   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7699   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7700 
7701   // Pair of floats / doubles used to pass the result.
7702   Type *RetTy = StructType::get(ArgTy, ArgTy);
7703   auto &DL = DAG.getDataLayout();
7704 
7705   ArgListTy Args;
7706   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7707   SDValue SRet;
7708   if (ShouldUseSRet) {
7709     // Create stack object for sret.
7710     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7711     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7712     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7713     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7714 
7715     ArgListEntry Entry;
7716     Entry.Node = SRet;
7717     Entry.Ty = RetTy->getPointerTo();
7718     Entry.IsSExt = false;
7719     Entry.IsZExt = false;
7720     Entry.IsSRet = true;
7721     Args.push_back(Entry);
7722     RetTy = Type::getVoidTy(*DAG.getContext());
7723   }
7724 
7725   ArgListEntry Entry;
7726   Entry.Node = Arg;
7727   Entry.Ty = ArgTy;
7728   Entry.IsSExt = false;
7729   Entry.IsZExt = false;
7730   Args.push_back(Entry);
7731 
7732   RTLIB::Libcall LC =
7733       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
7734   const char *LibcallName = getLibcallName(LC);
7735   CallingConv::ID CC = getLibcallCallingConv(LC);
7736   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7737 
7738   TargetLowering::CallLoweringInfo CLI(DAG);
7739   CLI.setDebugLoc(dl)
7740       .setChain(DAG.getEntryNode())
7741       .setCallee(CC, RetTy, Callee, std::move(Args))
7742       .setDiscardResult(ShouldUseSRet);
7743   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7744 
7745   if (!ShouldUseSRet)
7746     return CallResult.first;
7747 
7748   SDValue LoadSin =
7749       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7750 
7751   // Address of cos field.
7752   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7753                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7754   SDValue LoadCos =
7755       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7756 
7757   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7758   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7759                      LoadSin.getValue(0), LoadCos.getValue(0));
7760 }
7761 
7762 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7763                                                   bool Signed,
7764                                                   SDValue &Chain) const {
7765   EVT VT = Op.getValueType();
7766   assert((VT == MVT::i32 || VT == MVT::i64) &&
7767          "unexpected type for custom lowering DIV");
7768   SDLoc dl(Op);
7769 
7770   const auto &DL = DAG.getDataLayout();
7771   const auto &TLI = DAG.getTargetLoweringInfo();
7772 
7773   const char *Name = nullptr;
7774   if (Signed)
7775     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7776   else
7777     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7778 
7779   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7780 
7781   ARMTargetLowering::ArgListTy Args;
7782 
7783   for (auto AI : {1, 0}) {
7784     ArgListEntry Arg;
7785     Arg.Node = Op.getOperand(AI);
7786     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7787     Args.push_back(Arg);
7788   }
7789 
7790   CallLoweringInfo CLI(DAG);
7791   CLI.setDebugLoc(dl)
7792     .setChain(Chain)
7793     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7794                ES, std::move(Args));
7795 
7796   return LowerCallTo(CLI).first;
7797 }
7798 
7799 // This is a code size optimisation: return the original SDIV node to
7800 // DAGCombiner when we don't want to expand SDIV into a sequence of
7801 // instructions, and an empty node otherwise which will cause the
7802 // SDIV to be expanded in DAGCombine.
7803 SDValue
7804 ARMTargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
7805                                  SelectionDAG &DAG,
7806                                  SmallVectorImpl<SDNode *> &Created) const {
7807   // TODO: Support SREM
7808   if (N->getOpcode() != ISD::SDIV)
7809     return SDValue();
7810 
7811   const auto &ST = static_cast<const ARMSubtarget&>(DAG.getSubtarget());
7812   const auto &MF = DAG.getMachineFunction();
7813   const bool MinSize = MF.getFunction().optForMinSize();
7814   const bool HasDivide = ST.isThumb() ? ST.hasDivideInThumbMode()
7815                                       : ST.hasDivideInARMMode();
7816 
7817   // Don't touch vector types; rewriting this may lead to scalarizing
7818   // the int divs.
7819   if (N->getOperand(0).getValueType().isVector())
7820     return SDValue();
7821 
7822   // Bail if MinSize is not set, and also for both ARM and Thumb mode we need
7823   // hwdiv support for this to be really profitable.
7824   if (!(MinSize && HasDivide))
7825     return SDValue();
7826 
7827   // ARM mode is a bit simpler than Thumb: we can handle large power
7828   // of 2 immediates with 1 mov instruction; no further checks required,
7829   // just return the sdiv node.
7830   if (!ST.isThumb())
7831     return SDValue(N, 0);
7832 
7833   // In Thumb mode, immediates larger than 128 need a wide 4-byte MOV,
7834   // and thus lose the code size benefits of a MOVS that requires only 2.
7835   // TargetTransformInfo and 'getIntImmCodeSizeCost' could be helpful here,
7836   // but as it's doing exactly this, it's not worth the trouble to get TTI.
7837   if (Divisor.sgt(128))
7838     return SDValue();
7839 
7840   return SDValue(N, 0);
7841 }
7842 
7843 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7844                                             bool Signed) const {
7845   assert(Op.getValueType() == MVT::i32 &&
7846          "unexpected type for custom lowering DIV");
7847   SDLoc dl(Op);
7848 
7849   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7850                                DAG.getEntryNode(), Op.getOperand(1));
7851 
7852   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7853 }
7854 
7855 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7856   SDLoc DL(N);
7857   SDValue Op = N->getOperand(1);
7858   if (N->getValueType(0) == MVT::i32)
7859     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7860   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7861                            DAG.getConstant(0, DL, MVT::i32));
7862   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7863                            DAG.getConstant(1, DL, MVT::i32));
7864   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7865                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7866 }
7867 
7868 void ARMTargetLowering::ExpandDIV_Windows(
7869     SDValue Op, SelectionDAG &DAG, bool Signed,
7870     SmallVectorImpl<SDValue> &Results) const {
7871   const auto &DL = DAG.getDataLayout();
7872   const auto &TLI = DAG.getTargetLoweringInfo();
7873 
7874   assert(Op.getValueType() == MVT::i64 &&
7875          "unexpected type for custom lowering DIV");
7876   SDLoc dl(Op);
7877 
7878   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7879 
7880   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7881 
7882   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7883   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7884                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7885   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7886 
7887   Results.push_back(Lower);
7888   Results.push_back(Upper);
7889 }
7890 
7891 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7892   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7893     // Acquire/Release load/store is not legal for targets without a dmb or
7894     // equivalent available.
7895     return SDValue();
7896 
7897   // Monotonic load/store is legal for all targets.
7898   return Op;
7899 }
7900 
7901 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7902                                     SmallVectorImpl<SDValue> &Results,
7903                                     SelectionDAG &DAG,
7904                                     const ARMSubtarget *Subtarget) {
7905   SDLoc DL(N);
7906   // Under Power Management extensions, the cycle-count is:
7907   //    mrc p15, #0, <Rt>, c9, c13, #0
7908   SDValue Ops[] = { N->getOperand(0), // Chain
7909                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7910                     DAG.getConstant(15, DL, MVT::i32),
7911                     DAG.getConstant(0, DL, MVT::i32),
7912                     DAG.getConstant(9, DL, MVT::i32),
7913                     DAG.getConstant(13, DL, MVT::i32),
7914                     DAG.getConstant(0, DL, MVT::i32)
7915   };
7916 
7917   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7918                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7919   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7920                                 DAG.getConstant(0, DL, MVT::i32)));
7921   Results.push_back(Cycles32.getValue(1));
7922 }
7923 
7924 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7925   SDLoc dl(V.getNode());
7926   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7927   SDValue VHi = DAG.getAnyExtOrTrunc(
7928       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7929       dl, MVT::i32);
7930   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7931   if (isBigEndian)
7932     std::swap (VLo, VHi);
7933   SDValue RegClass =
7934       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7935   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7936   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7937   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7938   return SDValue(
7939       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7940 }
7941 
7942 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7943                                        SmallVectorImpl<SDValue> & Results,
7944                                        SelectionDAG &DAG) {
7945   assert(N->getValueType(0) == MVT::i64 &&
7946          "AtomicCmpSwap on types less than 64 should be legal");
7947   SDValue Ops[] = {N->getOperand(1),
7948                    createGPRPairNode(DAG, N->getOperand(2)),
7949                    createGPRPairNode(DAG, N->getOperand(3)),
7950                    N->getOperand(0)};
7951   SDNode *CmpSwap = DAG.getMachineNode(
7952       ARM::CMP_SWAP_64, SDLoc(N),
7953       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7954 
7955   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
7956   DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
7957 
7958   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7959 
7960   Results.push_back(
7961       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
7962                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7963   Results.push_back(
7964       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
7965                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7966   Results.push_back(SDValue(CmpSwap, 2));
7967 }
7968 
7969 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7970                           SelectionDAG &DAG) {
7971   const auto &TLI = DAG.getTargetLoweringInfo();
7972 
7973   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7974          "Custom lowering is MSVCRT specific!");
7975 
7976   SDLoc dl(Op);
7977   SDValue Val = Op.getOperand(0);
7978   MVT Ty = Val->getSimpleValueType(0);
7979   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7980   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7981                                          TLI.getPointerTy(DAG.getDataLayout()));
7982 
7983   TargetLowering::ArgListTy Args;
7984   TargetLowering::ArgListEntry Entry;
7985 
7986   Entry.Node = Val;
7987   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7988   Entry.IsZExt = true;
7989   Args.push_back(Entry);
7990 
7991   Entry.Node = Exponent;
7992   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7993   Entry.IsZExt = true;
7994   Args.push_back(Entry);
7995 
7996   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7997 
7998   // In the in-chain to the call is the entry node  If we are emitting a
7999   // tailcall, the chain will be mutated if the node has a non-entry input
8000   // chain.
8001   SDValue InChain = DAG.getEntryNode();
8002   SDValue TCChain = InChain;
8003 
8004   const Function &F = DAG.getMachineFunction().getFunction();
8005   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
8006               F.getReturnType() == LCRTy;
8007   if (IsTC)
8008     InChain = TCChain;
8009 
8010   TargetLowering::CallLoweringInfo CLI(DAG);
8011   CLI.setDebugLoc(dl)
8012       .setChain(InChain)
8013       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
8014       .setTailCall(IsTC);
8015   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
8016 
8017   // Return the chain (the DAG root) if it is a tail call
8018   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
8019 }
8020 
8021 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8022   LLVM_DEBUG(dbgs() << "Lowering node: "; Op.dump());
8023   switch (Op.getOpcode()) {
8024   default: llvm_unreachable("Don't know how to custom lower this!");
8025   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
8026   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8027   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
8028   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8029   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8030   case ISD::SELECT:        return LowerSELECT(Op, DAG);
8031   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
8032   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
8033   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
8034   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
8035   case ISD::VASTART:       return LowerVASTART(Op, DAG);
8036   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8037   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
8038   case ISD::SINT_TO_FP:
8039   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
8040   case ISD::FP_TO_SINT:
8041   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
8042   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
8043   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
8044   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
8045   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
8046   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
8047   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
8048   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
8049                                                                Subtarget);
8050   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
8051   case ISD::SHL:
8052   case ISD::SRL:
8053   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
8054   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
8055   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
8056   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
8057   case ISD::SRL_PARTS:
8058   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
8059   case ISD::CTTZ:
8060   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
8061   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
8062   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
8063   case ISD::SETCCCARRY:    return LowerSETCCCARRY(Op, DAG);
8064   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
8065   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
8066   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8067   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8068   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8069   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8070   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
8071   case ISD::MUL:           return LowerMUL(Op, DAG);
8072   case ISD::SDIV:
8073     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8074       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
8075     return LowerSDIV(Op, DAG);
8076   case ISD::UDIV:
8077     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8078       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
8079     return LowerUDIV(Op, DAG);
8080   case ISD::ADDCARRY:
8081   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
8082   case ISD::SADDO:
8083   case ISD::SSUBO:
8084     return LowerSignedALUO(Op, DAG);
8085   case ISD::UADDO:
8086   case ISD::USUBO:
8087     return LowerUnsignedALUO(Op, DAG);
8088   case ISD::ATOMIC_LOAD:
8089   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
8090   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
8091   case ISD::SDIVREM:
8092   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
8093   case ISD::DYNAMIC_STACKALLOC:
8094     if (Subtarget->isTargetWindows())
8095       return LowerDYNAMIC_STACKALLOC(Op, DAG);
8096     llvm_unreachable("Don't know how to custom lower this!");
8097   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
8098   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
8099   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
8100   case ARMISD::WIN__DBZCHK: return SDValue();
8101   }
8102 }
8103 
8104 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
8105                                  SelectionDAG &DAG) {
8106   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8107   unsigned Opc = 0;
8108   if (IntNo == Intrinsic::arm_smlald)
8109     Opc = ARMISD::SMLALD;
8110   else if (IntNo == Intrinsic::arm_smlaldx)
8111     Opc = ARMISD::SMLALDX;
8112   else if (IntNo == Intrinsic::arm_smlsld)
8113     Opc = ARMISD::SMLSLD;
8114   else if (IntNo == Intrinsic::arm_smlsldx)
8115     Opc = ARMISD::SMLSLDX;
8116   else
8117     return;
8118 
8119   SDLoc dl(N);
8120   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8121                            N->getOperand(3),
8122                            DAG.getConstant(0, dl, MVT::i32));
8123   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8124                            N->getOperand(3),
8125                            DAG.getConstant(1, dl, MVT::i32));
8126 
8127   SDValue LongMul = DAG.getNode(Opc, dl,
8128                                 DAG.getVTList(MVT::i32, MVT::i32),
8129                                 N->getOperand(1), N->getOperand(2),
8130                                 Lo, Hi);
8131   Results.push_back(LongMul.getValue(0));
8132   Results.push_back(LongMul.getValue(1));
8133 }
8134 
8135 /// ReplaceNodeResults - Replace the results of node with an illegal result
8136 /// type with new values built out of custom code.
8137 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
8138                                            SmallVectorImpl<SDValue> &Results,
8139                                            SelectionDAG &DAG) const {
8140   SDValue Res;
8141   switch (N->getOpcode()) {
8142   default:
8143     llvm_unreachable("Don't know how to custom expand this!");
8144   case ISD::READ_REGISTER:
8145     ExpandREAD_REGISTER(N, Results, DAG);
8146     break;
8147   case ISD::BITCAST:
8148     Res = ExpandBITCAST(N, DAG, Subtarget);
8149     break;
8150   case ISD::SRL:
8151   case ISD::SRA:
8152     Res = Expand64BitShift(N, DAG, Subtarget);
8153     break;
8154   case ISD::SREM:
8155   case ISD::UREM:
8156     Res = LowerREM(N, DAG);
8157     break;
8158   case ISD::SDIVREM:
8159   case ISD::UDIVREM:
8160     Res = LowerDivRem(SDValue(N, 0), DAG);
8161     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
8162     Results.push_back(Res.getValue(0));
8163     Results.push_back(Res.getValue(1));
8164     return;
8165   case ISD::READCYCLECOUNTER:
8166     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
8167     return;
8168   case ISD::UDIV:
8169   case ISD::SDIV:
8170     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
8171     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
8172                              Results);
8173   case ISD::ATOMIC_CMP_SWAP:
8174     ReplaceCMP_SWAP_64Results(N, Results, DAG);
8175     return;
8176   case ISD::INTRINSIC_WO_CHAIN:
8177     return ReplaceLongIntrinsic(N, Results, DAG);
8178   }
8179   if (Res.getNode())
8180     Results.push_back(Res);
8181 }
8182 
8183 //===----------------------------------------------------------------------===//
8184 //                           ARM Scheduler Hooks
8185 //===----------------------------------------------------------------------===//
8186 
8187 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
8188 /// registers the function context.
8189 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
8190                                                MachineBasicBlock *MBB,
8191                                                MachineBasicBlock *DispatchBB,
8192                                                int FI) const {
8193   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
8194          "ROPI/RWPI not currently supported with SjLj");
8195   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8196   DebugLoc dl = MI.getDebugLoc();
8197   MachineFunction *MF = MBB->getParent();
8198   MachineRegisterInfo *MRI = &MF->getRegInfo();
8199   MachineConstantPool *MCP = MF->getConstantPool();
8200   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
8201   const Function &F = MF->getFunction();
8202 
8203   bool isThumb = Subtarget->isThumb();
8204   bool isThumb2 = Subtarget->isThumb2();
8205 
8206   unsigned PCLabelId = AFI->createPICLabelUId();
8207   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
8208   ARMConstantPoolValue *CPV =
8209     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
8210   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
8211 
8212   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
8213                                            : &ARM::GPRRegClass;
8214 
8215   // Grab constant pool and fixed stack memory operands.
8216   MachineMemOperand *CPMMO =
8217       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
8218                                MachineMemOperand::MOLoad, 4, 4);
8219 
8220   MachineMemOperand *FIMMOSt =
8221       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
8222                                MachineMemOperand::MOStore, 4, 4);
8223 
8224   // Load the address of the dispatch MBB into the jump buffer.
8225   if (isThumb2) {
8226     // Incoming value: jbuf
8227     //   ldr.n  r5, LCPI1_1
8228     //   orr    r5, r5, #1
8229     //   add    r5, pc
8230     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
8231     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8232     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
8233         .addConstantPoolIndex(CPI)
8234         .addMemOperand(CPMMO)
8235         .add(predOps(ARMCC::AL));
8236     // Set the low bit because of thumb mode.
8237     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8238     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8239         .addReg(NewVReg1, RegState::Kill)
8240         .addImm(0x01)
8241         .add(predOps(ARMCC::AL))
8242         .add(condCodeOp());
8243     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8244     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8245       .addReg(NewVReg2, RegState::Kill)
8246       .addImm(PCLabelId);
8247     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8248         .addReg(NewVReg3, RegState::Kill)
8249         .addFrameIndex(FI)
8250         .addImm(36) // &jbuf[1] :: pc
8251         .addMemOperand(FIMMOSt)
8252         .add(predOps(ARMCC::AL));
8253   } else if (isThumb) {
8254     // Incoming value: jbuf
8255     //   ldr.n  r1, LCPI1_4
8256     //   add    r1, pc
8257     //   mov    r2, #1
8258     //   orrs   r1, r2
8259     //   add    r2, $jbuf, #+4 ; &jbuf[1]
8260     //   str    r1, [r2]
8261     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8262     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8263         .addConstantPoolIndex(CPI)
8264         .addMemOperand(CPMMO)
8265         .add(predOps(ARMCC::AL));
8266     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8267     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8268       .addReg(NewVReg1, RegState::Kill)
8269       .addImm(PCLabelId);
8270     // Set the low bit because of thumb mode.
8271     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8272     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8273         .addReg(ARM::CPSR, RegState::Define)
8274         .addImm(1)
8275         .add(predOps(ARMCC::AL));
8276     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8277     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8278         .addReg(ARM::CPSR, RegState::Define)
8279         .addReg(NewVReg2, RegState::Kill)
8280         .addReg(NewVReg3, RegState::Kill)
8281         .add(predOps(ARMCC::AL));
8282     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8283     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8284             .addFrameIndex(FI)
8285             .addImm(36); // &jbuf[1] :: pc
8286     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8287         .addReg(NewVReg4, RegState::Kill)
8288         .addReg(NewVReg5, RegState::Kill)
8289         .addImm(0)
8290         .addMemOperand(FIMMOSt)
8291         .add(predOps(ARMCC::AL));
8292   } else {
8293     // Incoming value: jbuf
8294     //   ldr  r1, LCPI1_1
8295     //   add  r1, pc, r1
8296     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
8297     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8298     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
8299         .addConstantPoolIndex(CPI)
8300         .addImm(0)
8301         .addMemOperand(CPMMO)
8302         .add(predOps(ARMCC::AL));
8303     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8304     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
8305         .addReg(NewVReg1, RegState::Kill)
8306         .addImm(PCLabelId)
8307         .add(predOps(ARMCC::AL));
8308     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
8309         .addReg(NewVReg2, RegState::Kill)
8310         .addFrameIndex(FI)
8311         .addImm(36) // &jbuf[1] :: pc
8312         .addMemOperand(FIMMOSt)
8313         .add(predOps(ARMCC::AL));
8314   }
8315 }
8316 
8317 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
8318                                               MachineBasicBlock *MBB) const {
8319   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8320   DebugLoc dl = MI.getDebugLoc();
8321   MachineFunction *MF = MBB->getParent();
8322   MachineRegisterInfo *MRI = &MF->getRegInfo();
8323   MachineFrameInfo &MFI = MF->getFrameInfo();
8324   int FI = MFI.getFunctionContextIndex();
8325 
8326   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
8327                                                         : &ARM::GPRnopcRegClass;
8328 
8329   // Get a mapping of the call site numbers to all of the landing pads they're
8330   // associated with.
8331   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
8332   unsigned MaxCSNum = 0;
8333   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8334        ++BB) {
8335     if (!BB->isEHPad()) continue;
8336 
8337     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8338     // pad.
8339     for (MachineBasicBlock::iterator
8340            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8341       if (!II->isEHLabel()) continue;
8342 
8343       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8344       if (!MF->hasCallSiteLandingPad(Sym)) continue;
8345 
8346       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8347       for (SmallVectorImpl<unsigned>::iterator
8348              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8349            CSI != CSE; ++CSI) {
8350         CallSiteNumToLPad[*CSI].push_back(&*BB);
8351         MaxCSNum = std::max(MaxCSNum, *CSI);
8352       }
8353       break;
8354     }
8355   }
8356 
8357   // Get an ordered list of the machine basic blocks for the jump table.
8358   std::vector<MachineBasicBlock*> LPadList;
8359   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8360   LPadList.reserve(CallSiteNumToLPad.size());
8361   for (unsigned I = 1; I <= MaxCSNum; ++I) {
8362     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8363     for (SmallVectorImpl<MachineBasicBlock*>::iterator
8364            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8365       LPadList.push_back(*II);
8366       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8367     }
8368   }
8369 
8370   assert(!LPadList.empty() &&
8371          "No landing pad destinations for the dispatch jump table!");
8372 
8373   // Create the jump table and associated information.
8374   MachineJumpTableInfo *JTI =
8375     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8376   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8377 
8378   // Create the MBBs for the dispatch code.
8379 
8380   // Shove the dispatch's address into the return slot in the function context.
8381   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8382   DispatchBB->setIsEHPad();
8383 
8384   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8385   unsigned trap_opcode;
8386   if (Subtarget->isThumb())
8387     trap_opcode = ARM::tTRAP;
8388   else
8389     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8390 
8391   BuildMI(TrapBB, dl, TII->get(trap_opcode));
8392   DispatchBB->addSuccessor(TrapBB);
8393 
8394   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8395   DispatchBB->addSuccessor(DispContBB);
8396 
8397   // Insert and MBBs.
8398   MF->insert(MF->end(), DispatchBB);
8399   MF->insert(MF->end(), DispContBB);
8400   MF->insert(MF->end(), TrapBB);
8401 
8402   // Insert code into the entry block that creates and registers the function
8403   // context.
8404   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8405 
8406   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8407       MachinePointerInfo::getFixedStack(*MF, FI),
8408       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8409 
8410   MachineInstrBuilder MIB;
8411   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8412 
8413   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8414   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8415 
8416   // Add a register mask with no preserved registers.  This results in all
8417   // registers being marked as clobbered. This can't work if the dispatch block
8418   // is in a Thumb1 function and is linked with ARM code which uses the FP
8419   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8420   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8421 
8422   bool IsPositionIndependent = isPositionIndependent();
8423   unsigned NumLPads = LPadList.size();
8424   if (Subtarget->isThumb2()) {
8425     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8426     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8427         .addFrameIndex(FI)
8428         .addImm(4)
8429         .addMemOperand(FIMMOLd)
8430         .add(predOps(ARMCC::AL));
8431 
8432     if (NumLPads < 256) {
8433       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8434           .addReg(NewVReg1)
8435           .addImm(LPadList.size())
8436           .add(predOps(ARMCC::AL));
8437     } else {
8438       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8439       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8440           .addImm(NumLPads & 0xFFFF)
8441           .add(predOps(ARMCC::AL));
8442 
8443       unsigned VReg2 = VReg1;
8444       if ((NumLPads & 0xFFFF0000) != 0) {
8445         VReg2 = MRI->createVirtualRegister(TRC);
8446         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8447             .addReg(VReg1)
8448             .addImm(NumLPads >> 16)
8449             .add(predOps(ARMCC::AL));
8450       }
8451 
8452       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8453           .addReg(NewVReg1)
8454           .addReg(VReg2)
8455           .add(predOps(ARMCC::AL));
8456     }
8457 
8458     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8459       .addMBB(TrapBB)
8460       .addImm(ARMCC::HI)
8461       .addReg(ARM::CPSR);
8462 
8463     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8464     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8465         .addJumpTableIndex(MJTI)
8466         .add(predOps(ARMCC::AL));
8467 
8468     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8469     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8470         .addReg(NewVReg3, RegState::Kill)
8471         .addReg(NewVReg1)
8472         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8473         .add(predOps(ARMCC::AL))
8474         .add(condCodeOp());
8475 
8476     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8477       .addReg(NewVReg4, RegState::Kill)
8478       .addReg(NewVReg1)
8479       .addJumpTableIndex(MJTI);
8480   } else if (Subtarget->isThumb()) {
8481     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8482     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8483         .addFrameIndex(FI)
8484         .addImm(1)
8485         .addMemOperand(FIMMOLd)
8486         .add(predOps(ARMCC::AL));
8487 
8488     if (NumLPads < 256) {
8489       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8490           .addReg(NewVReg1)
8491           .addImm(NumLPads)
8492           .add(predOps(ARMCC::AL));
8493     } else {
8494       MachineConstantPool *ConstantPool = MF->getConstantPool();
8495       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8496       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8497 
8498       // MachineConstantPool wants an explicit alignment.
8499       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8500       if (Align == 0)
8501         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8502       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8503 
8504       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8505       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8506           .addReg(VReg1, RegState::Define)
8507           .addConstantPoolIndex(Idx)
8508           .add(predOps(ARMCC::AL));
8509       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8510           .addReg(NewVReg1)
8511           .addReg(VReg1)
8512           .add(predOps(ARMCC::AL));
8513     }
8514 
8515     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8516       .addMBB(TrapBB)
8517       .addImm(ARMCC::HI)
8518       .addReg(ARM::CPSR);
8519 
8520     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8521     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8522         .addReg(ARM::CPSR, RegState::Define)
8523         .addReg(NewVReg1)
8524         .addImm(2)
8525         .add(predOps(ARMCC::AL));
8526 
8527     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8528     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8529         .addJumpTableIndex(MJTI)
8530         .add(predOps(ARMCC::AL));
8531 
8532     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8533     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8534         .addReg(ARM::CPSR, RegState::Define)
8535         .addReg(NewVReg2, RegState::Kill)
8536         .addReg(NewVReg3)
8537         .add(predOps(ARMCC::AL));
8538 
8539     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8540         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8541 
8542     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8543     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8544         .addReg(NewVReg4, RegState::Kill)
8545         .addImm(0)
8546         .addMemOperand(JTMMOLd)
8547         .add(predOps(ARMCC::AL));
8548 
8549     unsigned NewVReg6 = NewVReg5;
8550     if (IsPositionIndependent) {
8551       NewVReg6 = MRI->createVirtualRegister(TRC);
8552       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8553           .addReg(ARM::CPSR, RegState::Define)
8554           .addReg(NewVReg5, RegState::Kill)
8555           .addReg(NewVReg3)
8556           .add(predOps(ARMCC::AL));
8557     }
8558 
8559     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8560       .addReg(NewVReg6, RegState::Kill)
8561       .addJumpTableIndex(MJTI);
8562   } else {
8563     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8564     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8565         .addFrameIndex(FI)
8566         .addImm(4)
8567         .addMemOperand(FIMMOLd)
8568         .add(predOps(ARMCC::AL));
8569 
8570     if (NumLPads < 256) {
8571       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8572           .addReg(NewVReg1)
8573           .addImm(NumLPads)
8574           .add(predOps(ARMCC::AL));
8575     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8576       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8577       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8578           .addImm(NumLPads & 0xFFFF)
8579           .add(predOps(ARMCC::AL));
8580 
8581       unsigned VReg2 = VReg1;
8582       if ((NumLPads & 0xFFFF0000) != 0) {
8583         VReg2 = MRI->createVirtualRegister(TRC);
8584         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8585             .addReg(VReg1)
8586             .addImm(NumLPads >> 16)
8587             .add(predOps(ARMCC::AL));
8588       }
8589 
8590       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8591           .addReg(NewVReg1)
8592           .addReg(VReg2)
8593           .add(predOps(ARMCC::AL));
8594     } else {
8595       MachineConstantPool *ConstantPool = MF->getConstantPool();
8596       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8597       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8598 
8599       // MachineConstantPool wants an explicit alignment.
8600       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8601       if (Align == 0)
8602         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8603       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8604 
8605       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8606       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8607           .addReg(VReg1, RegState::Define)
8608           .addConstantPoolIndex(Idx)
8609           .addImm(0)
8610           .add(predOps(ARMCC::AL));
8611       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8612           .addReg(NewVReg1)
8613           .addReg(VReg1, RegState::Kill)
8614           .add(predOps(ARMCC::AL));
8615     }
8616 
8617     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8618       .addMBB(TrapBB)
8619       .addImm(ARMCC::HI)
8620       .addReg(ARM::CPSR);
8621 
8622     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8623     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8624         .addReg(NewVReg1)
8625         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8626         .add(predOps(ARMCC::AL))
8627         .add(condCodeOp());
8628     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8629     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8630         .addJumpTableIndex(MJTI)
8631         .add(predOps(ARMCC::AL));
8632 
8633     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8634         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8635     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8636     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8637         .addReg(NewVReg3, RegState::Kill)
8638         .addReg(NewVReg4)
8639         .addImm(0)
8640         .addMemOperand(JTMMOLd)
8641         .add(predOps(ARMCC::AL));
8642 
8643     if (IsPositionIndependent) {
8644       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8645         .addReg(NewVReg5, RegState::Kill)
8646         .addReg(NewVReg4)
8647         .addJumpTableIndex(MJTI);
8648     } else {
8649       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8650         .addReg(NewVReg5, RegState::Kill)
8651         .addJumpTableIndex(MJTI);
8652     }
8653   }
8654 
8655   // Add the jump table entries as successors to the MBB.
8656   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8657   for (std::vector<MachineBasicBlock*>::iterator
8658          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8659     MachineBasicBlock *CurMBB = *I;
8660     if (SeenMBBs.insert(CurMBB).second)
8661       DispContBB->addSuccessor(CurMBB);
8662   }
8663 
8664   // N.B. the order the invoke BBs are processed in doesn't matter here.
8665   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8666   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8667   for (MachineBasicBlock *BB : InvokeBBs) {
8668 
8669     // Remove the landing pad successor from the invoke block and replace it
8670     // with the new dispatch block.
8671     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8672                                                   BB->succ_end());
8673     while (!Successors.empty()) {
8674       MachineBasicBlock *SMBB = Successors.pop_back_val();
8675       if (SMBB->isEHPad()) {
8676         BB->removeSuccessor(SMBB);
8677         MBBLPads.push_back(SMBB);
8678       }
8679     }
8680 
8681     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8682     BB->normalizeSuccProbs();
8683 
8684     // Find the invoke call and mark all of the callee-saved registers as
8685     // 'implicit defined' so that they're spilled. This prevents code from
8686     // moving instructions to before the EH block, where they will never be
8687     // executed.
8688     for (MachineBasicBlock::reverse_iterator
8689            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8690       if (!II->isCall()) continue;
8691 
8692       DenseMap<unsigned, bool> DefRegs;
8693       for (MachineInstr::mop_iterator
8694              OI = II->operands_begin(), OE = II->operands_end();
8695            OI != OE; ++OI) {
8696         if (!OI->isReg()) continue;
8697         DefRegs[OI->getReg()] = true;
8698       }
8699 
8700       MachineInstrBuilder MIB(*MF, &*II);
8701 
8702       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8703         unsigned Reg = SavedRegs[i];
8704         if (Subtarget->isThumb2() &&
8705             !ARM::tGPRRegClass.contains(Reg) &&
8706             !ARM::hGPRRegClass.contains(Reg))
8707           continue;
8708         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8709           continue;
8710         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8711           continue;
8712         if (!DefRegs[Reg])
8713           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8714       }
8715 
8716       break;
8717     }
8718   }
8719 
8720   // Mark all former landing pads as non-landing pads. The dispatch is the only
8721   // landing pad now.
8722   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8723          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8724     (*I)->setIsEHPad(false);
8725 
8726   // The instruction is gone now.
8727   MI.eraseFromParent();
8728 }
8729 
8730 static
8731 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8732   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8733        E = MBB->succ_end(); I != E; ++I)
8734     if (*I != Succ)
8735       return *I;
8736   llvm_unreachable("Expecting a BB with two successors!");
8737 }
8738 
8739 /// Return the load opcode for a given load size. If load size >= 8,
8740 /// neon opcode will be returned.
8741 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8742   if (LdSize >= 8)
8743     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8744                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8745   if (IsThumb1)
8746     return LdSize == 4 ? ARM::tLDRi
8747                        : LdSize == 2 ? ARM::tLDRHi
8748                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8749   if (IsThumb2)
8750     return LdSize == 4 ? ARM::t2LDR_POST
8751                        : LdSize == 2 ? ARM::t2LDRH_POST
8752                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8753   return LdSize == 4 ? ARM::LDR_POST_IMM
8754                      : LdSize == 2 ? ARM::LDRH_POST
8755                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8756 }
8757 
8758 /// Return the store opcode for a given store size. If store size >= 8,
8759 /// neon opcode will be returned.
8760 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8761   if (StSize >= 8)
8762     return StSize == 16 ? ARM::VST1q32wb_fixed
8763                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8764   if (IsThumb1)
8765     return StSize == 4 ? ARM::tSTRi
8766                        : StSize == 2 ? ARM::tSTRHi
8767                                      : StSize == 1 ? ARM::tSTRBi : 0;
8768   if (IsThumb2)
8769     return StSize == 4 ? ARM::t2STR_POST
8770                        : StSize == 2 ? ARM::t2STRH_POST
8771                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8772   return StSize == 4 ? ARM::STR_POST_IMM
8773                      : StSize == 2 ? ARM::STRH_POST
8774                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8775 }
8776 
8777 /// Emit a post-increment load operation with given size. The instructions
8778 /// will be added to BB at Pos.
8779 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8780                        const TargetInstrInfo *TII, const DebugLoc &dl,
8781                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8782                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8783   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8784   assert(LdOpc != 0 && "Should have a load opcode");
8785   if (LdSize >= 8) {
8786     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8787         .addReg(AddrOut, RegState::Define)
8788         .addReg(AddrIn)
8789         .addImm(0)
8790         .add(predOps(ARMCC::AL));
8791   } else if (IsThumb1) {
8792     // load + update AddrIn
8793     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8794         .addReg(AddrIn)
8795         .addImm(0)
8796         .add(predOps(ARMCC::AL));
8797     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8798         .add(t1CondCodeOp())
8799         .addReg(AddrIn)
8800         .addImm(LdSize)
8801         .add(predOps(ARMCC::AL));
8802   } else if (IsThumb2) {
8803     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8804         .addReg(AddrOut, RegState::Define)
8805         .addReg(AddrIn)
8806         .addImm(LdSize)
8807         .add(predOps(ARMCC::AL));
8808   } else { // arm
8809     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8810         .addReg(AddrOut, RegState::Define)
8811         .addReg(AddrIn)
8812         .addReg(0)
8813         .addImm(LdSize)
8814         .add(predOps(ARMCC::AL));
8815   }
8816 }
8817 
8818 /// Emit a post-increment store operation with given size. The instructions
8819 /// will be added to BB at Pos.
8820 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8821                        const TargetInstrInfo *TII, const DebugLoc &dl,
8822                        unsigned StSize, unsigned Data, unsigned AddrIn,
8823                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8824   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8825   assert(StOpc != 0 && "Should have a store opcode");
8826   if (StSize >= 8) {
8827     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8828         .addReg(AddrIn)
8829         .addImm(0)
8830         .addReg(Data)
8831         .add(predOps(ARMCC::AL));
8832   } else if (IsThumb1) {
8833     // store + update AddrIn
8834     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8835         .addReg(Data)
8836         .addReg(AddrIn)
8837         .addImm(0)
8838         .add(predOps(ARMCC::AL));
8839     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8840         .add(t1CondCodeOp())
8841         .addReg(AddrIn)
8842         .addImm(StSize)
8843         .add(predOps(ARMCC::AL));
8844   } else if (IsThumb2) {
8845     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8846         .addReg(Data)
8847         .addReg(AddrIn)
8848         .addImm(StSize)
8849         .add(predOps(ARMCC::AL));
8850   } else { // arm
8851     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8852         .addReg(Data)
8853         .addReg(AddrIn)
8854         .addReg(0)
8855         .addImm(StSize)
8856         .add(predOps(ARMCC::AL));
8857   }
8858 }
8859 
8860 MachineBasicBlock *
8861 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8862                                    MachineBasicBlock *BB) const {
8863   // This pseudo instruction has 3 operands: dst, src, size
8864   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8865   // Otherwise, we will generate unrolled scalar copies.
8866   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8867   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8868   MachineFunction::iterator It = ++BB->getIterator();
8869 
8870   unsigned dest = MI.getOperand(0).getReg();
8871   unsigned src = MI.getOperand(1).getReg();
8872   unsigned SizeVal = MI.getOperand(2).getImm();
8873   unsigned Align = MI.getOperand(3).getImm();
8874   DebugLoc dl = MI.getDebugLoc();
8875 
8876   MachineFunction *MF = BB->getParent();
8877   MachineRegisterInfo &MRI = MF->getRegInfo();
8878   unsigned UnitSize = 0;
8879   const TargetRegisterClass *TRC = nullptr;
8880   const TargetRegisterClass *VecTRC = nullptr;
8881 
8882   bool IsThumb1 = Subtarget->isThumb1Only();
8883   bool IsThumb2 = Subtarget->isThumb2();
8884   bool IsThumb = Subtarget->isThumb();
8885 
8886   if (Align & 1) {
8887     UnitSize = 1;
8888   } else if (Align & 2) {
8889     UnitSize = 2;
8890   } else {
8891     // Check whether we can use NEON instructions.
8892     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
8893         Subtarget->hasNEON()) {
8894       if ((Align % 16 == 0) && SizeVal >= 16)
8895         UnitSize = 16;
8896       else if ((Align % 8 == 0) && SizeVal >= 8)
8897         UnitSize = 8;
8898     }
8899     // Can't use NEON instructions.
8900     if (UnitSize == 0)
8901       UnitSize = 4;
8902   }
8903 
8904   // Select the correct opcode and register class for unit size load/store
8905   bool IsNeon = UnitSize >= 8;
8906   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8907   if (IsNeon)
8908     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8909                             : UnitSize == 8 ? &ARM::DPRRegClass
8910                                             : nullptr;
8911 
8912   unsigned BytesLeft = SizeVal % UnitSize;
8913   unsigned LoopSize = SizeVal - BytesLeft;
8914 
8915   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8916     // Use LDR and STR to copy.
8917     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8918     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8919     unsigned srcIn = src;
8920     unsigned destIn = dest;
8921     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8922       unsigned srcOut = MRI.createVirtualRegister(TRC);
8923       unsigned destOut = MRI.createVirtualRegister(TRC);
8924       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8925       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8926                  IsThumb1, IsThumb2);
8927       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8928                  IsThumb1, IsThumb2);
8929       srcIn = srcOut;
8930       destIn = destOut;
8931     }
8932 
8933     // Handle the leftover bytes with LDRB and STRB.
8934     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8935     // [destOut] = STRB_POST(scratch, destIn, 1)
8936     for (unsigned i = 0; i < BytesLeft; i++) {
8937       unsigned srcOut = MRI.createVirtualRegister(TRC);
8938       unsigned destOut = MRI.createVirtualRegister(TRC);
8939       unsigned scratch = MRI.createVirtualRegister(TRC);
8940       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8941                  IsThumb1, IsThumb2);
8942       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8943                  IsThumb1, IsThumb2);
8944       srcIn = srcOut;
8945       destIn = destOut;
8946     }
8947     MI.eraseFromParent(); // The instruction is gone now.
8948     return BB;
8949   }
8950 
8951   // Expand the pseudo op to a loop.
8952   // thisMBB:
8953   //   ...
8954   //   movw varEnd, # --> with thumb2
8955   //   movt varEnd, #
8956   //   ldrcp varEnd, idx --> without thumb2
8957   //   fallthrough --> loopMBB
8958   // loopMBB:
8959   //   PHI varPhi, varEnd, varLoop
8960   //   PHI srcPhi, src, srcLoop
8961   //   PHI destPhi, dst, destLoop
8962   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8963   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8964   //   subs varLoop, varPhi, #UnitSize
8965   //   bne loopMBB
8966   //   fallthrough --> exitMBB
8967   // exitMBB:
8968   //   epilogue to handle left-over bytes
8969   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8970   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8971   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8972   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8973   MF->insert(It, loopMBB);
8974   MF->insert(It, exitMBB);
8975 
8976   // Transfer the remainder of BB and its successor edges to exitMBB.
8977   exitMBB->splice(exitMBB->begin(), BB,
8978                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8979   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8980 
8981   // Load an immediate to varEnd.
8982   unsigned varEnd = MRI.createVirtualRegister(TRC);
8983   if (Subtarget->useMovt(*MF)) {
8984     unsigned Vtmp = varEnd;
8985     if ((LoopSize & 0xFFFF0000) != 0)
8986       Vtmp = MRI.createVirtualRegister(TRC);
8987     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8988         .addImm(LoopSize & 0xFFFF)
8989         .add(predOps(ARMCC::AL));
8990 
8991     if ((LoopSize & 0xFFFF0000) != 0)
8992       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8993           .addReg(Vtmp)
8994           .addImm(LoopSize >> 16)
8995           .add(predOps(ARMCC::AL));
8996   } else {
8997     MachineConstantPool *ConstantPool = MF->getConstantPool();
8998     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8999     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
9000 
9001     // MachineConstantPool wants an explicit alignment.
9002     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9003     if (Align == 0)
9004       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9005     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9006 
9007     if (IsThumb)
9008       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
9009           .addReg(varEnd, RegState::Define)
9010           .addConstantPoolIndex(Idx)
9011           .add(predOps(ARMCC::AL));
9012     else
9013       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
9014           .addReg(varEnd, RegState::Define)
9015           .addConstantPoolIndex(Idx)
9016           .addImm(0)
9017           .add(predOps(ARMCC::AL));
9018   }
9019   BB->addSuccessor(loopMBB);
9020 
9021   // Generate the loop body:
9022   //   varPhi = PHI(varLoop, varEnd)
9023   //   srcPhi = PHI(srcLoop, src)
9024   //   destPhi = PHI(destLoop, dst)
9025   MachineBasicBlock *entryBB = BB;
9026   BB = loopMBB;
9027   unsigned varLoop = MRI.createVirtualRegister(TRC);
9028   unsigned varPhi = MRI.createVirtualRegister(TRC);
9029   unsigned srcLoop = MRI.createVirtualRegister(TRC);
9030   unsigned srcPhi = MRI.createVirtualRegister(TRC);
9031   unsigned destLoop = MRI.createVirtualRegister(TRC);
9032   unsigned destPhi = MRI.createVirtualRegister(TRC);
9033 
9034   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
9035     .addReg(varLoop).addMBB(loopMBB)
9036     .addReg(varEnd).addMBB(entryBB);
9037   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
9038     .addReg(srcLoop).addMBB(loopMBB)
9039     .addReg(src).addMBB(entryBB);
9040   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
9041     .addReg(destLoop).addMBB(loopMBB)
9042     .addReg(dest).addMBB(entryBB);
9043 
9044   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9045   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
9046   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9047   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
9048              IsThumb1, IsThumb2);
9049   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
9050              IsThumb1, IsThumb2);
9051 
9052   // Decrement loop variable by UnitSize.
9053   if (IsThumb1) {
9054     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
9055         .add(t1CondCodeOp())
9056         .addReg(varPhi)
9057         .addImm(UnitSize)
9058         .add(predOps(ARMCC::AL));
9059   } else {
9060     MachineInstrBuilder MIB =
9061         BuildMI(*BB, BB->end(), dl,
9062                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
9063     MIB.addReg(varPhi)
9064         .addImm(UnitSize)
9065         .add(predOps(ARMCC::AL))
9066         .add(condCodeOp());
9067     MIB->getOperand(5).setReg(ARM::CPSR);
9068     MIB->getOperand(5).setIsDef(true);
9069   }
9070   BuildMI(*BB, BB->end(), dl,
9071           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
9072       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
9073 
9074   // loopMBB can loop back to loopMBB or fall through to exitMBB.
9075   BB->addSuccessor(loopMBB);
9076   BB->addSuccessor(exitMBB);
9077 
9078   // Add epilogue to handle BytesLeft.
9079   BB = exitMBB;
9080   auto StartOfExit = exitMBB->begin();
9081 
9082   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9083   //   [destOut] = STRB_POST(scratch, destLoop, 1)
9084   unsigned srcIn = srcLoop;
9085   unsigned destIn = destLoop;
9086   for (unsigned i = 0; i < BytesLeft; i++) {
9087     unsigned srcOut = MRI.createVirtualRegister(TRC);
9088     unsigned destOut = MRI.createVirtualRegister(TRC);
9089     unsigned scratch = MRI.createVirtualRegister(TRC);
9090     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
9091                IsThumb1, IsThumb2);
9092     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
9093                IsThumb1, IsThumb2);
9094     srcIn = srcOut;
9095     destIn = destOut;
9096   }
9097 
9098   MI.eraseFromParent(); // The instruction is gone now.
9099   return BB;
9100 }
9101 
9102 MachineBasicBlock *
9103 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
9104                                        MachineBasicBlock *MBB) const {
9105   const TargetMachine &TM = getTargetMachine();
9106   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
9107   DebugLoc DL = MI.getDebugLoc();
9108 
9109   assert(Subtarget->isTargetWindows() &&
9110          "__chkstk is only supported on Windows");
9111   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
9112 
9113   // __chkstk takes the number of words to allocate on the stack in R4, and
9114   // returns the stack adjustment in number of bytes in R4.  This will not
9115   // clober any other registers (other than the obvious lr).
9116   //
9117   // Although, technically, IP should be considered a register which may be
9118   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
9119   // thumb-2 environment, so there is no interworking required.  As a result, we
9120   // do not expect a veneer to be emitted by the linker, clobbering IP.
9121   //
9122   // Each module receives its own copy of __chkstk, so no import thunk is
9123   // required, again, ensuring that IP is not clobbered.
9124   //
9125   // Finally, although some linkers may theoretically provide a trampoline for
9126   // out of range calls (which is quite common due to a 32M range limitation of
9127   // branches for Thumb), we can generate the long-call version via
9128   // -mcmodel=large, alleviating the need for the trampoline which may clobber
9129   // IP.
9130 
9131   switch (TM.getCodeModel()) {
9132   case CodeModel::Tiny:
9133     llvm_unreachable("Tiny code model not available on ARM.");
9134   case CodeModel::Small:
9135   case CodeModel::Medium:
9136   case CodeModel::Kernel:
9137     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
9138         .add(predOps(ARMCC::AL))
9139         .addExternalSymbol("__chkstk")
9140         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9141         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9142         .addReg(ARM::R12,
9143                 RegState::Implicit | RegState::Define | RegState::Dead)
9144         .addReg(ARM::CPSR,
9145                 RegState::Implicit | RegState::Define | RegState::Dead);
9146     break;
9147   case CodeModel::Large: {
9148     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9149     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
9150 
9151     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
9152       .addExternalSymbol("__chkstk");
9153     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
9154         .add(predOps(ARMCC::AL))
9155         .addReg(Reg, RegState::Kill)
9156         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9157         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9158         .addReg(ARM::R12,
9159                 RegState::Implicit | RegState::Define | RegState::Dead)
9160         .addReg(ARM::CPSR,
9161                 RegState::Implicit | RegState::Define | RegState::Dead);
9162     break;
9163   }
9164   }
9165 
9166   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
9167       .addReg(ARM::SP, RegState::Kill)
9168       .addReg(ARM::R4, RegState::Kill)
9169       .setMIFlags(MachineInstr::FrameSetup)
9170       .add(predOps(ARMCC::AL))
9171       .add(condCodeOp());
9172 
9173   MI.eraseFromParent();
9174   return MBB;
9175 }
9176 
9177 MachineBasicBlock *
9178 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
9179                                        MachineBasicBlock *MBB) const {
9180   DebugLoc DL = MI.getDebugLoc();
9181   MachineFunction *MF = MBB->getParent();
9182   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9183 
9184   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
9185   MF->insert(++MBB->getIterator(), ContBB);
9186   ContBB->splice(ContBB->begin(), MBB,
9187                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9188   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
9189   MBB->addSuccessor(ContBB);
9190 
9191   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9192   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
9193   MF->push_back(TrapBB);
9194   MBB->addSuccessor(TrapBB);
9195 
9196   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
9197       .addReg(MI.getOperand(0).getReg())
9198       .addImm(0)
9199       .add(predOps(ARMCC::AL));
9200   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
9201       .addMBB(TrapBB)
9202       .addImm(ARMCC::EQ)
9203       .addReg(ARM::CPSR);
9204 
9205   MI.eraseFromParent();
9206   return ContBB;
9207 }
9208 
9209 // The CPSR operand of SelectItr might be missing a kill marker
9210 // because there were multiple uses of CPSR, and ISel didn't know
9211 // which to mark. Figure out whether SelectItr should have had a
9212 // kill marker, and set it if it should. Returns the correct kill
9213 // marker value.
9214 static bool checkAndUpdateCPSRKill(MachineBasicBlock::iterator SelectItr,
9215                                    MachineBasicBlock* BB,
9216                                    const TargetRegisterInfo* TRI) {
9217   // Scan forward through BB for a use/def of CPSR.
9218   MachineBasicBlock::iterator miI(std::next(SelectItr));
9219   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
9220     const MachineInstr& mi = *miI;
9221     if (mi.readsRegister(ARM::CPSR))
9222       return false;
9223     if (mi.definesRegister(ARM::CPSR))
9224       break; // Should have kill-flag - update below.
9225   }
9226 
9227   // If we hit the end of the block, check whether CPSR is live into a
9228   // successor.
9229   if (miI == BB->end()) {
9230     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
9231                                           sEnd = BB->succ_end();
9232          sItr != sEnd; ++sItr) {
9233       MachineBasicBlock* succ = *sItr;
9234       if (succ->isLiveIn(ARM::CPSR))
9235         return false;
9236     }
9237   }
9238 
9239   // We found a def, or hit the end of the basic block and CPSR wasn't live
9240   // out. SelectMI should have a kill flag on CPSR.
9241   SelectItr->addRegisterKilled(ARM::CPSR, TRI);
9242   return true;
9243 }
9244 
9245 MachineBasicBlock *
9246 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9247                                                MachineBasicBlock *BB) const {
9248   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9249   DebugLoc dl = MI.getDebugLoc();
9250   bool isThumb2 = Subtarget->isThumb2();
9251   switch (MI.getOpcode()) {
9252   default: {
9253     MI.print(errs());
9254     llvm_unreachable("Unexpected instr type to insert");
9255   }
9256 
9257   // Thumb1 post-indexed loads are really just single-register LDMs.
9258   case ARM::tLDR_postidx: {
9259     MachineOperand Def(MI.getOperand(1));
9260     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
9261         .add(Def)  // Rn_wb
9262         .add(MI.getOperand(2))  // Rn
9263         .add(MI.getOperand(3))  // PredImm
9264         .add(MI.getOperand(4))  // PredReg
9265         .add(MI.getOperand(0)); // Rt
9266     MI.eraseFromParent();
9267     return BB;
9268   }
9269 
9270   // The Thumb2 pre-indexed stores have the same MI operands, they just
9271   // define them differently in the .td files from the isel patterns, so
9272   // they need pseudos.
9273   case ARM::t2STR_preidx:
9274     MI.setDesc(TII->get(ARM::t2STR_PRE));
9275     return BB;
9276   case ARM::t2STRB_preidx:
9277     MI.setDesc(TII->get(ARM::t2STRB_PRE));
9278     return BB;
9279   case ARM::t2STRH_preidx:
9280     MI.setDesc(TII->get(ARM::t2STRH_PRE));
9281     return BB;
9282 
9283   case ARM::STRi_preidx:
9284   case ARM::STRBi_preidx: {
9285     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9286                                                          : ARM::STRB_PRE_IMM;
9287     // Decode the offset.
9288     unsigned Offset = MI.getOperand(4).getImm();
9289     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
9290     Offset = ARM_AM::getAM2Offset(Offset);
9291     if (isSub)
9292       Offset = -Offset;
9293 
9294     MachineMemOperand *MMO = *MI.memoperands_begin();
9295     BuildMI(*BB, MI, dl, TII->get(NewOpc))
9296         .add(MI.getOperand(0)) // Rn_wb
9297         .add(MI.getOperand(1)) // Rt
9298         .add(MI.getOperand(2)) // Rn
9299         .addImm(Offset)        // offset (skip GPR==zero_reg)
9300         .add(MI.getOperand(5)) // pred
9301         .add(MI.getOperand(6))
9302         .addMemOperand(MMO);
9303     MI.eraseFromParent();
9304     return BB;
9305   }
9306   case ARM::STRr_preidx:
9307   case ARM::STRBr_preidx:
9308   case ARM::STRH_preidx: {
9309     unsigned NewOpc;
9310     switch (MI.getOpcode()) {
9311     default: llvm_unreachable("unexpected opcode!");
9312     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
9313     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
9314     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
9315     }
9316     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
9317     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
9318       MIB.add(MI.getOperand(i));
9319     MI.eraseFromParent();
9320     return BB;
9321   }
9322 
9323   case ARM::tMOVCCr_pseudo: {
9324     // To "insert" a SELECT_CC instruction, we actually have to insert the
9325     // diamond control-flow pattern.  The incoming instruction knows the
9326     // destination vreg to set, the condition code register to branch on, the
9327     // true/false values to select between, and a branch opcode to use.
9328     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9329     MachineFunction::iterator It = ++BB->getIterator();
9330 
9331     //  thisMBB:
9332     //  ...
9333     //   TrueVal = ...
9334     //   cmpTY ccX, r1, r2
9335     //   bCC copy1MBB
9336     //   fallthrough --> copy0MBB
9337     MachineBasicBlock *thisMBB  = BB;
9338     MachineFunction *F = BB->getParent();
9339     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9340     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
9341     F->insert(It, copy0MBB);
9342     F->insert(It, sinkMBB);
9343 
9344     // Check whether CPSR is live past the tMOVCCr_pseudo.
9345     const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
9346     if (!MI.killsRegister(ARM::CPSR) &&
9347         !checkAndUpdateCPSRKill(MI, thisMBB, TRI)) {
9348       copy0MBB->addLiveIn(ARM::CPSR);
9349       sinkMBB->addLiveIn(ARM::CPSR);
9350     }
9351 
9352     // Transfer the remainder of BB and its successor edges to sinkMBB.
9353     sinkMBB->splice(sinkMBB->begin(), BB,
9354                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9355     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9356 
9357     BB->addSuccessor(copy0MBB);
9358     BB->addSuccessor(sinkMBB);
9359 
9360     BuildMI(BB, dl, TII->get(ARM::tBcc))
9361         .addMBB(sinkMBB)
9362         .addImm(MI.getOperand(3).getImm())
9363         .addReg(MI.getOperand(4).getReg());
9364 
9365     //  copy0MBB:
9366     //   %FalseValue = ...
9367     //   # fallthrough to sinkMBB
9368     BB = copy0MBB;
9369 
9370     // Update machine-CFG edges
9371     BB->addSuccessor(sinkMBB);
9372 
9373     //  sinkMBB:
9374     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9375     //  ...
9376     BB = sinkMBB;
9377     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
9378         .addReg(MI.getOperand(1).getReg())
9379         .addMBB(copy0MBB)
9380         .addReg(MI.getOperand(2).getReg())
9381         .addMBB(thisMBB);
9382 
9383     MI.eraseFromParent(); // The pseudo instruction is gone now.
9384     return BB;
9385   }
9386 
9387   case ARM::BCCi64:
9388   case ARM::BCCZi64: {
9389     // If there is an unconditional branch to the other successor, remove it.
9390     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9391 
9392     // Compare both parts that make up the double comparison separately for
9393     // equality.
9394     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9395 
9396     unsigned LHS1 = MI.getOperand(1).getReg();
9397     unsigned LHS2 = MI.getOperand(2).getReg();
9398     if (RHSisZero) {
9399       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9400           .addReg(LHS1)
9401           .addImm(0)
9402           .add(predOps(ARMCC::AL));
9403       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9404         .addReg(LHS2).addImm(0)
9405         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9406     } else {
9407       unsigned RHS1 = MI.getOperand(3).getReg();
9408       unsigned RHS2 = MI.getOperand(4).getReg();
9409       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9410           .addReg(LHS1)
9411           .addReg(RHS1)
9412           .add(predOps(ARMCC::AL));
9413       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9414         .addReg(LHS2).addReg(RHS2)
9415         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9416     }
9417 
9418     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9419     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9420     if (MI.getOperand(0).getImm() == ARMCC::NE)
9421       std::swap(destMBB, exitMBB);
9422 
9423     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9424       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9425     if (isThumb2)
9426       BuildMI(BB, dl, TII->get(ARM::t2B))
9427           .addMBB(exitMBB)
9428           .add(predOps(ARMCC::AL));
9429     else
9430       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9431 
9432     MI.eraseFromParent(); // The pseudo instruction is gone now.
9433     return BB;
9434   }
9435 
9436   case ARM::Int_eh_sjlj_setjmp:
9437   case ARM::Int_eh_sjlj_setjmp_nofp:
9438   case ARM::tInt_eh_sjlj_setjmp:
9439   case ARM::t2Int_eh_sjlj_setjmp:
9440   case ARM::t2Int_eh_sjlj_setjmp_nofp:
9441     return BB;
9442 
9443   case ARM::Int_eh_sjlj_setup_dispatch:
9444     EmitSjLjDispatchBlock(MI, BB);
9445     return BB;
9446 
9447   case ARM::ABS:
9448   case ARM::t2ABS: {
9449     // To insert an ABS instruction, we have to insert the
9450     // diamond control-flow pattern.  The incoming instruction knows the
9451     // source vreg to test against 0, the destination vreg to set,
9452     // the condition code register to branch on, the
9453     // true/false values to select between, and a branch opcode to use.
9454     // It transforms
9455     //     V1 = ABS V0
9456     // into
9457     //     V2 = MOVS V0
9458     //     BCC                      (branch to SinkBB if V0 >= 0)
9459     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
9460     //     SinkBB: V1 = PHI(V2, V3)
9461     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9462     MachineFunction::iterator BBI = ++BB->getIterator();
9463     MachineFunction *Fn = BB->getParent();
9464     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9465     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
9466     Fn->insert(BBI, RSBBB);
9467     Fn->insert(BBI, SinkBB);
9468 
9469     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9470     unsigned int ABSDstReg = MI.getOperand(0).getReg();
9471     bool ABSSrcKIll = MI.getOperand(1).isKill();
9472     bool isThumb2 = Subtarget->isThumb2();
9473     MachineRegisterInfo &MRI = Fn->getRegInfo();
9474     // In Thumb mode S must not be specified if source register is the SP or
9475     // PC and if destination register is the SP, so restrict register class
9476     unsigned NewRsbDstReg =
9477       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9478 
9479     // Transfer the remainder of BB and its successor edges to sinkMBB.
9480     SinkBB->splice(SinkBB->begin(), BB,
9481                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9482     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9483 
9484     BB->addSuccessor(RSBBB);
9485     BB->addSuccessor(SinkBB);
9486 
9487     // fall through to SinkMBB
9488     RSBBB->addSuccessor(SinkBB);
9489 
9490     // insert a cmp at the end of BB
9491     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9492         .addReg(ABSSrcReg)
9493         .addImm(0)
9494         .add(predOps(ARMCC::AL));
9495 
9496     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9497     BuildMI(BB, dl,
9498       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9499       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9500 
9501     // insert rsbri in RSBBB
9502     // Note: BCC and rsbri will be converted into predicated rsbmi
9503     // by if-conversion pass
9504     BuildMI(*RSBBB, RSBBB->begin(), dl,
9505             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9506         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9507         .addImm(0)
9508         .add(predOps(ARMCC::AL))
9509         .add(condCodeOp());
9510 
9511     // insert PHI in SinkBB,
9512     // reuse ABSDstReg to not change uses of ABS instruction
9513     BuildMI(*SinkBB, SinkBB->begin(), dl,
9514       TII->get(ARM::PHI), ABSDstReg)
9515       .addReg(NewRsbDstReg).addMBB(RSBBB)
9516       .addReg(ABSSrcReg).addMBB(BB);
9517 
9518     // remove ABS instruction
9519     MI.eraseFromParent();
9520 
9521     // return last added BB
9522     return SinkBB;
9523   }
9524   case ARM::COPY_STRUCT_BYVAL_I32:
9525     ++NumLoopByVals;
9526     return EmitStructByval(MI, BB);
9527   case ARM::WIN__CHKSTK:
9528     return EmitLowered__chkstk(MI, BB);
9529   case ARM::WIN__DBZCHK:
9530     return EmitLowered__dbzchk(MI, BB);
9531   }
9532 }
9533 
9534 /// Attaches vregs to MEMCPY that it will use as scratch registers
9535 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9536 /// instead of as a custom inserter because we need the use list from the SDNode.
9537 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9538                                     MachineInstr &MI, const SDNode *Node) {
9539   bool isThumb1 = Subtarget->isThumb1Only();
9540 
9541   DebugLoc DL = MI.getDebugLoc();
9542   MachineFunction *MF = MI.getParent()->getParent();
9543   MachineRegisterInfo &MRI = MF->getRegInfo();
9544   MachineInstrBuilder MIB(*MF, MI);
9545 
9546   // If the new dst/src is unused mark it as dead.
9547   if (!Node->hasAnyUseOfValue(0)) {
9548     MI.getOperand(0).setIsDead(true);
9549   }
9550   if (!Node->hasAnyUseOfValue(1)) {
9551     MI.getOperand(1).setIsDead(true);
9552   }
9553 
9554   // The MEMCPY both defines and kills the scratch registers.
9555   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9556     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9557                                                          : &ARM::GPRRegClass);
9558     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9559   }
9560 }
9561 
9562 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9563                                                       SDNode *Node) const {
9564   if (MI.getOpcode() == ARM::MEMCPY) {
9565     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9566     return;
9567   }
9568 
9569   const MCInstrDesc *MCID = &MI.getDesc();
9570   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9571   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9572   // operand is still set to noreg. If needed, set the optional operand's
9573   // register to CPSR, and remove the redundant implicit def.
9574   //
9575   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
9576 
9577   // Rename pseudo opcodes.
9578   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9579   unsigned ccOutIdx;
9580   if (NewOpc) {
9581     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9582     MCID = &TII->get(NewOpc);
9583 
9584     assert(MCID->getNumOperands() ==
9585            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9586         && "converted opcode should be the same except for cc_out"
9587            " (and, on Thumb1, pred)");
9588 
9589     MI.setDesc(*MCID);
9590 
9591     // Add the optional cc_out operand
9592     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9593 
9594     // On Thumb1, move all input operands to the end, then add the predicate
9595     if (Subtarget->isThumb1Only()) {
9596       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9597         MI.addOperand(MI.getOperand(1));
9598         MI.RemoveOperand(1);
9599       }
9600 
9601       // Restore the ties
9602       for (unsigned i = MI.getNumOperands(); i--;) {
9603         const MachineOperand& op = MI.getOperand(i);
9604         if (op.isReg() && op.isUse()) {
9605           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9606           if (DefIdx != -1)
9607             MI.tieOperands(DefIdx, i);
9608         }
9609       }
9610 
9611       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9612       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9613       ccOutIdx = 1;
9614     } else
9615       ccOutIdx = MCID->getNumOperands() - 1;
9616   } else
9617     ccOutIdx = MCID->getNumOperands() - 1;
9618 
9619   // Any ARM instruction that sets the 's' bit should specify an optional
9620   // "cc_out" operand in the last operand position.
9621   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9622     assert(!NewOpc && "Optional cc_out operand required");
9623     return;
9624   }
9625   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9626   // since we already have an optional CPSR def.
9627   bool definesCPSR = false;
9628   bool deadCPSR = false;
9629   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9630        ++i) {
9631     const MachineOperand &MO = MI.getOperand(i);
9632     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9633       definesCPSR = true;
9634       if (MO.isDead())
9635         deadCPSR = true;
9636       MI.RemoveOperand(i);
9637       break;
9638     }
9639   }
9640   if (!definesCPSR) {
9641     assert(!NewOpc && "Optional cc_out operand required");
9642     return;
9643   }
9644   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9645   if (deadCPSR) {
9646     assert(!MI.getOperand(ccOutIdx).getReg() &&
9647            "expect uninitialized optional cc_out operand");
9648     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9649     if (!Subtarget->isThumb1Only())
9650       return;
9651   }
9652 
9653   // If this instruction was defined with an optional CPSR def and its dag node
9654   // had a live implicit CPSR def, then activate the optional CPSR def.
9655   MachineOperand &MO = MI.getOperand(ccOutIdx);
9656   MO.setReg(ARM::CPSR);
9657   MO.setIsDef(true);
9658 }
9659 
9660 //===----------------------------------------------------------------------===//
9661 //                           ARM Optimization Hooks
9662 //===----------------------------------------------------------------------===//
9663 
9664 // Helper function that checks if N is a null or all ones constant.
9665 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9666   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9667 }
9668 
9669 // Return true if N is conditionally 0 or all ones.
9670 // Detects these expressions where cc is an i1 value:
9671 //
9672 //   (select cc 0, y)   [AllOnes=0]
9673 //   (select cc y, 0)   [AllOnes=0]
9674 //   (zext cc)          [AllOnes=0]
9675 //   (sext cc)          [AllOnes=0/1]
9676 //   (select cc -1, y)  [AllOnes=1]
9677 //   (select cc y, -1)  [AllOnes=1]
9678 //
9679 // Invert is set when N is the null/all ones constant when CC is false.
9680 // OtherOp is set to the alternative value of N.
9681 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9682                                        SDValue &CC, bool &Invert,
9683                                        SDValue &OtherOp,
9684                                        SelectionDAG &DAG) {
9685   switch (N->getOpcode()) {
9686   default: return false;
9687   case ISD::SELECT: {
9688     CC = N->getOperand(0);
9689     SDValue N1 = N->getOperand(1);
9690     SDValue N2 = N->getOperand(2);
9691     if (isZeroOrAllOnes(N1, AllOnes)) {
9692       Invert = false;
9693       OtherOp = N2;
9694       return true;
9695     }
9696     if (isZeroOrAllOnes(N2, AllOnes)) {
9697       Invert = true;
9698       OtherOp = N1;
9699       return true;
9700     }
9701     return false;
9702   }
9703   case ISD::ZERO_EXTEND:
9704     // (zext cc) can never be the all ones value.
9705     if (AllOnes)
9706       return false;
9707     LLVM_FALLTHROUGH;
9708   case ISD::SIGN_EXTEND: {
9709     SDLoc dl(N);
9710     EVT VT = N->getValueType(0);
9711     CC = N->getOperand(0);
9712     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9713       return false;
9714     Invert = !AllOnes;
9715     if (AllOnes)
9716       // When looking for an AllOnes constant, N is an sext, and the 'other'
9717       // value is 0.
9718       OtherOp = DAG.getConstant(0, dl, VT);
9719     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9720       // When looking for a 0 constant, N can be zext or sext.
9721       OtherOp = DAG.getConstant(1, dl, VT);
9722     else
9723       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9724                                 VT);
9725     return true;
9726   }
9727   }
9728 }
9729 
9730 // Combine a constant select operand into its use:
9731 //
9732 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9733 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9734 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9735 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9736 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9737 //
9738 // The transform is rejected if the select doesn't have a constant operand that
9739 // is null, or all ones when AllOnes is set.
9740 //
9741 // Also recognize sext/zext from i1:
9742 //
9743 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9744 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9745 //
9746 // These transformations eventually create predicated instructions.
9747 //
9748 // @param N       The node to transform.
9749 // @param Slct    The N operand that is a select.
9750 // @param OtherOp The other N operand (x above).
9751 // @param DCI     Context.
9752 // @param AllOnes Require the select constant to be all ones instead of null.
9753 // @returns The new node, or SDValue() on failure.
9754 static
9755 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9756                             TargetLowering::DAGCombinerInfo &DCI,
9757                             bool AllOnes = false) {
9758   SelectionDAG &DAG = DCI.DAG;
9759   EVT VT = N->getValueType(0);
9760   SDValue NonConstantVal;
9761   SDValue CCOp;
9762   bool SwapSelectOps;
9763   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9764                                   NonConstantVal, DAG))
9765     return SDValue();
9766 
9767   // Slct is now know to be the desired identity constant when CC is true.
9768   SDValue TrueVal = OtherOp;
9769   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9770                                  OtherOp, NonConstantVal);
9771   // Unless SwapSelectOps says CC should be false.
9772   if (SwapSelectOps)
9773     std::swap(TrueVal, FalseVal);
9774 
9775   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9776                      CCOp, TrueVal, FalseVal);
9777 }
9778 
9779 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9780 static
9781 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9782                                        TargetLowering::DAGCombinerInfo &DCI) {
9783   SDValue N0 = N->getOperand(0);
9784   SDValue N1 = N->getOperand(1);
9785   if (N0.getNode()->hasOneUse())
9786     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9787       return Result;
9788   if (N1.getNode()->hasOneUse())
9789     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9790       return Result;
9791   return SDValue();
9792 }
9793 
9794 static bool IsVUZPShuffleNode(SDNode *N) {
9795   // VUZP shuffle node.
9796   if (N->getOpcode() == ARMISD::VUZP)
9797     return true;
9798 
9799   // "VUZP" on i32 is an alias for VTRN.
9800   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9801     return true;
9802 
9803   return false;
9804 }
9805 
9806 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9807                                  TargetLowering::DAGCombinerInfo &DCI,
9808                                  const ARMSubtarget *Subtarget) {
9809   // Look for ADD(VUZP.0, VUZP.1).
9810   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9811       N0 == N1)
9812    return SDValue();
9813 
9814   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9815   if (!N->getValueType(0).is64BitVector())
9816     return SDValue();
9817 
9818   // Generate vpadd.
9819   SelectionDAG &DAG = DCI.DAG;
9820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9821   SDLoc dl(N);
9822   SDNode *Unzip = N0.getNode();
9823   EVT VT = N->getValueType(0);
9824 
9825   SmallVector<SDValue, 8> Ops;
9826   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9827                                 TLI.getPointerTy(DAG.getDataLayout())));
9828   Ops.push_back(Unzip->getOperand(0));
9829   Ops.push_back(Unzip->getOperand(1));
9830 
9831   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9832 }
9833 
9834 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9835                                       TargetLowering::DAGCombinerInfo &DCI,
9836                                       const ARMSubtarget *Subtarget) {
9837   // Check for two extended operands.
9838   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9839         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9840       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9841         N1.getOpcode() == ISD::ZERO_EXTEND))
9842     return SDValue();
9843 
9844   SDValue N00 = N0.getOperand(0);
9845   SDValue N10 = N1.getOperand(0);
9846 
9847   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9848   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9849       N00 == N10)
9850     return SDValue();
9851 
9852   // We only recognize Q register paddl here; this can't be reached until
9853   // after type legalization.
9854   if (!N00.getValueType().is64BitVector() ||
9855       !N0.getValueType().is128BitVector())
9856     return SDValue();
9857 
9858   // Generate vpaddl.
9859   SelectionDAG &DAG = DCI.DAG;
9860   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9861   SDLoc dl(N);
9862   EVT VT = N->getValueType(0);
9863 
9864   SmallVector<SDValue, 8> Ops;
9865   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9866   unsigned Opcode;
9867   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9868     Opcode = Intrinsic::arm_neon_vpaddls;
9869   else
9870     Opcode = Intrinsic::arm_neon_vpaddlu;
9871   Ops.push_back(DAG.getConstant(Opcode, dl,
9872                                 TLI.getPointerTy(DAG.getDataLayout())));
9873   EVT ElemTy = N00.getValueType().getVectorElementType();
9874   unsigned NumElts = VT.getVectorNumElements();
9875   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9876   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9877                                N00.getOperand(0), N00.getOperand(1));
9878   Ops.push_back(Concat);
9879 
9880   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9881 }
9882 
9883 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9884 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9885 // much easier to match.
9886 static SDValue
9887 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9888                                TargetLowering::DAGCombinerInfo &DCI,
9889                                const ARMSubtarget *Subtarget) {
9890   // Only perform optimization if after legalize, and if NEON is available. We
9891   // also expected both operands to be BUILD_VECTORs.
9892   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9893       || N0.getOpcode() != ISD::BUILD_VECTOR
9894       || N1.getOpcode() != ISD::BUILD_VECTOR)
9895     return SDValue();
9896 
9897   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9898   EVT VT = N->getValueType(0);
9899   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9900     return SDValue();
9901 
9902   // Check that the vector operands are of the right form.
9903   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9904   // operands, where N is the size of the formed vector.
9905   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9906   // index such that we have a pair wise add pattern.
9907 
9908   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9909   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9910     return SDValue();
9911   SDValue Vec = N0->getOperand(0)->getOperand(0);
9912   SDNode *V = Vec.getNode();
9913   unsigned nextIndex = 0;
9914 
9915   // For each operands to the ADD which are BUILD_VECTORs,
9916   // check to see if each of their operands are an EXTRACT_VECTOR with
9917   // the same vector and appropriate index.
9918   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9919     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9920         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9921 
9922       SDValue ExtVec0 = N0->getOperand(i);
9923       SDValue ExtVec1 = N1->getOperand(i);
9924 
9925       // First operand is the vector, verify its the same.
9926       if (V != ExtVec0->getOperand(0).getNode() ||
9927           V != ExtVec1->getOperand(0).getNode())
9928         return SDValue();
9929 
9930       // Second is the constant, verify its correct.
9931       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9932       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9933 
9934       // For the constant, we want to see all the even or all the odd.
9935       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9936           || C1->getZExtValue() != nextIndex+1)
9937         return SDValue();
9938 
9939       // Increment index.
9940       nextIndex+=2;
9941     } else
9942       return SDValue();
9943   }
9944 
9945   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9946   // we're using the entire input vector, otherwise there's a size/legality
9947   // mismatch somewhere.
9948   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9949       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9950     return SDValue();
9951 
9952   // Create VPADDL node.
9953   SelectionDAG &DAG = DCI.DAG;
9954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9955 
9956   SDLoc dl(N);
9957 
9958   // Build operand list.
9959   SmallVector<SDValue, 8> Ops;
9960   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9961                                 TLI.getPointerTy(DAG.getDataLayout())));
9962 
9963   // Input is the vector.
9964   Ops.push_back(Vec);
9965 
9966   // Get widened type and narrowed type.
9967   MVT widenType;
9968   unsigned numElem = VT.getVectorNumElements();
9969 
9970   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9971   switch (inputLaneType.getSimpleVT().SimpleTy) {
9972     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9973     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9974     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9975     default:
9976       llvm_unreachable("Invalid vector element type for padd optimization.");
9977   }
9978 
9979   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9980   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9981   return DAG.getNode(ExtOp, dl, VT, tmp);
9982 }
9983 
9984 static SDValue findMUL_LOHI(SDValue V) {
9985   if (V->getOpcode() == ISD::UMUL_LOHI ||
9986       V->getOpcode() == ISD::SMUL_LOHI)
9987     return V;
9988   return SDValue();
9989 }
9990 
9991 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9992                                         TargetLowering::DAGCombinerInfo &DCI,
9993                                         const ARMSubtarget *Subtarget) {
9994   if (Subtarget->isThumb()) {
9995     if (!Subtarget->hasDSP())
9996       return SDValue();
9997   } else if (!Subtarget->hasV5TEOps())
9998     return SDValue();
9999 
10000   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
10001   // accumulates the product into a 64-bit value. The 16-bit values will
10002   // be sign extended somehow or SRA'd into 32-bit values
10003   // (addc (adde (mul 16bit, 16bit), lo), hi)
10004   SDValue Mul = AddcNode->getOperand(0);
10005   SDValue Lo = AddcNode->getOperand(1);
10006   if (Mul.getOpcode() != ISD::MUL) {
10007     Lo = AddcNode->getOperand(0);
10008     Mul = AddcNode->getOperand(1);
10009     if (Mul.getOpcode() != ISD::MUL)
10010       return SDValue();
10011   }
10012 
10013   SDValue SRA = AddeNode->getOperand(0);
10014   SDValue Hi = AddeNode->getOperand(1);
10015   if (SRA.getOpcode() != ISD::SRA) {
10016     SRA = AddeNode->getOperand(1);
10017     Hi = AddeNode->getOperand(0);
10018     if (SRA.getOpcode() != ISD::SRA)
10019       return SDValue();
10020   }
10021   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
10022     if (Const->getZExtValue() != 31)
10023       return SDValue();
10024   } else
10025     return SDValue();
10026 
10027   if (SRA.getOperand(0) != Mul)
10028     return SDValue();
10029 
10030   SelectionDAG &DAG = DCI.DAG;
10031   SDLoc dl(AddcNode);
10032   unsigned Opcode = 0;
10033   SDValue Op0;
10034   SDValue Op1;
10035 
10036   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
10037     Opcode = ARMISD::SMLALBB;
10038     Op0 = Mul.getOperand(0);
10039     Op1 = Mul.getOperand(1);
10040   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
10041     Opcode = ARMISD::SMLALBT;
10042     Op0 = Mul.getOperand(0);
10043     Op1 = Mul.getOperand(1).getOperand(0);
10044   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
10045     Opcode = ARMISD::SMLALTB;
10046     Op0 = Mul.getOperand(0).getOperand(0);
10047     Op1 = Mul.getOperand(1);
10048   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
10049     Opcode = ARMISD::SMLALTT;
10050     Op0 = Mul->getOperand(0).getOperand(0);
10051     Op1 = Mul->getOperand(1).getOperand(0);
10052   }
10053 
10054   if (!Op0 || !Op1)
10055     return SDValue();
10056 
10057   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
10058                               Op0, Op1, Lo, Hi);
10059   // Replace the ADDs' nodes uses by the MLA node's values.
10060   SDValue HiMLALResult(SMLAL.getNode(), 1);
10061   SDValue LoMLALResult(SMLAL.getNode(), 0);
10062 
10063   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
10064   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
10065 
10066   // Return original node to notify the driver to stop replacing.
10067   SDValue resNode(AddcNode, 0);
10068   return resNode;
10069 }
10070 
10071 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
10072                                      TargetLowering::DAGCombinerInfo &DCI,
10073                                      const ARMSubtarget *Subtarget) {
10074   // Look for multiply add opportunities.
10075   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
10076   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
10077   // a glue link from the first add to the second add.
10078   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
10079   // a S/UMLAL instruction.
10080   //                  UMUL_LOHI
10081   //                 / :lo    \ :hi
10082   //                V          \          [no multiline comment]
10083   //    loAdd ->  ADDC         |
10084   //                 \ :carry /
10085   //                  V      V
10086   //                    ADDE   <- hiAdd
10087   //
10088   // In the special case where only the higher part of a signed result is used
10089   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
10090   // a constant with the exact value of 0x80000000, we recognize we are dealing
10091   // with a "rounded multiply and add" (or subtract) and transform it into
10092   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
10093 
10094   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
10095           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
10096          "Expect an ADDE or SUBE");
10097 
10098   assert(AddeSubeNode->getNumOperands() == 3 &&
10099          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
10100          "ADDE node has the wrong inputs");
10101 
10102   // Check that we are chained to the right ADDC or SUBC node.
10103   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
10104   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10105        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
10106       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
10107        AddcSubcNode->getOpcode() != ARMISD::SUBC))
10108     return SDValue();
10109 
10110   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
10111   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
10112 
10113   // Check if the two operands are from the same mul_lohi node.
10114   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
10115     return SDValue();
10116 
10117   assert(AddcSubcNode->getNumValues() == 2 &&
10118          AddcSubcNode->getValueType(0) == MVT::i32 &&
10119          "Expect ADDC with two result values. First: i32");
10120 
10121   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
10122   // maybe a SMLAL which multiplies two 16-bit values.
10123   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10124       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
10125       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
10126       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
10127       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
10128     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
10129 
10130   // Check for the triangle shape.
10131   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
10132   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
10133 
10134   // Make sure that the ADDE/SUBE operands are not coming from the same node.
10135   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
10136     return SDValue();
10137 
10138   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
10139   bool IsLeftOperandMUL = false;
10140   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
10141   if (MULOp == SDValue())
10142     MULOp = findMUL_LOHI(AddeSubeOp1);
10143   else
10144     IsLeftOperandMUL = true;
10145   if (MULOp == SDValue())
10146     return SDValue();
10147 
10148   // Figure out the right opcode.
10149   unsigned Opc = MULOp->getOpcode();
10150   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
10151 
10152   // Figure out the high and low input values to the MLAL node.
10153   SDValue *HiAddSub = nullptr;
10154   SDValue *LoMul = nullptr;
10155   SDValue *LowAddSub = nullptr;
10156 
10157   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
10158   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
10159     return SDValue();
10160 
10161   if (IsLeftOperandMUL)
10162     HiAddSub = &AddeSubeOp1;
10163   else
10164     HiAddSub = &AddeSubeOp0;
10165 
10166   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
10167   // whose low result is fed to the ADDC/SUBC we are checking.
10168 
10169   if (AddcSubcOp0 == MULOp.getValue(0)) {
10170     LoMul = &AddcSubcOp0;
10171     LowAddSub = &AddcSubcOp1;
10172   }
10173   if (AddcSubcOp1 == MULOp.getValue(0)) {
10174     LoMul = &AddcSubcOp1;
10175     LowAddSub = &AddcSubcOp0;
10176   }
10177 
10178   if (!LoMul)
10179     return SDValue();
10180 
10181   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
10182   // the replacement below will create a cycle.
10183   if (AddcSubcNode == HiAddSub->getNode() ||
10184       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
10185     return SDValue();
10186 
10187   // Create the merged node.
10188   SelectionDAG &DAG = DCI.DAG;
10189 
10190   // Start building operand list.
10191   SmallVector<SDValue, 8> Ops;
10192   Ops.push_back(LoMul->getOperand(0));
10193   Ops.push_back(LoMul->getOperand(1));
10194 
10195   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
10196   // the case, we must be doing signed multiplication and only use the higher
10197   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
10198   // addition or subtraction with the value of 0x800000.
10199   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
10200       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
10201       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
10202       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
10203           0x80000000) {
10204     Ops.push_back(*HiAddSub);
10205     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
10206       FinalOpc = ARMISD::SMMLSR;
10207     } else {
10208       FinalOpc = ARMISD::SMMLAR;
10209     }
10210     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
10211     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
10212 
10213     return SDValue(AddeSubeNode, 0);
10214   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
10215     // SMMLS is generated during instruction selection and the rest of this
10216     // function can not handle the case where AddcSubcNode is a SUBC.
10217     return SDValue();
10218 
10219   // Finish building the operand list for {U/S}MLAL
10220   Ops.push_back(*LowAddSub);
10221   Ops.push_back(*HiAddSub);
10222 
10223   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
10224                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10225 
10226   // Replace the ADDs' nodes uses by the MLA node's values.
10227   SDValue HiMLALResult(MLALNode.getNode(), 1);
10228   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
10229 
10230   SDValue LoMLALResult(MLALNode.getNode(), 0);
10231   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
10232 
10233   // Return original node to notify the driver to stop replacing.
10234   return SDValue(AddeSubeNode, 0);
10235 }
10236 
10237 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
10238                                       TargetLowering::DAGCombinerInfo &DCI,
10239                                       const ARMSubtarget *Subtarget) {
10240   // UMAAL is similar to UMLAL except that it adds two unsigned values.
10241   // While trying to combine for the other MLAL nodes, first search for the
10242   // chance to use UMAAL. Check if Addc uses a node which has already
10243   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
10244   // as the addend, and it's handled in PerformUMLALCombine.
10245 
10246   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10247     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10248 
10249   // Check that we have a glued ADDC node.
10250   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
10251   if (AddcNode->getOpcode() != ARMISD::ADDC)
10252     return SDValue();
10253 
10254   // Find the converted UMAAL or quit if it doesn't exist.
10255   SDNode *UmlalNode = nullptr;
10256   SDValue AddHi;
10257   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
10258     UmlalNode = AddcNode->getOperand(0).getNode();
10259     AddHi = AddcNode->getOperand(1);
10260   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
10261     UmlalNode = AddcNode->getOperand(1).getNode();
10262     AddHi = AddcNode->getOperand(0);
10263   } else {
10264     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10265   }
10266 
10267   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
10268   // the ADDC as well as Zero.
10269   if (!isNullConstant(UmlalNode->getOperand(3)))
10270     return SDValue();
10271 
10272   if ((isNullConstant(AddeNode->getOperand(0)) &&
10273        AddeNode->getOperand(1).getNode() == UmlalNode) ||
10274       (AddeNode->getOperand(0).getNode() == UmlalNode &&
10275        isNullConstant(AddeNode->getOperand(1)))) {
10276     SelectionDAG &DAG = DCI.DAG;
10277     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
10278                       UmlalNode->getOperand(2), AddHi };
10279     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
10280                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10281 
10282     // Replace the ADDs' nodes uses by the UMAAL node's values.
10283     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
10284     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
10285 
10286     // Return original node to notify the driver to stop replacing.
10287     return SDValue(AddeNode, 0);
10288   }
10289   return SDValue();
10290 }
10291 
10292 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
10293                                    const ARMSubtarget *Subtarget) {
10294   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10295     return SDValue();
10296 
10297   // Check that we have a pair of ADDC and ADDE as operands.
10298   // Both addends of the ADDE must be zero.
10299   SDNode* AddcNode = N->getOperand(2).getNode();
10300   SDNode* AddeNode = N->getOperand(3).getNode();
10301   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
10302       (AddeNode->getOpcode() == ARMISD::ADDE) &&
10303       isNullConstant(AddeNode->getOperand(0)) &&
10304       isNullConstant(AddeNode->getOperand(1)) &&
10305       (AddeNode->getOperand(2).getNode() == AddcNode))
10306     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
10307                        DAG.getVTList(MVT::i32, MVT::i32),
10308                        {N->getOperand(0), N->getOperand(1),
10309                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
10310   else
10311     return SDValue();
10312 }
10313 
10314 static SDValue PerformAddcSubcCombine(SDNode *N,
10315                                       TargetLowering::DAGCombinerInfo &DCI,
10316                                       const ARMSubtarget *Subtarget) {
10317   SelectionDAG &DAG(DCI.DAG);
10318 
10319   if (N->getOpcode() == ARMISD::SUBC) {
10320     // (SUBC (ADDE 0, 0, C), 1) -> C
10321     SDValue LHS = N->getOperand(0);
10322     SDValue RHS = N->getOperand(1);
10323     if (LHS->getOpcode() == ARMISD::ADDE &&
10324         isNullConstant(LHS->getOperand(0)) &&
10325         isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
10326       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
10327     }
10328   }
10329 
10330   if (Subtarget->isThumb1Only()) {
10331     SDValue RHS = N->getOperand(1);
10332     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10333       int32_t imm = C->getSExtValue();
10334       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
10335         SDLoc DL(N);
10336         RHS = DAG.getConstant(-imm, DL, MVT::i32);
10337         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
10338                                                            : ARMISD::ADDC;
10339         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
10340       }
10341     }
10342   }
10343 
10344   return SDValue();
10345 }
10346 
10347 static SDValue PerformAddeSubeCombine(SDNode *N,
10348                                       TargetLowering::DAGCombinerInfo &DCI,
10349                                       const ARMSubtarget *Subtarget) {
10350   if (Subtarget->isThumb1Only()) {
10351     SelectionDAG &DAG = DCI.DAG;
10352     SDValue RHS = N->getOperand(1);
10353     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10354       int64_t imm = C->getSExtValue();
10355       if (imm < 0) {
10356         SDLoc DL(N);
10357 
10358         // The with-carry-in form matches bitwise not instead of the negation.
10359         // Effectively, the inverse interpretation of the carry flag already
10360         // accounts for part of the negation.
10361         RHS = DAG.getConstant(~imm, DL, MVT::i32);
10362 
10363         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
10364                                                            : ARMISD::ADDE;
10365         return DAG.getNode(Opcode, DL, N->getVTList(),
10366                            N->getOperand(0), RHS, N->getOperand(2));
10367       }
10368     }
10369   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
10370     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
10371   }
10372   return SDValue();
10373 }
10374 
10375 /// PerformADDECombine - Target-specific dag combine transform from
10376 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
10377 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
10378 static SDValue PerformADDECombine(SDNode *N,
10379                                   TargetLowering::DAGCombinerInfo &DCI,
10380                                   const ARMSubtarget *Subtarget) {
10381   // Only ARM and Thumb2 support UMLAL/SMLAL.
10382   if (Subtarget->isThumb1Only())
10383     return PerformAddeSubeCombine(N, DCI, Subtarget);
10384 
10385   // Only perform the checks after legalize when the pattern is available.
10386   if (DCI.isBeforeLegalize()) return SDValue();
10387 
10388   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
10389 }
10390 
10391 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
10392 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
10393 /// called with the default operands, and if that fails, with commuted
10394 /// operands.
10395 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
10396                                           TargetLowering::DAGCombinerInfo &DCI,
10397                                           const ARMSubtarget *Subtarget){
10398   // Attempt to create vpadd for this add.
10399   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
10400     return Result;
10401 
10402   // Attempt to create vpaddl for this add.
10403   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
10404     return Result;
10405   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
10406                                                       Subtarget))
10407     return Result;
10408 
10409   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10410   if (N0.getNode()->hasOneUse())
10411     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
10412       return Result;
10413   return SDValue();
10414 }
10415 
10416 bool
10417 ARMTargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
10418                                                  CombineLevel Level) const {
10419   if (Level == BeforeLegalizeTypes)
10420     return true;
10421 
10422   if (Subtarget->isThumb() && Subtarget->isThumb1Only())
10423     return true;
10424 
10425   if (N->getOpcode() != ISD::SHL)
10426     return true;
10427 
10428   // Turn off commute-with-shift transform after legalization, so it doesn't
10429   // conflict with PerformSHLSimplify.  (We could try to detect when
10430   // PerformSHLSimplify would trigger more precisely, but it isn't
10431   // really necessary.)
10432   return false;
10433 }
10434 
10435 static SDValue PerformSHLSimplify(SDNode *N,
10436                                 TargetLowering::DAGCombinerInfo &DCI,
10437                                 const ARMSubtarget *ST) {
10438   // Allow the generic combiner to identify potential bswaps.
10439   if (DCI.isBeforeLegalize())
10440     return SDValue();
10441 
10442   // DAG combiner will fold:
10443   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
10444   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
10445   // Other code patterns that can be also be modified have the following form:
10446   // b + ((a << 1) | 510)
10447   // b + ((a << 1) & 510)
10448   // b + ((a << 1) ^ 510)
10449   // b + ((a << 1) + 510)
10450 
10451   // Many instructions can  perform the shift for free, but it requires both
10452   // the operands to be registers. If c1 << c2 is too large, a mov immediate
10453   // instruction will needed. So, unfold back to the original pattern if:
10454   // - if c1 and c2 are small enough that they don't require mov imms.
10455   // - the user(s) of the node can perform an shl
10456 
10457   // No shifted operands for 16-bit instructions.
10458   if (ST->isThumb() && ST->isThumb1Only())
10459     return SDValue();
10460 
10461   // Check that all the users could perform the shl themselves.
10462   for (auto U : N->uses()) {
10463     switch(U->getOpcode()) {
10464     default:
10465       return SDValue();
10466     case ISD::SUB:
10467     case ISD::ADD:
10468     case ISD::AND:
10469     case ISD::OR:
10470     case ISD::XOR:
10471     case ISD::SETCC:
10472     case ARMISD::CMP:
10473       // Check that the user isn't already using a constant because there
10474       // aren't any instructions that support an immediate operand and a
10475       // shifted operand.
10476       if (isa<ConstantSDNode>(U->getOperand(0)) ||
10477           isa<ConstantSDNode>(U->getOperand(1)))
10478         return SDValue();
10479 
10480       // Check that it's not already using a shift.
10481       if (U->getOperand(0).getOpcode() == ISD::SHL ||
10482           U->getOperand(1).getOpcode() == ISD::SHL)
10483         return SDValue();
10484       break;
10485     }
10486   }
10487 
10488   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
10489       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
10490     return SDValue();
10491 
10492   if (N->getOperand(0).getOpcode() != ISD::SHL)
10493     return SDValue();
10494 
10495   SDValue SHL = N->getOperand(0);
10496 
10497   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
10498   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
10499   if (!C1ShlC2 || !C2)
10500     return SDValue();
10501 
10502   APInt C2Int = C2->getAPIntValue();
10503   APInt C1Int = C1ShlC2->getAPIntValue();
10504 
10505   // Check that performing a lshr will not lose any information.
10506   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
10507                                      C2Int.getBitWidth() - C2->getZExtValue());
10508   if ((C1Int & Mask) != C1Int)
10509     return SDValue();
10510 
10511   // Shift the first constant.
10512   C1Int.lshrInPlace(C2Int);
10513 
10514   // The immediates are encoded as an 8-bit value that can be rotated.
10515   auto LargeImm = [](const APInt &Imm) {
10516     unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
10517     return Imm.getBitWidth() - Zeros > 8;
10518   };
10519 
10520   if (LargeImm(C1Int) || LargeImm(C2Int))
10521     return SDValue();
10522 
10523   SelectionDAG &DAG = DCI.DAG;
10524   SDLoc dl(N);
10525   SDValue X = SHL.getOperand(0);
10526   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
10527                               DAG.getConstant(C1Int, dl, MVT::i32));
10528   // Shift left to compensate for the lshr of C1Int.
10529   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
10530 
10531   LLVM_DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump();
10532              SHL.dump(); N->dump());
10533   LLVM_DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
10534   return Res;
10535 }
10536 
10537 
10538 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
10539 ///
10540 static SDValue PerformADDCombine(SDNode *N,
10541                                  TargetLowering::DAGCombinerInfo &DCI,
10542                                  const ARMSubtarget *Subtarget) {
10543   SDValue N0 = N->getOperand(0);
10544   SDValue N1 = N->getOperand(1);
10545 
10546   // Only works one way, because it needs an immediate operand.
10547   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10548     return Result;
10549 
10550   // First try with the default operand order.
10551   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
10552     return Result;
10553 
10554   // If that didn't work, try again with the operands commuted.
10555   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
10556 }
10557 
10558 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
10559 ///
10560 static SDValue PerformSUBCombine(SDNode *N,
10561                                  TargetLowering::DAGCombinerInfo &DCI) {
10562   SDValue N0 = N->getOperand(0);
10563   SDValue N1 = N->getOperand(1);
10564 
10565   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10566   if (N1.getNode()->hasOneUse())
10567     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10568       return Result;
10569 
10570   return SDValue();
10571 }
10572 
10573 /// PerformVMULCombine
10574 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10575 /// special multiplier accumulator forwarding.
10576 ///   vmul d3, d0, d2
10577 ///   vmla d3, d1, d2
10578 /// is faster than
10579 ///   vadd d3, d0, d1
10580 ///   vmul d3, d3, d2
10581 //  However, for (A + B) * (A + B),
10582 //    vadd d2, d0, d1
10583 //    vmul d3, d0, d2
10584 //    vmla d3, d1, d2
10585 //  is slower than
10586 //    vadd d2, d0, d1
10587 //    vmul d3, d2, d2
10588 static SDValue PerformVMULCombine(SDNode *N,
10589                                   TargetLowering::DAGCombinerInfo &DCI,
10590                                   const ARMSubtarget *Subtarget) {
10591   if (!Subtarget->hasVMLxForwarding())
10592     return SDValue();
10593 
10594   SelectionDAG &DAG = DCI.DAG;
10595   SDValue N0 = N->getOperand(0);
10596   SDValue N1 = N->getOperand(1);
10597   unsigned Opcode = N0.getOpcode();
10598   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10599       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10600     Opcode = N1.getOpcode();
10601     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10602         Opcode != ISD::FADD && Opcode != ISD::FSUB)
10603       return SDValue();
10604     std::swap(N0, N1);
10605   }
10606 
10607   if (N0 == N1)
10608     return SDValue();
10609 
10610   EVT VT = N->getValueType(0);
10611   SDLoc DL(N);
10612   SDValue N00 = N0->getOperand(0);
10613   SDValue N01 = N0->getOperand(1);
10614   return DAG.getNode(Opcode, DL, VT,
10615                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10616                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10617 }
10618 
10619 static SDValue PerformMULCombine(SDNode *N,
10620                                  TargetLowering::DAGCombinerInfo &DCI,
10621                                  const ARMSubtarget *Subtarget) {
10622   SelectionDAG &DAG = DCI.DAG;
10623 
10624   if (Subtarget->isThumb1Only())
10625     return SDValue();
10626 
10627   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10628     return SDValue();
10629 
10630   EVT VT = N->getValueType(0);
10631   if (VT.is64BitVector() || VT.is128BitVector())
10632     return PerformVMULCombine(N, DCI, Subtarget);
10633   if (VT != MVT::i32)
10634     return SDValue();
10635 
10636   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10637   if (!C)
10638     return SDValue();
10639 
10640   int64_t MulAmt = C->getSExtValue();
10641   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10642 
10643   ShiftAmt = ShiftAmt & (32 - 1);
10644   SDValue V = N->getOperand(0);
10645   SDLoc DL(N);
10646 
10647   SDValue Res;
10648   MulAmt >>= ShiftAmt;
10649 
10650   if (MulAmt >= 0) {
10651     if (isPowerOf2_32(MulAmt - 1)) {
10652       // (mul x, 2^N + 1) => (add (shl x, N), x)
10653       Res = DAG.getNode(ISD::ADD, DL, VT,
10654                         V,
10655                         DAG.getNode(ISD::SHL, DL, VT,
10656                                     V,
10657                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
10658                                                     MVT::i32)));
10659     } else if (isPowerOf2_32(MulAmt + 1)) {
10660       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10661       Res = DAG.getNode(ISD::SUB, DL, VT,
10662                         DAG.getNode(ISD::SHL, DL, VT,
10663                                     V,
10664                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10665                                                     MVT::i32)),
10666                         V);
10667     } else
10668       return SDValue();
10669   } else {
10670     uint64_t MulAmtAbs = -MulAmt;
10671     if (isPowerOf2_32(MulAmtAbs + 1)) {
10672       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10673       Res = DAG.getNode(ISD::SUB, DL, VT,
10674                         V,
10675                         DAG.getNode(ISD::SHL, DL, VT,
10676                                     V,
10677                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10678                                                     MVT::i32)));
10679     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10680       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10681       Res = DAG.getNode(ISD::ADD, DL, VT,
10682                         V,
10683                         DAG.getNode(ISD::SHL, DL, VT,
10684                                     V,
10685                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10686                                                     MVT::i32)));
10687       Res = DAG.getNode(ISD::SUB, DL, VT,
10688                         DAG.getConstant(0, DL, MVT::i32), Res);
10689     } else
10690       return SDValue();
10691   }
10692 
10693   if (ShiftAmt != 0)
10694     Res = DAG.getNode(ISD::SHL, DL, VT,
10695                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10696 
10697   // Do not add new nodes to DAG combiner worklist.
10698   DCI.CombineTo(N, Res, false);
10699   return SDValue();
10700 }
10701 
10702 static SDValue CombineANDShift(SDNode *N,
10703                                TargetLowering::DAGCombinerInfo &DCI,
10704                                const ARMSubtarget *Subtarget) {
10705   // Allow DAGCombine to pattern-match before we touch the canonical form.
10706   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10707     return SDValue();
10708 
10709   if (N->getValueType(0) != MVT::i32)
10710     return SDValue();
10711 
10712   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10713   if (!N1C)
10714     return SDValue();
10715 
10716   uint32_t C1 = (uint32_t)N1C->getZExtValue();
10717   // Don't transform uxtb/uxth.
10718   if (C1 == 255 || C1 == 65535)
10719     return SDValue();
10720 
10721   SDNode *N0 = N->getOperand(0).getNode();
10722   if (!N0->hasOneUse())
10723     return SDValue();
10724 
10725   if (N0->getOpcode() != ISD::SHL && N0->getOpcode() != ISD::SRL)
10726     return SDValue();
10727 
10728   bool LeftShift = N0->getOpcode() == ISD::SHL;
10729 
10730   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10731   if (!N01C)
10732     return SDValue();
10733 
10734   uint32_t C2 = (uint32_t)N01C->getZExtValue();
10735   if (!C2 || C2 >= 32)
10736     return SDValue();
10737 
10738   SelectionDAG &DAG = DCI.DAG;
10739   SDLoc DL(N);
10740 
10741   // We have a pattern of the form "(and (shl x, c2) c1)" or
10742   // "(and (srl x, c2) c1)", where c1 is a shifted mask. Try to
10743   // transform to a pair of shifts, to save materializing c1.
10744 
10745   // First pattern: right shift, and c1+1 is a power of two.
10746   // FIXME: Also check reversed pattern (left shift, and ~c1+1 is a power
10747   // of two).
10748   // FIXME: Use demanded bits?
10749   if (!LeftShift && isMask_32(C1)) {
10750     uint32_t C3 = countLeadingZeros(C1);
10751     if (C2 < C3) {
10752       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
10753                                 DAG.getConstant(C3 - C2, DL, MVT::i32));
10754       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
10755                          DAG.getConstant(C3, DL, MVT::i32));
10756     }
10757   }
10758 
10759   // Second pattern: left shift, and (c1>>c2)+1 is a power of two.
10760   // FIXME: Also check reversed pattern (right shift, and ~(c1<<c2)+1
10761   // is a power of two).
10762   // FIXME: Use demanded bits?
10763   if (LeftShift && isShiftedMask_32(C1)) {
10764     uint32_t C3 = countLeadingZeros(C1);
10765     if (C2 + C3 < 32 && C1 == ((-1U << (C2 + C3)) >> C3)) {
10766       SDValue SHL = DAG.getNode(ISD::SHL, DL, MVT::i32, N0->getOperand(0),
10767                                 DAG.getConstant(C2 + C3, DL, MVT::i32));
10768       return DAG.getNode(ISD::SRL, DL, MVT::i32, SHL,
10769                         DAG.getConstant(C3, DL, MVT::i32));
10770     }
10771   }
10772 
10773   // FIXME: Transform "(and (shl x, c2) c1)" ->
10774   // "(shl (and x, c1>>c2), c2)" if "c1 >> c2" is a cheaper immediate than
10775   // c1.
10776   return SDValue();
10777 }
10778 
10779 static SDValue PerformANDCombine(SDNode *N,
10780                                  TargetLowering::DAGCombinerInfo &DCI,
10781                                  const ARMSubtarget *Subtarget) {
10782   // Attempt to use immediate-form VBIC
10783   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10784   SDLoc dl(N);
10785   EVT VT = N->getValueType(0);
10786   SelectionDAG &DAG = DCI.DAG;
10787 
10788   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10789     return SDValue();
10790 
10791   APInt SplatBits, SplatUndef;
10792   unsigned SplatBitSize;
10793   bool HasAnyUndefs;
10794   if (BVN &&
10795       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10796     if (SplatBitSize <= 64) {
10797       EVT VbicVT;
10798       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10799                                       SplatUndef.getZExtValue(), SplatBitSize,
10800                                       DAG, dl, VbicVT, VT.is128BitVector(),
10801                                       OtherModImm);
10802       if (Val.getNode()) {
10803         SDValue Input =
10804           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10805         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10806         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10807       }
10808     }
10809   }
10810 
10811   if (!Subtarget->isThumb1Only()) {
10812     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10813     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10814       return Result;
10815 
10816     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10817       return Result;
10818   }
10819 
10820   if (Subtarget->isThumb1Only())
10821     if (SDValue Result = CombineANDShift(N, DCI, Subtarget))
10822       return Result;
10823 
10824   return SDValue();
10825 }
10826 
10827 // Try combining OR nodes to SMULWB, SMULWT.
10828 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10829                                          TargetLowering::DAGCombinerInfo &DCI,
10830                                          const ARMSubtarget *Subtarget) {
10831   if (!Subtarget->hasV6Ops() ||
10832       (Subtarget->isThumb() &&
10833        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10834     return SDValue();
10835 
10836   SDValue SRL = OR->getOperand(0);
10837   SDValue SHL = OR->getOperand(1);
10838 
10839   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10840     SRL = OR->getOperand(1);
10841     SHL = OR->getOperand(0);
10842   }
10843   if (!isSRL16(SRL) || !isSHL16(SHL))
10844     return SDValue();
10845 
10846   // The first operands to the shifts need to be the two results from the
10847   // same smul_lohi node.
10848   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10849        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10850     return SDValue();
10851 
10852   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10853   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10854       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10855     return SDValue();
10856 
10857   // Now we have:
10858   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10859   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10860   // For SMUWB the 16-bit value will signed extended somehow.
10861   // For SMULWT only the SRA is required.
10862   // Check both sides of SMUL_LOHI
10863   SDValue OpS16 = SMULLOHI->getOperand(0);
10864   SDValue OpS32 = SMULLOHI->getOperand(1);
10865 
10866   SelectionDAG &DAG = DCI.DAG;
10867   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10868     OpS16 = OpS32;
10869     OpS32 = SMULLOHI->getOperand(0);
10870   }
10871 
10872   SDLoc dl(OR);
10873   unsigned Opcode = 0;
10874   if (isS16(OpS16, DAG))
10875     Opcode = ARMISD::SMULWB;
10876   else if (isSRA16(OpS16)) {
10877     Opcode = ARMISD::SMULWT;
10878     OpS16 = OpS16->getOperand(0);
10879   }
10880   else
10881     return SDValue();
10882 
10883   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10884   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10885   return SDValue(OR, 0);
10886 }
10887 
10888 static SDValue PerformORCombineToBFI(SDNode *N,
10889                                      TargetLowering::DAGCombinerInfo &DCI,
10890                                      const ARMSubtarget *Subtarget) {
10891   // BFI is only available on V6T2+
10892   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10893     return SDValue();
10894 
10895   EVT VT = N->getValueType(0);
10896   SDValue N0 = N->getOperand(0);
10897   SDValue N1 = N->getOperand(1);
10898   SelectionDAG &DAG = DCI.DAG;
10899   SDLoc DL(N);
10900   // 1) or (and A, mask), val => ARMbfi A, val, mask
10901   //      iff (val & mask) == val
10902   //
10903   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10904   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10905   //          && mask == ~mask2
10906   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10907   //          && ~mask == mask2
10908   //  (i.e., copy a bitfield value into another bitfield of the same width)
10909 
10910   if (VT != MVT::i32)
10911     return SDValue();
10912 
10913   SDValue N00 = N0.getOperand(0);
10914 
10915   // The value and the mask need to be constants so we can verify this is
10916   // actually a bitfield set. If the mask is 0xffff, we can do better
10917   // via a movt instruction, so don't use BFI in that case.
10918   SDValue MaskOp = N0.getOperand(1);
10919   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10920   if (!MaskC)
10921     return SDValue();
10922   unsigned Mask = MaskC->getZExtValue();
10923   if (Mask == 0xffff)
10924     return SDValue();
10925   SDValue Res;
10926   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10927   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10928   if (N1C) {
10929     unsigned Val = N1C->getZExtValue();
10930     if ((Val & ~Mask) != Val)
10931       return SDValue();
10932 
10933     if (ARM::isBitFieldInvertedMask(Mask)) {
10934       Val >>= countTrailingZeros(~Mask);
10935 
10936       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10937                         DAG.getConstant(Val, DL, MVT::i32),
10938                         DAG.getConstant(Mask, DL, MVT::i32));
10939 
10940       DCI.CombineTo(N, Res, false);
10941       // Return value from the original node to inform the combiner than N is
10942       // now dead.
10943       return SDValue(N, 0);
10944     }
10945   } else if (N1.getOpcode() == ISD::AND) {
10946     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10947     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10948     if (!N11C)
10949       return SDValue();
10950     unsigned Mask2 = N11C->getZExtValue();
10951 
10952     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10953     // as is to match.
10954     if (ARM::isBitFieldInvertedMask(Mask) &&
10955         (Mask == ~Mask2)) {
10956       // The pack halfword instruction works better for masks that fit it,
10957       // so use that when it's available.
10958       if (Subtarget->hasDSP() &&
10959           (Mask == 0xffff || Mask == 0xffff0000))
10960         return SDValue();
10961       // 2a
10962       unsigned amt = countTrailingZeros(Mask2);
10963       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10964                         DAG.getConstant(amt, DL, MVT::i32));
10965       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10966                         DAG.getConstant(Mask, DL, MVT::i32));
10967       DCI.CombineTo(N, Res, false);
10968       // Return value from the original node to inform the combiner than N is
10969       // now dead.
10970       return SDValue(N, 0);
10971     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10972                (~Mask == Mask2)) {
10973       // The pack halfword instruction works better for masks that fit it,
10974       // so use that when it's available.
10975       if (Subtarget->hasDSP() &&
10976           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10977         return SDValue();
10978       // 2b
10979       unsigned lsb = countTrailingZeros(Mask);
10980       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10981                         DAG.getConstant(lsb, DL, MVT::i32));
10982       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10983                         DAG.getConstant(Mask2, DL, MVT::i32));
10984       DCI.CombineTo(N, Res, false);
10985       // Return value from the original node to inform the combiner than N is
10986       // now dead.
10987       return SDValue(N, 0);
10988     }
10989   }
10990 
10991   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10992       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10993       ARM::isBitFieldInvertedMask(~Mask)) {
10994     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10995     // where lsb(mask) == #shamt and masked bits of B are known zero.
10996     SDValue ShAmt = N00.getOperand(1);
10997     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10998     unsigned LSB = countTrailingZeros(Mask);
10999     if (ShAmtC != LSB)
11000       return SDValue();
11001 
11002     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
11003                       DAG.getConstant(~Mask, DL, MVT::i32));
11004 
11005     DCI.CombineTo(N, Res, false);
11006     // Return value from the original node to inform the combiner than N is
11007     // now dead.
11008     return SDValue(N, 0);
11009   }
11010 
11011   return SDValue();
11012 }
11013 
11014 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
11015 static SDValue PerformORCombine(SDNode *N,
11016                                 TargetLowering::DAGCombinerInfo &DCI,
11017                                 const ARMSubtarget *Subtarget) {
11018   // Attempt to use immediate-form VORR
11019   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
11020   SDLoc dl(N);
11021   EVT VT = N->getValueType(0);
11022   SelectionDAG &DAG = DCI.DAG;
11023 
11024   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11025     return SDValue();
11026 
11027   APInt SplatBits, SplatUndef;
11028   unsigned SplatBitSize;
11029   bool HasAnyUndefs;
11030   if (BVN && Subtarget->hasNEON() &&
11031       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
11032     if (SplatBitSize <= 64) {
11033       EVT VorrVT;
11034       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
11035                                       SplatUndef.getZExtValue(), SplatBitSize,
11036                                       DAG, dl, VorrVT, VT.is128BitVector(),
11037                                       OtherModImm);
11038       if (Val.getNode()) {
11039         SDValue Input =
11040           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
11041         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
11042         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
11043       }
11044     }
11045   }
11046 
11047   if (!Subtarget->isThumb1Only()) {
11048     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
11049     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11050       return Result;
11051     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
11052       return Result;
11053   }
11054 
11055   SDValue N0 = N->getOperand(0);
11056   SDValue N1 = N->getOperand(1);
11057 
11058   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
11059   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
11060       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
11061 
11062     // The code below optimizes (or (and X, Y), Z).
11063     // The AND operand needs to have a single user to make these optimizations
11064     // profitable.
11065     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
11066       return SDValue();
11067 
11068     APInt SplatUndef;
11069     unsigned SplatBitSize;
11070     bool HasAnyUndefs;
11071 
11072     APInt SplatBits0, SplatBits1;
11073     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
11074     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
11075     // Ensure that the second operand of both ands are constants
11076     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
11077                                       HasAnyUndefs) && !HasAnyUndefs) {
11078         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
11079                                           HasAnyUndefs) && !HasAnyUndefs) {
11080             // Ensure that the bit width of the constants are the same and that
11081             // the splat arguments are logical inverses as per the pattern we
11082             // are trying to simplify.
11083             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
11084                 SplatBits0 == ~SplatBits1) {
11085                 // Canonicalize the vector type to make instruction selection
11086                 // simpler.
11087                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
11088                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
11089                                              N0->getOperand(1),
11090                                              N0->getOperand(0),
11091                                              N1->getOperand(0));
11092                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11093             }
11094         }
11095     }
11096   }
11097 
11098   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
11099   // reasonable.
11100   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
11101     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
11102       return Res;
11103   }
11104 
11105   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11106     return Result;
11107 
11108   return SDValue();
11109 }
11110 
11111 static SDValue PerformXORCombine(SDNode *N,
11112                                  TargetLowering::DAGCombinerInfo &DCI,
11113                                  const ARMSubtarget *Subtarget) {
11114   EVT VT = N->getValueType(0);
11115   SelectionDAG &DAG = DCI.DAG;
11116 
11117   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11118     return SDValue();
11119 
11120   if (!Subtarget->isThumb1Only()) {
11121     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
11122     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11123       return Result;
11124 
11125     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11126       return Result;
11127   }
11128 
11129   return SDValue();
11130 }
11131 
11132 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
11133 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
11134 // their position in "to" (Rd).
11135 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
11136   assert(N->getOpcode() == ARMISD::BFI);
11137 
11138   SDValue From = N->getOperand(1);
11139   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
11140   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
11141 
11142   // If the Base came from a SHR #C, we can deduce that it is really testing bit
11143   // #C in the base of the SHR.
11144   if (From->getOpcode() == ISD::SRL &&
11145       isa<ConstantSDNode>(From->getOperand(1))) {
11146     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
11147     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
11148     FromMask <<= Shift.getLimitedValue(31);
11149     From = From->getOperand(0);
11150   }
11151 
11152   return From;
11153 }
11154 
11155 // If A and B contain one contiguous set of bits, does A | B == A . B?
11156 //
11157 // Neither A nor B must be zero.
11158 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
11159   unsigned LastActiveBitInA =  A.countTrailingZeros();
11160   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
11161   return LastActiveBitInA - 1 == FirstActiveBitInB;
11162 }
11163 
11164 static SDValue FindBFIToCombineWith(SDNode *N) {
11165   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
11166   // if one exists.
11167   APInt ToMask, FromMask;
11168   SDValue From = ParseBFI(N, ToMask, FromMask);
11169   SDValue To = N->getOperand(0);
11170 
11171   // Now check for a compatible BFI to merge with. We can pass through BFIs that
11172   // aren't compatible, but not if they set the same bit in their destination as
11173   // we do (or that of any BFI we're going to combine with).
11174   SDValue V = To;
11175   APInt CombinedToMask = ToMask;
11176   while (V.getOpcode() == ARMISD::BFI) {
11177     APInt NewToMask, NewFromMask;
11178     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
11179     if (NewFrom != From) {
11180       // This BFI has a different base. Keep going.
11181       CombinedToMask |= NewToMask;
11182       V = V.getOperand(0);
11183       continue;
11184     }
11185 
11186     // Do the written bits conflict with any we've seen so far?
11187     if ((NewToMask & CombinedToMask).getBoolValue())
11188       // Conflicting bits - bail out because going further is unsafe.
11189       return SDValue();
11190 
11191     // Are the new bits contiguous when combined with the old bits?
11192     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
11193         BitsProperlyConcatenate(FromMask, NewFromMask))
11194       return V;
11195     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
11196         BitsProperlyConcatenate(NewFromMask, FromMask))
11197       return V;
11198 
11199     // We've seen a write to some bits, so track it.
11200     CombinedToMask |= NewToMask;
11201     // Keep going...
11202     V = V.getOperand(0);
11203   }
11204 
11205   return SDValue();
11206 }
11207 
11208 static SDValue PerformBFICombine(SDNode *N,
11209                                  TargetLowering::DAGCombinerInfo &DCI) {
11210   SDValue N1 = N->getOperand(1);
11211   if (N1.getOpcode() == ISD::AND) {
11212     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
11213     // the bits being cleared by the AND are not demanded by the BFI.
11214     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11215     if (!N11C)
11216       return SDValue();
11217     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11218     unsigned LSB = countTrailingZeros(~InvMask);
11219     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
11220     assert(Width <
11221                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
11222            "undefined behavior");
11223     unsigned Mask = (1u << Width) - 1;
11224     unsigned Mask2 = N11C->getZExtValue();
11225     if ((Mask & (~Mask2)) == 0)
11226       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
11227                              N->getOperand(0), N1.getOperand(0),
11228                              N->getOperand(2));
11229   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
11230     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
11231     // Keep track of any consecutive bits set that all come from the same base
11232     // value. We can combine these together into a single BFI.
11233     SDValue CombineBFI = FindBFIToCombineWith(N);
11234     if (CombineBFI == SDValue())
11235       return SDValue();
11236 
11237     // We've found a BFI.
11238     APInt ToMask1, FromMask1;
11239     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
11240 
11241     APInt ToMask2, FromMask2;
11242     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
11243     assert(From1 == From2);
11244     (void)From2;
11245 
11246     // First, unlink CombineBFI.
11247     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
11248     // Then create a new BFI, combining the two together.
11249     APInt NewFromMask = FromMask1 | FromMask2;
11250     APInt NewToMask = ToMask1 | ToMask2;
11251 
11252     EVT VT = N->getValueType(0);
11253     SDLoc dl(N);
11254 
11255     if (NewFromMask[0] == 0)
11256       From1 = DCI.DAG.getNode(
11257         ISD::SRL, dl, VT, From1,
11258         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
11259     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
11260                            DCI.DAG.getConstant(~NewToMask, dl, VT));
11261   }
11262   return SDValue();
11263 }
11264 
11265 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
11266 /// ARMISD::VMOVRRD.
11267 static SDValue PerformVMOVRRDCombine(SDNode *N,
11268                                      TargetLowering::DAGCombinerInfo &DCI,
11269                                      const ARMSubtarget *Subtarget) {
11270   // vmovrrd(vmovdrr x, y) -> x,y
11271   SDValue InDouble = N->getOperand(0);
11272   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
11273     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
11274 
11275   // vmovrrd(load f64) -> (load i32), (load i32)
11276   SDNode *InNode = InDouble.getNode();
11277   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
11278       InNode->getValueType(0) == MVT::f64 &&
11279       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
11280       !cast<LoadSDNode>(InNode)->isVolatile()) {
11281     // TODO: Should this be done for non-FrameIndex operands?
11282     LoadSDNode *LD = cast<LoadSDNode>(InNode);
11283 
11284     SelectionDAG &DAG = DCI.DAG;
11285     SDLoc DL(LD);
11286     SDValue BasePtr = LD->getBasePtr();
11287     SDValue NewLD1 =
11288         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
11289                     LD->getAlignment(), LD->getMemOperand()->getFlags());
11290 
11291     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11292                                     DAG.getConstant(4, DL, MVT::i32));
11293     SDValue NewLD2 = DAG.getLoad(
11294         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
11295         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
11296 
11297     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
11298     if (DCI.DAG.getDataLayout().isBigEndian())
11299       std::swap (NewLD1, NewLD2);
11300     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
11301     return Result;
11302   }
11303 
11304   return SDValue();
11305 }
11306 
11307 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
11308 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
11309 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
11310   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
11311   SDValue Op0 = N->getOperand(0);
11312   SDValue Op1 = N->getOperand(1);
11313   if (Op0.getOpcode() == ISD::BITCAST)
11314     Op0 = Op0.getOperand(0);
11315   if (Op1.getOpcode() == ISD::BITCAST)
11316     Op1 = Op1.getOperand(0);
11317   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
11318       Op0.getNode() == Op1.getNode() &&
11319       Op0.getResNo() == 0 && Op1.getResNo() == 1)
11320     return DAG.getNode(ISD::BITCAST, SDLoc(N),
11321                        N->getValueType(0), Op0.getOperand(0));
11322   return SDValue();
11323 }
11324 
11325 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
11326 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
11327 /// i64 vector to have f64 elements, since the value can then be loaded
11328 /// directly into a VFP register.
11329 static bool hasNormalLoadOperand(SDNode *N) {
11330   unsigned NumElts = N->getValueType(0).getVectorNumElements();
11331   for (unsigned i = 0; i < NumElts; ++i) {
11332     SDNode *Elt = N->getOperand(i).getNode();
11333     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
11334       return true;
11335   }
11336   return false;
11337 }
11338 
11339 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
11340 /// ISD::BUILD_VECTOR.
11341 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
11342                                           TargetLowering::DAGCombinerInfo &DCI,
11343                                           const ARMSubtarget *Subtarget) {
11344   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
11345   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
11346   // into a pair of GPRs, which is fine when the value is used as a scalar,
11347   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
11348   SelectionDAG &DAG = DCI.DAG;
11349   if (N->getNumOperands() == 2)
11350     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
11351       return RV;
11352 
11353   // Load i64 elements as f64 values so that type legalization does not split
11354   // them up into i32 values.
11355   EVT VT = N->getValueType(0);
11356   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
11357     return SDValue();
11358   SDLoc dl(N);
11359   SmallVector<SDValue, 8> Ops;
11360   unsigned NumElts = VT.getVectorNumElements();
11361   for (unsigned i = 0; i < NumElts; ++i) {
11362     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
11363     Ops.push_back(V);
11364     // Make the DAGCombiner fold the bitcast.
11365     DCI.AddToWorklist(V.getNode());
11366   }
11367   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
11368   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
11369   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11370 }
11371 
11372 /// Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
11373 static SDValue
11374 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11375   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
11376   // At that time, we may have inserted bitcasts from integer to float.
11377   // If these bitcasts have survived DAGCombine, change the lowering of this
11378   // BUILD_VECTOR in something more vector friendly, i.e., that does not
11379   // force to use floating point types.
11380 
11381   // Make sure we can change the type of the vector.
11382   // This is possible iff:
11383   // 1. The vector is only used in a bitcast to a integer type. I.e.,
11384   //    1.1. Vector is used only once.
11385   //    1.2. Use is a bit convert to an integer type.
11386   // 2. The size of its operands are 32-bits (64-bits are not legal).
11387   EVT VT = N->getValueType(0);
11388   EVT EltVT = VT.getVectorElementType();
11389 
11390   // Check 1.1. and 2.
11391   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
11392     return SDValue();
11393 
11394   // By construction, the input type must be float.
11395   assert(EltVT == MVT::f32 && "Unexpected type!");
11396 
11397   // Check 1.2.
11398   SDNode *Use = *N->use_begin();
11399   if (Use->getOpcode() != ISD::BITCAST ||
11400       Use->getValueType(0).isFloatingPoint())
11401     return SDValue();
11402 
11403   // Check profitability.
11404   // Model is, if more than half of the relevant operands are bitcast from
11405   // i32, turn the build_vector into a sequence of insert_vector_elt.
11406   // Relevant operands are everything that is not statically
11407   // (i.e., at compile time) bitcasted.
11408   unsigned NumOfBitCastedElts = 0;
11409   unsigned NumElts = VT.getVectorNumElements();
11410   unsigned NumOfRelevantElts = NumElts;
11411   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
11412     SDValue Elt = N->getOperand(Idx);
11413     if (Elt->getOpcode() == ISD::BITCAST) {
11414       // Assume only bit cast to i32 will go away.
11415       if (Elt->getOperand(0).getValueType() == MVT::i32)
11416         ++NumOfBitCastedElts;
11417     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
11418       // Constants are statically casted, thus do not count them as
11419       // relevant operands.
11420       --NumOfRelevantElts;
11421   }
11422 
11423   // Check if more than half of the elements require a non-free bitcast.
11424   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
11425     return SDValue();
11426 
11427   SelectionDAG &DAG = DCI.DAG;
11428   // Create the new vector type.
11429   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
11430   // Check if the type is legal.
11431   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11432   if (!TLI.isTypeLegal(VecVT))
11433     return SDValue();
11434 
11435   // Combine:
11436   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
11437   // => BITCAST INSERT_VECTOR_ELT
11438   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
11439   //                      (BITCAST EN), N.
11440   SDValue Vec = DAG.getUNDEF(VecVT);
11441   SDLoc dl(N);
11442   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
11443     SDValue V = N->getOperand(Idx);
11444     if (V.isUndef())
11445       continue;
11446     if (V.getOpcode() == ISD::BITCAST &&
11447         V->getOperand(0).getValueType() == MVT::i32)
11448       // Fold obvious case.
11449       V = V.getOperand(0);
11450     else {
11451       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
11452       // Make the DAGCombiner fold the bitcasts.
11453       DCI.AddToWorklist(V.getNode());
11454     }
11455     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
11456     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
11457   }
11458   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
11459   // Make the DAGCombiner fold the bitcasts.
11460   DCI.AddToWorklist(Vec.getNode());
11461   return Vec;
11462 }
11463 
11464 /// PerformInsertEltCombine - Target-specific dag combine xforms for
11465 /// ISD::INSERT_VECTOR_ELT.
11466 static SDValue PerformInsertEltCombine(SDNode *N,
11467                                        TargetLowering::DAGCombinerInfo &DCI) {
11468   // Bitcast an i64 load inserted into a vector to f64.
11469   // Otherwise, the i64 value will be legalized to a pair of i32 values.
11470   EVT VT = N->getValueType(0);
11471   SDNode *Elt = N->getOperand(1).getNode();
11472   if (VT.getVectorElementType() != MVT::i64 ||
11473       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
11474     return SDValue();
11475 
11476   SelectionDAG &DAG = DCI.DAG;
11477   SDLoc dl(N);
11478   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11479                                  VT.getVectorNumElements());
11480   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
11481   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
11482   // Make the DAGCombiner fold the bitcasts.
11483   DCI.AddToWorklist(Vec.getNode());
11484   DCI.AddToWorklist(V.getNode());
11485   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
11486                                Vec, V, N->getOperand(2));
11487   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
11488 }
11489 
11490 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
11491 /// ISD::VECTOR_SHUFFLE.
11492 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
11493   // The LLVM shufflevector instruction does not require the shuffle mask
11494   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
11495   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
11496   // operands do not match the mask length, they are extended by concatenating
11497   // them with undef vectors.  That is probably the right thing for other
11498   // targets, but for NEON it is better to concatenate two double-register
11499   // size vector operands into a single quad-register size vector.  Do that
11500   // transformation here:
11501   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
11502   //   shuffle(concat(v1, v2), undef)
11503   SDValue Op0 = N->getOperand(0);
11504   SDValue Op1 = N->getOperand(1);
11505   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
11506       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
11507       Op0.getNumOperands() != 2 ||
11508       Op1.getNumOperands() != 2)
11509     return SDValue();
11510   SDValue Concat0Op1 = Op0.getOperand(1);
11511   SDValue Concat1Op1 = Op1.getOperand(1);
11512   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
11513     return SDValue();
11514   // Skip the transformation if any of the types are illegal.
11515   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11516   EVT VT = N->getValueType(0);
11517   if (!TLI.isTypeLegal(VT) ||
11518       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
11519       !TLI.isTypeLegal(Concat1Op1.getValueType()))
11520     return SDValue();
11521 
11522   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11523                                   Op0.getOperand(0), Op1.getOperand(0));
11524   // Translate the shuffle mask.
11525   SmallVector<int, 16> NewMask;
11526   unsigned NumElts = VT.getVectorNumElements();
11527   unsigned HalfElts = NumElts/2;
11528   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11529   for (unsigned n = 0; n < NumElts; ++n) {
11530     int MaskElt = SVN->getMaskElt(n);
11531     int NewElt = -1;
11532     if (MaskElt < (int)HalfElts)
11533       NewElt = MaskElt;
11534     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
11535       NewElt = HalfElts + MaskElt - NumElts;
11536     NewMask.push_back(NewElt);
11537   }
11538   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
11539                               DAG.getUNDEF(VT), NewMask);
11540 }
11541 
11542 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
11543 /// NEON load/store intrinsics, and generic vector load/stores, to merge
11544 /// base address updates.
11545 /// For generic load/stores, the memory type is assumed to be a vector.
11546 /// The caller is assumed to have checked legality.
11547 static SDValue CombineBaseUpdate(SDNode *N,
11548                                  TargetLowering::DAGCombinerInfo &DCI) {
11549   SelectionDAG &DAG = DCI.DAG;
11550   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
11551                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
11552   const bool isStore = N->getOpcode() == ISD::STORE;
11553   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
11554   SDValue Addr = N->getOperand(AddrOpIdx);
11555   MemSDNode *MemN = cast<MemSDNode>(N);
11556   SDLoc dl(N);
11557 
11558   // Search for a use of the address operand that is an increment.
11559   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11560          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11561     SDNode *User = *UI;
11562     if (User->getOpcode() != ISD::ADD ||
11563         UI.getUse().getResNo() != Addr.getResNo())
11564       continue;
11565 
11566     // Check that the add is independent of the load/store.  Otherwise, folding
11567     // it would create a cycle. We can avoid searching through Addr as it's a
11568     // predecessor to both.
11569     SmallPtrSet<const SDNode *, 32> Visited;
11570     SmallVector<const SDNode *, 16> Worklist;
11571     Visited.insert(Addr.getNode());
11572     Worklist.push_back(N);
11573     Worklist.push_back(User);
11574     if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
11575         SDNode::hasPredecessorHelper(User, Visited, Worklist))
11576       continue;
11577 
11578     // Find the new opcode for the updating load/store.
11579     bool isLoadOp = true;
11580     bool isLaneOp = false;
11581     unsigned NewOpc = 0;
11582     unsigned NumVecs = 0;
11583     if (isIntrinsic) {
11584       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11585       switch (IntNo) {
11586       default: llvm_unreachable("unexpected intrinsic for Neon base update");
11587       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
11588         NumVecs = 1; break;
11589       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
11590         NumVecs = 2; break;
11591       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
11592         NumVecs = 3; break;
11593       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
11594         NumVecs = 4; break;
11595       case Intrinsic::arm_neon_vld2dup:
11596       case Intrinsic::arm_neon_vld3dup:
11597       case Intrinsic::arm_neon_vld4dup:
11598         // TODO: Support updating VLDxDUP nodes. For now, we just skip
11599         // combining base updates for such intrinsics.
11600         continue;
11601       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
11602         NumVecs = 2; isLaneOp = true; break;
11603       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
11604         NumVecs = 3; isLaneOp = true; break;
11605       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
11606         NumVecs = 4; isLaneOp = true; break;
11607       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
11608         NumVecs = 1; isLoadOp = false; break;
11609       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
11610         NumVecs = 2; isLoadOp = false; break;
11611       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
11612         NumVecs = 3; isLoadOp = false; break;
11613       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
11614         NumVecs = 4; isLoadOp = false; break;
11615       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
11616         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
11617       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
11618         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
11619       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
11620         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
11621       }
11622     } else {
11623       isLaneOp = true;
11624       switch (N->getOpcode()) {
11625       default: llvm_unreachable("unexpected opcode for Neon base update");
11626       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
11627       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
11628       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
11629       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
11630       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
11631         NumVecs = 1; isLaneOp = false; break;
11632       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
11633         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
11634       }
11635     }
11636 
11637     // Find the size of memory referenced by the load/store.
11638     EVT VecTy;
11639     if (isLoadOp) {
11640       VecTy = N->getValueType(0);
11641     } else if (isIntrinsic) {
11642       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
11643     } else {
11644       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
11645       VecTy = N->getOperand(1).getValueType();
11646     }
11647 
11648     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11649     if (isLaneOp)
11650       NumBytes /= VecTy.getVectorNumElements();
11651 
11652     // If the increment is a constant, it must match the memory ref size.
11653     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11654     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
11655     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
11656       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
11657       // separate instructions that make it harder to use a non-constant update.
11658       continue;
11659     }
11660 
11661     // OK, we found an ADD we can fold into the base update.
11662     // Now, create a _UPD node, taking care of not breaking alignment.
11663 
11664     EVT AlignedVecTy = VecTy;
11665     unsigned Alignment = MemN->getAlignment();
11666 
11667     // If this is a less-than-standard-aligned load/store, change the type to
11668     // match the standard alignment.
11669     // The alignment is overlooked when selecting _UPD variants; and it's
11670     // easier to introduce bitcasts here than fix that.
11671     // There are 3 ways to get to this base-update combine:
11672     // - intrinsics: they are assumed to be properly aligned (to the standard
11673     //   alignment of the memory type), so we don't need to do anything.
11674     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
11675     //   intrinsics, so, likewise, there's nothing to do.
11676     // - generic load/store instructions: the alignment is specified as an
11677     //   explicit operand, rather than implicitly as the standard alignment
11678     //   of the memory type (like the intrisics).  We need to change the
11679     //   memory type to match the explicit alignment.  That way, we don't
11680     //   generate non-standard-aligned ARMISD::VLDx nodes.
11681     if (isa<LSBaseSDNode>(N)) {
11682       if (Alignment == 0)
11683         Alignment = 1;
11684       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
11685         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
11686         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
11687         assert(!isLaneOp && "Unexpected generic load/store lane.");
11688         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
11689         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
11690       }
11691       // Don't set an explicit alignment on regular load/stores that we want
11692       // to transform to VLD/VST 1_UPD nodes.
11693       // This matches the behavior of regular load/stores, which only get an
11694       // explicit alignment if the MMO alignment is larger than the standard
11695       // alignment of the memory type.
11696       // Intrinsics, however, always get an explicit alignment, set to the
11697       // alignment of the MMO.
11698       Alignment = 1;
11699     }
11700 
11701     // Create the new updating load/store node.
11702     // First, create an SDVTList for the new updating node's results.
11703     EVT Tys[6];
11704     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
11705     unsigned n;
11706     for (n = 0; n < NumResultVecs; ++n)
11707       Tys[n] = AlignedVecTy;
11708     Tys[n++] = MVT::i32;
11709     Tys[n] = MVT::Other;
11710     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
11711 
11712     // Then, gather the new node's operands.
11713     SmallVector<SDValue, 8> Ops;
11714     Ops.push_back(N->getOperand(0)); // incoming chain
11715     Ops.push_back(N->getOperand(AddrOpIdx));
11716     Ops.push_back(Inc);
11717 
11718     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
11719       // Try to match the intrinsic's signature
11720       Ops.push_back(StN->getValue());
11721     } else {
11722       // Loads (and of course intrinsics) match the intrinsics' signature,
11723       // so just add all but the alignment operand.
11724       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
11725         Ops.push_back(N->getOperand(i));
11726     }
11727 
11728     // For all node types, the alignment operand is always the last one.
11729     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
11730 
11731     // If this is a non-standard-aligned STORE, the penultimate operand is the
11732     // stored value.  Bitcast it to the aligned type.
11733     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11734       SDValue &StVal = Ops[Ops.size()-2];
11735       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11736     }
11737 
11738     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11739     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11740                                            MemN->getMemOperand());
11741 
11742     // Update the uses.
11743     SmallVector<SDValue, 5> NewResults;
11744     for (unsigned i = 0; i < NumResultVecs; ++i)
11745       NewResults.push_back(SDValue(UpdN.getNode(), i));
11746 
11747     // If this is an non-standard-aligned LOAD, the first result is the loaded
11748     // value.  Bitcast it to the expected result type.
11749     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11750       SDValue &LdVal = NewResults[0];
11751       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11752     }
11753 
11754     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11755     DCI.CombineTo(N, NewResults);
11756     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11757 
11758     break;
11759   }
11760   return SDValue();
11761 }
11762 
11763 static SDValue PerformVLDCombine(SDNode *N,
11764                                  TargetLowering::DAGCombinerInfo &DCI) {
11765   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11766     return SDValue();
11767 
11768   return CombineBaseUpdate(N, DCI);
11769 }
11770 
11771 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11772 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11773 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
11774 /// return true.
11775 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11776   SelectionDAG &DAG = DCI.DAG;
11777   EVT VT = N->getValueType(0);
11778   // vldN-dup instructions only support 64-bit vectors for N > 1.
11779   if (!VT.is64BitVector())
11780     return false;
11781 
11782   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11783   SDNode *VLD = N->getOperand(0).getNode();
11784   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11785     return false;
11786   unsigned NumVecs = 0;
11787   unsigned NewOpc = 0;
11788   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11789   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11790     NumVecs = 2;
11791     NewOpc = ARMISD::VLD2DUP;
11792   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11793     NumVecs = 3;
11794     NewOpc = ARMISD::VLD3DUP;
11795   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11796     NumVecs = 4;
11797     NewOpc = ARMISD::VLD4DUP;
11798   } else {
11799     return false;
11800   }
11801 
11802   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11803   // numbers match the load.
11804   unsigned VLDLaneNo =
11805     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11806   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11807        UI != UE; ++UI) {
11808     // Ignore uses of the chain result.
11809     if (UI.getUse().getResNo() == NumVecs)
11810       continue;
11811     SDNode *User = *UI;
11812     if (User->getOpcode() != ARMISD::VDUPLANE ||
11813         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11814       return false;
11815   }
11816 
11817   // Create the vldN-dup node.
11818   EVT Tys[5];
11819   unsigned n;
11820   for (n = 0; n < NumVecs; ++n)
11821     Tys[n] = VT;
11822   Tys[n] = MVT::Other;
11823   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11824   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11825   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11826   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11827                                            Ops, VLDMemInt->getMemoryVT(),
11828                                            VLDMemInt->getMemOperand());
11829 
11830   // Update the uses.
11831   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11832        UI != UE; ++UI) {
11833     unsigned ResNo = UI.getUse().getResNo();
11834     // Ignore uses of the chain result.
11835     if (ResNo == NumVecs)
11836       continue;
11837     SDNode *User = *UI;
11838     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11839   }
11840 
11841   // Now the vldN-lane intrinsic is dead except for its chain result.
11842   // Update uses of the chain.
11843   std::vector<SDValue> VLDDupResults;
11844   for (unsigned n = 0; n < NumVecs; ++n)
11845     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11846   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11847   DCI.CombineTo(VLD, VLDDupResults);
11848 
11849   return true;
11850 }
11851 
11852 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11853 /// ARMISD::VDUPLANE.
11854 static SDValue PerformVDUPLANECombine(SDNode *N,
11855                                       TargetLowering::DAGCombinerInfo &DCI) {
11856   SDValue Op = N->getOperand(0);
11857 
11858   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11859   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11860   if (CombineVLDDUP(N, DCI))
11861     return SDValue(N, 0);
11862 
11863   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11864   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11865   while (Op.getOpcode() == ISD::BITCAST)
11866     Op = Op.getOperand(0);
11867   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11868     return SDValue();
11869 
11870   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11871   unsigned EltSize = Op.getScalarValueSizeInBits();
11872   // The canonical VMOV for a zero vector uses a 32-bit element size.
11873   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11874   unsigned EltBits;
11875   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11876     EltSize = 8;
11877   EVT VT = N->getValueType(0);
11878   if (EltSize > VT.getScalarSizeInBits())
11879     return SDValue();
11880 
11881   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11882 }
11883 
11884 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11885 static SDValue PerformVDUPCombine(SDNode *N,
11886                                   TargetLowering::DAGCombinerInfo &DCI) {
11887   SelectionDAG &DAG = DCI.DAG;
11888   SDValue Op = N->getOperand(0);
11889 
11890   // Match VDUP(LOAD) -> VLD1DUP.
11891   // We match this pattern here rather than waiting for isel because the
11892   // transform is only legal for unindexed loads.
11893   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11894   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11895       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11896     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11897                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11898     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11899     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11900                                              Ops, LD->getMemoryVT(),
11901                                              LD->getMemOperand());
11902     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11903     return VLDDup;
11904   }
11905 
11906   return SDValue();
11907 }
11908 
11909 static SDValue PerformLOADCombine(SDNode *N,
11910                                   TargetLowering::DAGCombinerInfo &DCI) {
11911   EVT VT = N->getValueType(0);
11912 
11913   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11914   if (ISD::isNormalLoad(N) && VT.isVector() &&
11915       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11916     return CombineBaseUpdate(N, DCI);
11917 
11918   return SDValue();
11919 }
11920 
11921 /// PerformSTORECombine - Target-specific dag combine xforms for
11922 /// ISD::STORE.
11923 static SDValue PerformSTORECombine(SDNode *N,
11924                                    TargetLowering::DAGCombinerInfo &DCI) {
11925   StoreSDNode *St = cast<StoreSDNode>(N);
11926   if (St->isVolatile())
11927     return SDValue();
11928 
11929   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11930   // pack all of the elements in one place.  Next, store to memory in fewer
11931   // chunks.
11932   SDValue StVal = St->getValue();
11933   EVT VT = StVal.getValueType();
11934   if (St->isTruncatingStore() && VT.isVector()) {
11935     SelectionDAG &DAG = DCI.DAG;
11936     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11937     EVT StVT = St->getMemoryVT();
11938     unsigned NumElems = VT.getVectorNumElements();
11939     assert(StVT != VT && "Cannot truncate to the same type");
11940     unsigned FromEltSz = VT.getScalarSizeInBits();
11941     unsigned ToEltSz = StVT.getScalarSizeInBits();
11942 
11943     // From, To sizes and ElemCount must be pow of two
11944     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11945 
11946     // We are going to use the original vector elt for storing.
11947     // Accumulated smaller vector elements must be a multiple of the store size.
11948     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11949 
11950     unsigned SizeRatio  = FromEltSz / ToEltSz;
11951     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11952 
11953     // Create a type on which we perform the shuffle.
11954     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11955                                      NumElems*SizeRatio);
11956     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11957 
11958     SDLoc DL(St);
11959     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11960     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11961     for (unsigned i = 0; i < NumElems; ++i)
11962       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11963                           ? (i + 1) * SizeRatio - 1
11964                           : i * SizeRatio;
11965 
11966     // Can't shuffle using an illegal type.
11967     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11968 
11969     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11970                                 DAG.getUNDEF(WideVec.getValueType()),
11971                                 ShuffleVec);
11972     // At this point all of the data is stored at the bottom of the
11973     // register. We now need to save it to mem.
11974 
11975     // Find the largest store unit
11976     MVT StoreType = MVT::i8;
11977     for (MVT Tp : MVT::integer_valuetypes()) {
11978       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11979         StoreType = Tp;
11980     }
11981     // Didn't find a legal store type.
11982     if (!TLI.isTypeLegal(StoreType))
11983       return SDValue();
11984 
11985     // Bitcast the original vector into a vector of store-size units
11986     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11987             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11988     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11989     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11990     SmallVector<SDValue, 8> Chains;
11991     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11992                                         TLI.getPointerTy(DAG.getDataLayout()));
11993     SDValue BasePtr = St->getBasePtr();
11994 
11995     // Perform one or more big stores into memory.
11996     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11997     for (unsigned I = 0; I < E; I++) {
11998       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11999                                    StoreType, ShuffWide,
12000                                    DAG.getIntPtrConstant(I, DL));
12001       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
12002                                 St->getPointerInfo(), St->getAlignment(),
12003                                 St->getMemOperand()->getFlags());
12004       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
12005                             Increment);
12006       Chains.push_back(Ch);
12007     }
12008     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
12009   }
12010 
12011   if (!ISD::isNormalStore(St))
12012     return SDValue();
12013 
12014   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
12015   // ARM stores of arguments in the same cache line.
12016   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
12017       StVal.getNode()->hasOneUse()) {
12018     SelectionDAG  &DAG = DCI.DAG;
12019     bool isBigEndian = DAG.getDataLayout().isBigEndian();
12020     SDLoc DL(St);
12021     SDValue BasePtr = St->getBasePtr();
12022     SDValue NewST1 = DAG.getStore(
12023         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
12024         BasePtr, St->getPointerInfo(), St->getAlignment(),
12025         St->getMemOperand()->getFlags());
12026 
12027     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
12028                                     DAG.getConstant(4, DL, MVT::i32));
12029     return DAG.getStore(NewST1.getValue(0), DL,
12030                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
12031                         OffsetPtr, St->getPointerInfo(),
12032                         std::min(4U, St->getAlignment() / 2),
12033                         St->getMemOperand()->getFlags());
12034   }
12035 
12036   if (StVal.getValueType() == MVT::i64 &&
12037       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12038 
12039     // Bitcast an i64 store extracted from a vector to f64.
12040     // Otherwise, the i64 value will be legalized to a pair of i32 values.
12041     SelectionDAG &DAG = DCI.DAG;
12042     SDLoc dl(StVal);
12043     SDValue IntVec = StVal.getOperand(0);
12044     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
12045                                    IntVec.getValueType().getVectorNumElements());
12046     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
12047     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12048                                  Vec, StVal.getOperand(1));
12049     dl = SDLoc(N);
12050     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
12051     // Make the DAGCombiner fold the bitcasts.
12052     DCI.AddToWorklist(Vec.getNode());
12053     DCI.AddToWorklist(ExtElt.getNode());
12054     DCI.AddToWorklist(V.getNode());
12055     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
12056                         St->getPointerInfo(), St->getAlignment(),
12057                         St->getMemOperand()->getFlags(), St->getAAInfo());
12058   }
12059 
12060   // If this is a legal vector store, try to combine it into a VST1_UPD.
12061   if (ISD::isNormalStore(N) && VT.isVector() &&
12062       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
12063     return CombineBaseUpdate(N, DCI);
12064 
12065   return SDValue();
12066 }
12067 
12068 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
12069 /// can replace combinations of VMUL and VCVT (floating-point to integer)
12070 /// when the VMUL has a constant operand that is a power of 2.
12071 ///
12072 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
12073 ///  vmul.f32        d16, d17, d16
12074 ///  vcvt.s32.f32    d16, d16
12075 /// becomes:
12076 ///  vcvt.s32.f32    d16, d16, #3
12077 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
12078                                   const ARMSubtarget *Subtarget) {
12079   if (!Subtarget->hasNEON())
12080     return SDValue();
12081 
12082   SDValue Op = N->getOperand(0);
12083   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
12084       Op.getOpcode() != ISD::FMUL)
12085     return SDValue();
12086 
12087   SDValue ConstVec = Op->getOperand(1);
12088   if (!isa<BuildVectorSDNode>(ConstVec))
12089     return SDValue();
12090 
12091   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
12092   uint32_t FloatBits = FloatTy.getSizeInBits();
12093   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
12094   uint32_t IntBits = IntTy.getSizeInBits();
12095   unsigned NumLanes = Op.getValueType().getVectorNumElements();
12096   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
12097     // These instructions only exist converting from f32 to i32. We can handle
12098     // smaller integers by generating an extra truncate, but larger ones would
12099     // be lossy. We also can't handle more then 4 lanes, since these intructions
12100     // only support v2i32/v4i32 types.
12101     return SDValue();
12102   }
12103 
12104   BitVector UndefElements;
12105   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12106   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12107   if (C == -1 || C == 0 || C > 32)
12108     return SDValue();
12109 
12110   SDLoc dl(N);
12111   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
12112   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
12113     Intrinsic::arm_neon_vcvtfp2fxu;
12114   SDValue FixConv = DAG.getNode(
12115       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12116       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
12117       DAG.getConstant(C, dl, MVT::i32));
12118 
12119   if (IntBits < FloatBits)
12120     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
12121 
12122   return FixConv;
12123 }
12124 
12125 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
12126 /// can replace combinations of VCVT (integer to floating-point) and VDIV
12127 /// when the VDIV has a constant operand that is a power of 2.
12128 ///
12129 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
12130 ///  vcvt.f32.s32    d16, d16
12131 ///  vdiv.f32        d16, d17, d16
12132 /// becomes:
12133 ///  vcvt.f32.s32    d16, d16, #3
12134 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
12135                                   const ARMSubtarget *Subtarget) {
12136   if (!Subtarget->hasNEON())
12137     return SDValue();
12138 
12139   SDValue Op = N->getOperand(0);
12140   unsigned OpOpcode = Op.getNode()->getOpcode();
12141   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
12142       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
12143     return SDValue();
12144 
12145   SDValue ConstVec = N->getOperand(1);
12146   if (!isa<BuildVectorSDNode>(ConstVec))
12147     return SDValue();
12148 
12149   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
12150   uint32_t FloatBits = FloatTy.getSizeInBits();
12151   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
12152   uint32_t IntBits = IntTy.getSizeInBits();
12153   unsigned NumLanes = Op.getValueType().getVectorNumElements();
12154   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
12155     // These instructions only exist converting from i32 to f32. We can handle
12156     // smaller integers by generating an extra extend, but larger ones would
12157     // be lossy. We also can't handle more then 4 lanes, since these intructions
12158     // only support v2i32/v4i32 types.
12159     return SDValue();
12160   }
12161 
12162   BitVector UndefElements;
12163   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12164   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12165   if (C == -1 || C == 0 || C > 32)
12166     return SDValue();
12167 
12168   SDLoc dl(N);
12169   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
12170   SDValue ConvInput = Op.getOperand(0);
12171   if (IntBits < FloatBits)
12172     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
12173                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12174                             ConvInput);
12175 
12176   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
12177     Intrinsic::arm_neon_vcvtfxu2fp;
12178   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
12179                      Op.getValueType(),
12180                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
12181                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
12182 }
12183 
12184 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
12185 /// operand of a vector shift operation, where all the elements of the
12186 /// build_vector must have the same constant integer value.
12187 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
12188   // Ignore bit_converts.
12189   while (Op.getOpcode() == ISD::BITCAST)
12190     Op = Op.getOperand(0);
12191   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
12192   APInt SplatBits, SplatUndef;
12193   unsigned SplatBitSize;
12194   bool HasAnyUndefs;
12195   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
12196                                       HasAnyUndefs, ElementBits) ||
12197       SplatBitSize > ElementBits)
12198     return false;
12199   Cnt = SplatBits.getSExtValue();
12200   return true;
12201 }
12202 
12203 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
12204 /// operand of a vector shift left operation.  That value must be in the range:
12205 ///   0 <= Value < ElementBits for a left shift; or
12206 ///   0 <= Value <= ElementBits for a long left shift.
12207 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
12208   assert(VT.isVector() && "vector shift count is not a vector type");
12209   int64_t ElementBits = VT.getScalarSizeInBits();
12210   if (! getVShiftImm(Op, ElementBits, Cnt))
12211     return false;
12212   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
12213 }
12214 
12215 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
12216 /// operand of a vector shift right operation.  For a shift opcode, the value
12217 /// is positive, but for an intrinsic the value count must be negative. The
12218 /// absolute value must be in the range:
12219 ///   1 <= |Value| <= ElementBits for a right shift; or
12220 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
12221 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
12222                          int64_t &Cnt) {
12223   assert(VT.isVector() && "vector shift count is not a vector type");
12224   int64_t ElementBits = VT.getScalarSizeInBits();
12225   if (! getVShiftImm(Op, ElementBits, Cnt))
12226     return false;
12227   if (!isIntrinsic)
12228     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
12229   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
12230     Cnt = -Cnt;
12231     return true;
12232   }
12233   return false;
12234 }
12235 
12236 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
12237 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
12238   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12239   switch (IntNo) {
12240   default:
12241     // Don't do anything for most intrinsics.
12242     break;
12243 
12244   // Vector shifts: check for immediate versions and lower them.
12245   // Note: This is done during DAG combining instead of DAG legalizing because
12246   // the build_vectors for 64-bit vector element shift counts are generally
12247   // not legal, and it is hard to see their values after they get legalized to
12248   // loads from a constant pool.
12249   case Intrinsic::arm_neon_vshifts:
12250   case Intrinsic::arm_neon_vshiftu:
12251   case Intrinsic::arm_neon_vrshifts:
12252   case Intrinsic::arm_neon_vrshiftu:
12253   case Intrinsic::arm_neon_vrshiftn:
12254   case Intrinsic::arm_neon_vqshifts:
12255   case Intrinsic::arm_neon_vqshiftu:
12256   case Intrinsic::arm_neon_vqshiftsu:
12257   case Intrinsic::arm_neon_vqshiftns:
12258   case Intrinsic::arm_neon_vqshiftnu:
12259   case Intrinsic::arm_neon_vqshiftnsu:
12260   case Intrinsic::arm_neon_vqrshiftns:
12261   case Intrinsic::arm_neon_vqrshiftnu:
12262   case Intrinsic::arm_neon_vqrshiftnsu: {
12263     EVT VT = N->getOperand(1).getValueType();
12264     int64_t Cnt;
12265     unsigned VShiftOpc = 0;
12266 
12267     switch (IntNo) {
12268     case Intrinsic::arm_neon_vshifts:
12269     case Intrinsic::arm_neon_vshiftu:
12270       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
12271         VShiftOpc = ARMISD::VSHL;
12272         break;
12273       }
12274       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
12275         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
12276                      ARMISD::VSHRs : ARMISD::VSHRu);
12277         break;
12278       }
12279       return SDValue();
12280 
12281     case Intrinsic::arm_neon_vrshifts:
12282     case Intrinsic::arm_neon_vrshiftu:
12283       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
12284         break;
12285       return SDValue();
12286 
12287     case Intrinsic::arm_neon_vqshifts:
12288     case Intrinsic::arm_neon_vqshiftu:
12289       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12290         break;
12291       return SDValue();
12292 
12293     case Intrinsic::arm_neon_vqshiftsu:
12294       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12295         break;
12296       llvm_unreachable("invalid shift count for vqshlu intrinsic");
12297 
12298     case Intrinsic::arm_neon_vrshiftn:
12299     case Intrinsic::arm_neon_vqshiftns:
12300     case Intrinsic::arm_neon_vqshiftnu:
12301     case Intrinsic::arm_neon_vqshiftnsu:
12302     case Intrinsic::arm_neon_vqrshiftns:
12303     case Intrinsic::arm_neon_vqrshiftnu:
12304     case Intrinsic::arm_neon_vqrshiftnsu:
12305       // Narrowing shifts require an immediate right shift.
12306       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
12307         break;
12308       llvm_unreachable("invalid shift count for narrowing vector shift "
12309                        "intrinsic");
12310 
12311     default:
12312       llvm_unreachable("unhandled vector shift");
12313     }
12314 
12315     switch (IntNo) {
12316     case Intrinsic::arm_neon_vshifts:
12317     case Intrinsic::arm_neon_vshiftu:
12318       // Opcode already set above.
12319       break;
12320     case Intrinsic::arm_neon_vrshifts:
12321       VShiftOpc = ARMISD::VRSHRs; break;
12322     case Intrinsic::arm_neon_vrshiftu:
12323       VShiftOpc = ARMISD::VRSHRu; break;
12324     case Intrinsic::arm_neon_vrshiftn:
12325       VShiftOpc = ARMISD::VRSHRN; break;
12326     case Intrinsic::arm_neon_vqshifts:
12327       VShiftOpc = ARMISD::VQSHLs; break;
12328     case Intrinsic::arm_neon_vqshiftu:
12329       VShiftOpc = ARMISD::VQSHLu; break;
12330     case Intrinsic::arm_neon_vqshiftsu:
12331       VShiftOpc = ARMISD::VQSHLsu; break;
12332     case Intrinsic::arm_neon_vqshiftns:
12333       VShiftOpc = ARMISD::VQSHRNs; break;
12334     case Intrinsic::arm_neon_vqshiftnu:
12335       VShiftOpc = ARMISD::VQSHRNu; break;
12336     case Intrinsic::arm_neon_vqshiftnsu:
12337       VShiftOpc = ARMISD::VQSHRNsu; break;
12338     case Intrinsic::arm_neon_vqrshiftns:
12339       VShiftOpc = ARMISD::VQRSHRNs; break;
12340     case Intrinsic::arm_neon_vqrshiftnu:
12341       VShiftOpc = ARMISD::VQRSHRNu; break;
12342     case Intrinsic::arm_neon_vqrshiftnsu:
12343       VShiftOpc = ARMISD::VQRSHRNsu; break;
12344     }
12345 
12346     SDLoc dl(N);
12347     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12348                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
12349   }
12350 
12351   case Intrinsic::arm_neon_vshiftins: {
12352     EVT VT = N->getOperand(1).getValueType();
12353     int64_t Cnt;
12354     unsigned VShiftOpc = 0;
12355 
12356     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
12357       VShiftOpc = ARMISD::VSLI;
12358     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
12359       VShiftOpc = ARMISD::VSRI;
12360     else {
12361       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
12362     }
12363 
12364     SDLoc dl(N);
12365     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12366                        N->getOperand(1), N->getOperand(2),
12367                        DAG.getConstant(Cnt, dl, MVT::i32));
12368   }
12369 
12370   case Intrinsic::arm_neon_vqrshifts:
12371   case Intrinsic::arm_neon_vqrshiftu:
12372     // No immediate versions of these to check for.
12373     break;
12374   }
12375 
12376   return SDValue();
12377 }
12378 
12379 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
12380 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
12381 /// combining instead of DAG legalizing because the build_vectors for 64-bit
12382 /// vector element shift counts are generally not legal, and it is hard to see
12383 /// their values after they get legalized to loads from a constant pool.
12384 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
12385                                    const ARMSubtarget *ST) {
12386   EVT VT = N->getValueType(0);
12387   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
12388     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
12389     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
12390     SDValue N1 = N->getOperand(1);
12391     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
12392       SDValue N0 = N->getOperand(0);
12393       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
12394           DAG.MaskedValueIsZero(N0.getOperand(0),
12395                                 APInt::getHighBitsSet(32, 16)))
12396         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
12397     }
12398   }
12399 
12400   // Nothing to be done for scalar shifts.
12401   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12402   if (!VT.isVector() || !TLI.isTypeLegal(VT))
12403     return SDValue();
12404 
12405   assert(ST->hasNEON() && "unexpected vector shift");
12406   int64_t Cnt;
12407 
12408   switch (N->getOpcode()) {
12409   default: llvm_unreachable("unexpected shift opcode");
12410 
12411   case ISD::SHL:
12412     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
12413       SDLoc dl(N);
12414       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
12415                          DAG.getConstant(Cnt, dl, MVT::i32));
12416     }
12417     break;
12418 
12419   case ISD::SRA:
12420   case ISD::SRL:
12421     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
12422       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
12423                             ARMISD::VSHRs : ARMISD::VSHRu);
12424       SDLoc dl(N);
12425       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
12426                          DAG.getConstant(Cnt, dl, MVT::i32));
12427     }
12428   }
12429   return SDValue();
12430 }
12431 
12432 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
12433 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
12434 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
12435                                     const ARMSubtarget *ST) {
12436   SDValue N0 = N->getOperand(0);
12437 
12438   // Check for sign- and zero-extensions of vector extract operations of 8-
12439   // and 16-bit vector elements.  NEON supports these directly.  They are
12440   // handled during DAG combining because type legalization will promote them
12441   // to 32-bit types and it is messy to recognize the operations after that.
12442   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12443     SDValue Vec = N0.getOperand(0);
12444     SDValue Lane = N0.getOperand(1);
12445     EVT VT = N->getValueType(0);
12446     EVT EltVT = N0.getValueType();
12447     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12448 
12449     if (VT == MVT::i32 &&
12450         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
12451         TLI.isTypeLegal(Vec.getValueType()) &&
12452         isa<ConstantSDNode>(Lane)) {
12453 
12454       unsigned Opc = 0;
12455       switch (N->getOpcode()) {
12456       default: llvm_unreachable("unexpected opcode");
12457       case ISD::SIGN_EXTEND:
12458         Opc = ARMISD::VGETLANEs;
12459         break;
12460       case ISD::ZERO_EXTEND:
12461       case ISD::ANY_EXTEND:
12462         Opc = ARMISD::VGETLANEu;
12463         break;
12464       }
12465       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
12466     }
12467   }
12468 
12469   return SDValue();
12470 }
12471 
12472 static const APInt *isPowerOf2Constant(SDValue V) {
12473   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12474   if (!C)
12475     return nullptr;
12476   const APInt *CV = &C->getAPIntValue();
12477   return CV->isPowerOf2() ? CV : nullptr;
12478 }
12479 
12480 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
12481   // If we have a CMOV, OR and AND combination such as:
12482   //   if (x & CN)
12483   //     y |= CM;
12484   //
12485   // And:
12486   //   * CN is a single bit;
12487   //   * All bits covered by CM are known zero in y
12488   //
12489   // Then we can convert this into a sequence of BFI instructions. This will
12490   // always be a win if CM is a single bit, will always be no worse than the
12491   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
12492   // three bits (due to the extra IT instruction).
12493 
12494   SDValue Op0 = CMOV->getOperand(0);
12495   SDValue Op1 = CMOV->getOperand(1);
12496   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
12497   auto CC = CCNode->getAPIntValue().getLimitedValue();
12498   SDValue CmpZ = CMOV->getOperand(4);
12499 
12500   // The compare must be against zero.
12501   if (!isNullConstant(CmpZ->getOperand(1)))
12502     return SDValue();
12503 
12504   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
12505   SDValue And = CmpZ->getOperand(0);
12506   if (And->getOpcode() != ISD::AND)
12507     return SDValue();
12508   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
12509   if (!AndC)
12510     return SDValue();
12511   SDValue X = And->getOperand(0);
12512 
12513   if (CC == ARMCC::EQ) {
12514     // We're performing an "equal to zero" compare. Swap the operands so we
12515     // canonicalize on a "not equal to zero" compare.
12516     std::swap(Op0, Op1);
12517   } else {
12518     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
12519   }
12520 
12521   if (Op1->getOpcode() != ISD::OR)
12522     return SDValue();
12523 
12524   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
12525   if (!OrC)
12526     return SDValue();
12527   SDValue Y = Op1->getOperand(0);
12528 
12529   if (Op0 != Y)
12530     return SDValue();
12531 
12532   // Now, is it profitable to continue?
12533   APInt OrCI = OrC->getAPIntValue();
12534   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
12535   if (OrCI.countPopulation() > Heuristic)
12536     return SDValue();
12537 
12538   // Lastly, can we determine that the bits defined by OrCI
12539   // are zero in Y?
12540   KnownBits Known;
12541   DAG.computeKnownBits(Y, Known);
12542   if ((OrCI & Known.Zero) != OrCI)
12543     return SDValue();
12544 
12545   // OK, we can do the combine.
12546   SDValue V = Y;
12547   SDLoc dl(X);
12548   EVT VT = X.getValueType();
12549   unsigned BitInX = AndC->logBase2();
12550 
12551   if (BitInX != 0) {
12552     // We must shift X first.
12553     X = DAG.getNode(ISD::SRL, dl, VT, X,
12554                     DAG.getConstant(BitInX, dl, VT));
12555   }
12556 
12557   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
12558        BitInY < NumActiveBits; ++BitInY) {
12559     if (OrCI[BitInY] == 0)
12560       continue;
12561     APInt Mask(VT.getSizeInBits(), 0);
12562     Mask.setBit(BitInY);
12563     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
12564                     // Confusingly, the operand is an *inverted* mask.
12565                     DAG.getConstant(~Mask, dl, VT));
12566   }
12567 
12568   return V;
12569 }
12570 
12571 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
12572 SDValue
12573 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
12574   SDValue Cmp = N->getOperand(4);
12575   if (Cmp.getOpcode() != ARMISD::CMPZ)
12576     // Only looking at NE cases.
12577     return SDValue();
12578 
12579   EVT VT = N->getValueType(0);
12580   SDLoc dl(N);
12581   SDValue LHS = Cmp.getOperand(0);
12582   SDValue RHS = Cmp.getOperand(1);
12583   SDValue Chain = N->getOperand(0);
12584   SDValue BB = N->getOperand(1);
12585   SDValue ARMcc = N->getOperand(2);
12586   ARMCC::CondCodes CC =
12587     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12588 
12589   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
12590   // -> (brcond Chain BB CC CPSR Cmp)
12591   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
12592       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
12593       LHS->getOperand(0)->hasOneUse()) {
12594     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
12595     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
12596     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12597     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12598     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
12599         (LHS01C && LHS01C->getZExtValue() == 1) &&
12600         (LHS1C && LHS1C->getZExtValue() == 1) &&
12601         (RHSC && RHSC->getZExtValue() == 0)) {
12602       return DAG.getNode(
12603           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
12604           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
12605     }
12606   }
12607 
12608   return SDValue();
12609 }
12610 
12611 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
12612 SDValue
12613 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
12614   SDValue Cmp = N->getOperand(4);
12615   if (Cmp.getOpcode() != ARMISD::CMPZ)
12616     // Only looking at EQ and NE cases.
12617     return SDValue();
12618 
12619   EVT VT = N->getValueType(0);
12620   SDLoc dl(N);
12621   SDValue LHS = Cmp.getOperand(0);
12622   SDValue RHS = Cmp.getOperand(1);
12623   SDValue FalseVal = N->getOperand(0);
12624   SDValue TrueVal = N->getOperand(1);
12625   SDValue ARMcc = N->getOperand(2);
12626   ARMCC::CondCodes CC =
12627     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12628 
12629   // BFI is only available on V6T2+.
12630   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
12631     SDValue R = PerformCMOVToBFICombine(N, DAG);
12632     if (R)
12633       return R;
12634   }
12635 
12636   // Simplify
12637   //   mov     r1, r0
12638   //   cmp     r1, x
12639   //   mov     r0, y
12640   //   moveq   r0, x
12641   // to
12642   //   cmp     r0, x
12643   //   movne   r0, y
12644   //
12645   //   mov     r1, r0
12646   //   cmp     r1, x
12647   //   mov     r0, x
12648   //   movne   r0, y
12649   // to
12650   //   cmp     r0, x
12651   //   movne   r0, y
12652   /// FIXME: Turn this into a target neutral optimization?
12653   SDValue Res;
12654   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
12655     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
12656                       N->getOperand(3), Cmp);
12657   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
12658     SDValue ARMcc;
12659     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
12660     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
12661                       N->getOperand(3), NewCmp);
12662   }
12663 
12664   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
12665   // -> (cmov F T CC CPSR Cmp)
12666   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
12667     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
12668     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12669     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12670     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
12671         (LHS1C && LHS1C->getZExtValue() == 1) &&
12672         (RHSC && RHSC->getZExtValue() == 0)) {
12673       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
12674                          LHS->getOperand(2), LHS->getOperand(3),
12675                          LHS->getOperand(4));
12676     }
12677   }
12678 
12679   if (!VT.isInteger())
12680       return SDValue();
12681 
12682   // Materialize a boolean comparison for integers so we can avoid branching.
12683   if (isNullConstant(FalseVal)) {
12684     if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
12685       if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
12686         // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
12687         // right 5 bits will make that 32 be 1, otherwise it will be 0.
12688         // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
12689         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12690         Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
12691                           DAG.getConstant(5, dl, MVT::i32));
12692       } else {
12693         // CMOV 0, 1, ==, (CMPZ x, y) ->
12694         //     (ADDCARRY (SUB x, y), t:0, t:1)
12695         // where t = (SUBCARRY 0, (SUB x, y), 0)
12696         //
12697         // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
12698         // x != y. In other words, a carry C == 1 when x == y, C == 0
12699         // otherwise.
12700         // The final ADDCARRY computes
12701         //     x - y + (0 - (x - y)) + C == C
12702         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12703         SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12704         SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
12705         // ISD::SUBCARRY returns a borrow but we want the carry here
12706         // actually.
12707         SDValue Carry =
12708             DAG.getNode(ISD::SUB, dl, MVT::i32,
12709                         DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
12710         Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
12711       }
12712     } else if (CC == ARMCC::NE && !isNullConstant(RHS) &&
12713                (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
12714       // This seems pointless but will allow us to combine it further below.
12715       // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
12716       SDValue Sub =
12717           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
12718       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
12719                                           Sub.getValue(1), SDValue());
12720       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
12721                         N->getOperand(3), CPSRGlue.getValue(1));
12722       FalseVal = Sub;
12723     }
12724   } else if (isNullConstant(TrueVal)) {
12725     if (CC == ARMCC::EQ && !isNullConstant(RHS) &&
12726         (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
12727       // This seems pointless but will allow us to combine it further below
12728       // Note that we change == for != as this is the dual for the case above.
12729       // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUBS x, y), z, !=, (SUBS x, y):1
12730       SDValue Sub =
12731           DAG.getNode(ARMISD::SUBS, dl, DAG.getVTList(VT, MVT::i32), LHS, RHS);
12732       SDValue CPSRGlue = DAG.getCopyToReg(DAG.getEntryNode(), dl, ARM::CPSR,
12733                                           Sub.getValue(1), SDValue());
12734       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
12735                         DAG.getConstant(ARMCC::NE, dl, MVT::i32),
12736                         N->getOperand(3), CPSRGlue.getValue(1));
12737       FalseVal = Sub;
12738     }
12739   }
12740 
12741   // On Thumb1, the DAG above may be further combined if z is a power of 2
12742   // (z == 2 ^ K).
12743   // CMOV (SUBS x, y), z, !=, (SUBS x, y):1 ->
12744   //       merge t3, t4
12745   // where t1 = (SUBCARRY (SUB x, y), z, 0)
12746   //       t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
12747   //       t3 = if K != 0 then (SHL t2:0, K) else t2:0
12748   //       t4 = (SUB 1, t2:1)   [ we want a carry, not a borrow ]
12749   const APInt *TrueConst;
12750   if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
12751       (FalseVal.getOpcode() == ARMISD::SUBS) &&
12752       (FalseVal.getOperand(0) == LHS) && (FalseVal.getOperand(1) == RHS) &&
12753       (TrueConst = isPowerOf2Constant(TrueVal))) {
12754     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12755     unsigned ShiftAmount = TrueConst->logBase2();
12756     if (ShiftAmount)
12757       TrueVal = DAG.getConstant(1, dl, VT);
12758     SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
12759     Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
12760     // Make it a carry, not a borrow.
12761     SDValue Carry = DAG.getNode(
12762         ISD::SUB, dl, VT, DAG.getConstant(1, dl, MVT::i32), Res.getValue(1));
12763     Res = DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Res, Carry);
12764 
12765     if (ShiftAmount)
12766       Res = DAG.getNode(ISD::SHL, dl, VT, Res,
12767                         DAG.getConstant(ShiftAmount, dl, MVT::i32));
12768   }
12769 
12770   if (Res.getNode()) {
12771     KnownBits Known;
12772     DAG.computeKnownBits(SDValue(N,0), Known);
12773     // Capture demanded bits information that would be otherwise lost.
12774     if (Known.Zero == 0xfffffffe)
12775       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12776                         DAG.getValueType(MVT::i1));
12777     else if (Known.Zero == 0xffffff00)
12778       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12779                         DAG.getValueType(MVT::i8));
12780     else if (Known.Zero == 0xffff0000)
12781       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12782                         DAG.getValueType(MVT::i16));
12783   }
12784 
12785   return Res;
12786 }
12787 
12788 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
12789                                              DAGCombinerInfo &DCI) const {
12790   switch (N->getOpcode()) {
12791   default: break;
12792   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
12793   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
12794   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
12795   case ISD::SUB:        return PerformSUBCombine(N, DCI);
12796   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
12797   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
12798   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
12799   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
12800   case ARMISD::ADDC:
12801   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
12802   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
12803   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
12804   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
12805   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
12806   case ISD::STORE:      return PerformSTORECombine(N, DCI);
12807   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
12808   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
12809   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
12810   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
12811   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
12812   case ISD::FP_TO_SINT:
12813   case ISD::FP_TO_UINT:
12814     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
12815   case ISD::FDIV:
12816     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
12817   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
12818   case ISD::SHL:
12819   case ISD::SRA:
12820   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
12821   case ISD::SIGN_EXTEND:
12822   case ISD::ZERO_EXTEND:
12823   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
12824   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
12825   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
12826   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
12827   case ARMISD::VLD1DUP:
12828   case ARMISD::VLD2DUP:
12829   case ARMISD::VLD3DUP:
12830   case ARMISD::VLD4DUP:
12831     return PerformVLDCombine(N, DCI);
12832   case ARMISD::BUILD_VECTOR:
12833     return PerformARMBUILD_VECTORCombine(N, DCI);
12834   case ARMISD::SMULWB: {
12835     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12836     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12837     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12838       return SDValue();
12839     break;
12840   }
12841   case ARMISD::SMULWT: {
12842     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12843     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12844     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12845       return SDValue();
12846     break;
12847   }
12848   case ARMISD::SMLALBB: {
12849     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12850     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12851     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12852         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12853       return SDValue();
12854     break;
12855   }
12856   case ARMISD::SMLALBT: {
12857     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12858     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12859     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12860     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12861     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12862         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12863       return SDValue();
12864     break;
12865   }
12866   case ARMISD::SMLALTB: {
12867     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12868     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12869     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12870     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12871     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12872         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12873       return SDValue();
12874     break;
12875   }
12876   case ARMISD::SMLALTT: {
12877     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12878     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12879     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12880         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12881       return SDValue();
12882     break;
12883   }
12884   case ISD::INTRINSIC_VOID:
12885   case ISD::INTRINSIC_W_CHAIN:
12886     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12887     case Intrinsic::arm_neon_vld1:
12888     case Intrinsic::arm_neon_vld1x2:
12889     case Intrinsic::arm_neon_vld1x3:
12890     case Intrinsic::arm_neon_vld1x4:
12891     case Intrinsic::arm_neon_vld2:
12892     case Intrinsic::arm_neon_vld3:
12893     case Intrinsic::arm_neon_vld4:
12894     case Intrinsic::arm_neon_vld2lane:
12895     case Intrinsic::arm_neon_vld3lane:
12896     case Intrinsic::arm_neon_vld4lane:
12897     case Intrinsic::arm_neon_vld2dup:
12898     case Intrinsic::arm_neon_vld3dup:
12899     case Intrinsic::arm_neon_vld4dup:
12900     case Intrinsic::arm_neon_vst1:
12901     case Intrinsic::arm_neon_vst1x2:
12902     case Intrinsic::arm_neon_vst1x3:
12903     case Intrinsic::arm_neon_vst1x4:
12904     case Intrinsic::arm_neon_vst2:
12905     case Intrinsic::arm_neon_vst3:
12906     case Intrinsic::arm_neon_vst4:
12907     case Intrinsic::arm_neon_vst2lane:
12908     case Intrinsic::arm_neon_vst3lane:
12909     case Intrinsic::arm_neon_vst4lane:
12910       return PerformVLDCombine(N, DCI);
12911     default: break;
12912     }
12913     break;
12914   }
12915   return SDValue();
12916 }
12917 
12918 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12919                                                           EVT VT) const {
12920   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12921 }
12922 
12923 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12924                                                        unsigned,
12925                                                        unsigned,
12926                                                        bool *Fast) const {
12927   // Depends what it gets converted into if the type is weird.
12928   if (!VT.isSimple())
12929     return false;
12930 
12931   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12932   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12933 
12934   switch (VT.getSimpleVT().SimpleTy) {
12935   default:
12936     return false;
12937   case MVT::i8:
12938   case MVT::i16:
12939   case MVT::i32: {
12940     // Unaligned access can use (for example) LRDB, LRDH, LDR
12941     if (AllowsUnaligned) {
12942       if (Fast)
12943         *Fast = Subtarget->hasV7Ops();
12944       return true;
12945     }
12946     return false;
12947   }
12948   case MVT::f64:
12949   case MVT::v2f64: {
12950     // For any little-endian targets with neon, we can support unaligned ld/st
12951     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12952     // A big-endian target may also explicitly support unaligned accesses
12953     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12954       if (Fast)
12955         *Fast = true;
12956       return true;
12957     }
12958     return false;
12959   }
12960   }
12961 }
12962 
12963 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12964                        unsigned AlignCheck) {
12965   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12966           (DstAlign == 0 || DstAlign % AlignCheck == 0));
12967 }
12968 
12969 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12970                                            unsigned DstAlign, unsigned SrcAlign,
12971                                            bool IsMemset, bool ZeroMemset,
12972                                            bool MemcpyStrSrc,
12973                                            MachineFunction &MF) const {
12974   const Function &F = MF.getFunction();
12975 
12976   // See if we can use NEON instructions for this...
12977   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12978       !F.hasFnAttribute(Attribute::NoImplicitFloat)) {
12979     bool Fast;
12980     if (Size >= 16 &&
12981         (memOpAlign(SrcAlign, DstAlign, 16) ||
12982          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12983       return MVT::v2f64;
12984     } else if (Size >= 8 &&
12985                (memOpAlign(SrcAlign, DstAlign, 8) ||
12986                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12987                  Fast))) {
12988       return MVT::f64;
12989     }
12990   }
12991 
12992   // Let the target-independent logic figure it out.
12993   return MVT::Other;
12994 }
12995 
12996 // 64-bit integers are split into their high and low parts and held in two
12997 // different registers, so the trunc is free since the low register can just
12998 // be used.
12999 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
13000   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
13001     return false;
13002   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
13003   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
13004   return (SrcBits == 64 && DestBits == 32);
13005 }
13006 
13007 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
13008   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
13009       !DstVT.isInteger())
13010     return false;
13011   unsigned SrcBits = SrcVT.getSizeInBits();
13012   unsigned DestBits = DstVT.getSizeInBits();
13013   return (SrcBits == 64 && DestBits == 32);
13014 }
13015 
13016 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
13017   if (Val.getOpcode() != ISD::LOAD)
13018     return false;
13019 
13020   EVT VT1 = Val.getValueType();
13021   if (!VT1.isSimple() || !VT1.isInteger() ||
13022       !VT2.isSimple() || !VT2.isInteger())
13023     return false;
13024 
13025   switch (VT1.getSimpleVT().SimpleTy) {
13026   default: break;
13027   case MVT::i1:
13028   case MVT::i8:
13029   case MVT::i16:
13030     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
13031     return true;
13032   }
13033 
13034   return false;
13035 }
13036 
13037 bool ARMTargetLowering::isFNegFree(EVT VT) const {
13038   if (!VT.isSimple())
13039     return false;
13040 
13041   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
13042   // negate values directly (fneg is free). So, we don't want to let the DAG
13043   // combiner rewrite fneg into xors and some other instructions.  For f16 and
13044   // FullFP16 argument passing, some bitcast nodes may be introduced,
13045   // triggering this DAG combine rewrite, so we are avoiding that with this.
13046   switch (VT.getSimpleVT().SimpleTy) {
13047   default: break;
13048   case MVT::f16:
13049     return Subtarget->hasFullFP16();
13050   }
13051 
13052   return false;
13053 }
13054 
13055 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
13056   EVT VT = ExtVal.getValueType();
13057 
13058   if (!isTypeLegal(VT))
13059     return false;
13060 
13061   // Don't create a loadext if we can fold the extension into a wide/long
13062   // instruction.
13063   // If there's more than one user instruction, the loadext is desirable no
13064   // matter what.  There can be two uses by the same instruction.
13065   if (ExtVal->use_empty() ||
13066       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
13067     return true;
13068 
13069   SDNode *U = *ExtVal->use_begin();
13070   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
13071        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
13072     return false;
13073 
13074   return true;
13075 }
13076 
13077 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
13078   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
13079     return false;
13080 
13081   if (!isTypeLegal(EVT::getEVT(Ty1)))
13082     return false;
13083 
13084   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
13085 
13086   // Assuming the caller doesn't have a zeroext or signext return parameter,
13087   // truncation all the way down to i1 is valid.
13088   return true;
13089 }
13090 
13091 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
13092                                                 const AddrMode &AM, Type *Ty,
13093                                                 unsigned AS) const {
13094   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
13095     if (Subtarget->hasFPAO())
13096       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
13097     return 0;
13098   }
13099   return -1;
13100 }
13101 
13102 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
13103   if (V < 0)
13104     return false;
13105 
13106   unsigned Scale = 1;
13107   switch (VT.getSimpleVT().SimpleTy) {
13108   default: return false;
13109   case MVT::i1:
13110   case MVT::i8:
13111     // Scale == 1;
13112     break;
13113   case MVT::i16:
13114     // Scale == 2;
13115     Scale = 2;
13116     break;
13117   case MVT::i32:
13118     // Scale == 4;
13119     Scale = 4;
13120     break;
13121   }
13122 
13123   if ((V & (Scale - 1)) != 0)
13124     return false;
13125   V /= Scale;
13126   return V == (V & ((1LL << 5) - 1));
13127 }
13128 
13129 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
13130                                       const ARMSubtarget *Subtarget) {
13131   bool isNeg = false;
13132   if (V < 0) {
13133     isNeg = true;
13134     V = - V;
13135   }
13136 
13137   switch (VT.getSimpleVT().SimpleTy) {
13138   default: return false;
13139   case MVT::i1:
13140   case MVT::i8:
13141   case MVT::i16:
13142   case MVT::i32:
13143     // + imm12 or - imm8
13144     if (isNeg)
13145       return V == (V & ((1LL << 8) - 1));
13146     return V == (V & ((1LL << 12) - 1));
13147   case MVT::f32:
13148   case MVT::f64:
13149     // Same as ARM mode. FIXME: NEON?
13150     if (!Subtarget->hasVFP2())
13151       return false;
13152     if ((V & 3) != 0)
13153       return false;
13154     V >>= 2;
13155     return V == (V & ((1LL << 8) - 1));
13156   }
13157 }
13158 
13159 /// isLegalAddressImmediate - Return true if the integer value can be used
13160 /// as the offset of the target addressing mode for load / store of the
13161 /// given type.
13162 static bool isLegalAddressImmediate(int64_t V, EVT VT,
13163                                     const ARMSubtarget *Subtarget) {
13164   if (V == 0)
13165     return true;
13166 
13167   if (!VT.isSimple())
13168     return false;
13169 
13170   if (Subtarget->isThumb1Only())
13171     return isLegalT1AddressImmediate(V, VT);
13172   else if (Subtarget->isThumb2())
13173     return isLegalT2AddressImmediate(V, VT, Subtarget);
13174 
13175   // ARM mode.
13176   if (V < 0)
13177     V = - V;
13178   switch (VT.getSimpleVT().SimpleTy) {
13179   default: return false;
13180   case MVT::i1:
13181   case MVT::i8:
13182   case MVT::i32:
13183     // +- imm12
13184     return V == (V & ((1LL << 12) - 1));
13185   case MVT::i16:
13186     // +- imm8
13187     return V == (V & ((1LL << 8) - 1));
13188   case MVT::f32:
13189   case MVT::f64:
13190     if (!Subtarget->hasVFP2()) // FIXME: NEON?
13191       return false;
13192     if ((V & 3) != 0)
13193       return false;
13194     V >>= 2;
13195     return V == (V & ((1LL << 8) - 1));
13196   }
13197 }
13198 
13199 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
13200                                                       EVT VT) const {
13201   int Scale = AM.Scale;
13202   if (Scale < 0)
13203     return false;
13204 
13205   switch (VT.getSimpleVT().SimpleTy) {
13206   default: return false;
13207   case MVT::i1:
13208   case MVT::i8:
13209   case MVT::i16:
13210   case MVT::i32:
13211     if (Scale == 1)
13212       return true;
13213     // r + r << imm
13214     Scale = Scale & ~1;
13215     return Scale == 2 || Scale == 4 || Scale == 8;
13216   case MVT::i64:
13217     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
13218     // version in Thumb mode.
13219     // r + r
13220     if (Scale == 1)
13221       return true;
13222     // r * 2 (this can be lowered to r + r).
13223     if (!AM.HasBaseReg && Scale == 2)
13224       return true;
13225     return false;
13226   case MVT::isVoid:
13227     // Note, we allow "void" uses (basically, uses that aren't loads or
13228     // stores), because arm allows folding a scale into many arithmetic
13229     // operations.  This should be made more precise and revisited later.
13230 
13231     // Allow r << imm, but the imm has to be a multiple of two.
13232     if (Scale & 1) return false;
13233     return isPowerOf2_32(Scale);
13234   }
13235 }
13236 
13237 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
13238                                                       EVT VT) const {
13239   const int Scale = AM.Scale;
13240 
13241   // Negative scales are not supported in Thumb1.
13242   if (Scale < 0)
13243     return false;
13244 
13245   // Thumb1 addressing modes do not support register scaling excepting the
13246   // following cases:
13247   // 1. Scale == 1 means no scaling.
13248   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
13249   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
13250 }
13251 
13252 /// isLegalAddressingMode - Return true if the addressing mode represented
13253 /// by AM is legal for this target, for a load/store of the specified type.
13254 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
13255                                               const AddrMode &AM, Type *Ty,
13256                                               unsigned AS, Instruction *I) const {
13257   EVT VT = getValueType(DL, Ty, true);
13258   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
13259     return false;
13260 
13261   // Can never fold addr of global into load/store.
13262   if (AM.BaseGV)
13263     return false;
13264 
13265   switch (AM.Scale) {
13266   case 0:  // no scale reg, must be "r+i" or "r", or "i".
13267     break;
13268   default:
13269     // ARM doesn't support any R+R*scale+imm addr modes.
13270     if (AM.BaseOffs)
13271       return false;
13272 
13273     if (!VT.isSimple())
13274       return false;
13275 
13276     if (Subtarget->isThumb1Only())
13277       return isLegalT1ScaledAddressingMode(AM, VT);
13278 
13279     if (Subtarget->isThumb2())
13280       return isLegalT2ScaledAddressingMode(AM, VT);
13281 
13282     int Scale = AM.Scale;
13283     switch (VT.getSimpleVT().SimpleTy) {
13284     default: return false;
13285     case MVT::i1:
13286     case MVT::i8:
13287     case MVT::i32:
13288       if (Scale < 0) Scale = -Scale;
13289       if (Scale == 1)
13290         return true;
13291       // r + r << imm
13292       return isPowerOf2_32(Scale & ~1);
13293     case MVT::i16:
13294     case MVT::i64:
13295       // r +/- r
13296       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
13297         return true;
13298       // r * 2 (this can be lowered to r + r).
13299       if (!AM.HasBaseReg && Scale == 2)
13300         return true;
13301       return false;
13302 
13303     case MVT::isVoid:
13304       // Note, we allow "void" uses (basically, uses that aren't loads or
13305       // stores), because arm allows folding a scale into many arithmetic
13306       // operations.  This should be made more precise and revisited later.
13307 
13308       // Allow r << imm, but the imm has to be a multiple of two.
13309       if (Scale & 1) return false;
13310       return isPowerOf2_32(Scale);
13311     }
13312   }
13313   return true;
13314 }
13315 
13316 /// isLegalICmpImmediate - Return true if the specified immediate is legal
13317 /// icmp immediate, that is the target has icmp instructions which can compare
13318 /// a register against the immediate without having to materialize the
13319 /// immediate into a register.
13320 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13321   // Thumb2 and ARM modes can use cmn for negative immediates.
13322   if (!Subtarget->isThumb())
13323     return ARM_AM::getSOImmVal((uint32_t)Imm) != -1 ||
13324            ARM_AM::getSOImmVal(-(uint32_t)Imm) != -1;
13325   if (Subtarget->isThumb2())
13326     return ARM_AM::getT2SOImmVal((uint32_t)Imm) != -1 ||
13327            ARM_AM::getT2SOImmVal(-(uint32_t)Imm) != -1;
13328   // Thumb1 doesn't have cmn, and only 8-bit immediates.
13329   return Imm >= 0 && Imm <= 255;
13330 }
13331 
13332 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
13333 /// *or sub* immediate, that is the target has add or sub instructions which can
13334 /// add a register with the immediate without having to materialize the
13335 /// immediate into a register.
13336 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13337   // Same encoding for add/sub, just flip the sign.
13338   int64_t AbsImm = std::abs(Imm);
13339   if (!Subtarget->isThumb())
13340     return ARM_AM::getSOImmVal(AbsImm) != -1;
13341   if (Subtarget->isThumb2())
13342     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
13343   // Thumb1 only has 8-bit unsigned immediate.
13344   return AbsImm >= 0 && AbsImm <= 255;
13345 }
13346 
13347 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
13348                                       bool isSEXTLoad, SDValue &Base,
13349                                       SDValue &Offset, bool &isInc,
13350                                       SelectionDAG &DAG) {
13351   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13352     return false;
13353 
13354   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
13355     // AddressingMode 3
13356     Base = Ptr->getOperand(0);
13357     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13358       int RHSC = (int)RHS->getZExtValue();
13359       if (RHSC < 0 && RHSC > -256) {
13360         assert(Ptr->getOpcode() == ISD::ADD);
13361         isInc = false;
13362         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13363         return true;
13364       }
13365     }
13366     isInc = (Ptr->getOpcode() == ISD::ADD);
13367     Offset = Ptr->getOperand(1);
13368     return true;
13369   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
13370     // AddressingMode 2
13371     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13372       int RHSC = (int)RHS->getZExtValue();
13373       if (RHSC < 0 && RHSC > -0x1000) {
13374         assert(Ptr->getOpcode() == ISD::ADD);
13375         isInc = false;
13376         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13377         Base = Ptr->getOperand(0);
13378         return true;
13379       }
13380     }
13381 
13382     if (Ptr->getOpcode() == ISD::ADD) {
13383       isInc = true;
13384       ARM_AM::ShiftOpc ShOpcVal=
13385         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
13386       if (ShOpcVal != ARM_AM::no_shift) {
13387         Base = Ptr->getOperand(1);
13388         Offset = Ptr->getOperand(0);
13389       } else {
13390         Base = Ptr->getOperand(0);
13391         Offset = Ptr->getOperand(1);
13392       }
13393       return true;
13394     }
13395 
13396     isInc = (Ptr->getOpcode() == ISD::ADD);
13397     Base = Ptr->getOperand(0);
13398     Offset = Ptr->getOperand(1);
13399     return true;
13400   }
13401 
13402   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
13403   return false;
13404 }
13405 
13406 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
13407                                      bool isSEXTLoad, SDValue &Base,
13408                                      SDValue &Offset, bool &isInc,
13409                                      SelectionDAG &DAG) {
13410   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13411     return false;
13412 
13413   Base = Ptr->getOperand(0);
13414   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13415     int RHSC = (int)RHS->getZExtValue();
13416     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
13417       assert(Ptr->getOpcode() == ISD::ADD);
13418       isInc = false;
13419       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13420       return true;
13421     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
13422       isInc = Ptr->getOpcode() == ISD::ADD;
13423       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
13424       return true;
13425     }
13426   }
13427 
13428   return false;
13429 }
13430 
13431 /// getPreIndexedAddressParts - returns true by value, base pointer and
13432 /// offset pointer and addressing mode by reference if the node's address
13433 /// can be legally represented as pre-indexed load / store address.
13434 bool
13435 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
13436                                              SDValue &Offset,
13437                                              ISD::MemIndexedMode &AM,
13438                                              SelectionDAG &DAG) const {
13439   if (Subtarget->isThumb1Only())
13440     return false;
13441 
13442   EVT VT;
13443   SDValue Ptr;
13444   bool isSEXTLoad = false;
13445   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13446     Ptr = LD->getBasePtr();
13447     VT  = LD->getMemoryVT();
13448     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13449   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13450     Ptr = ST->getBasePtr();
13451     VT  = ST->getMemoryVT();
13452   } else
13453     return false;
13454 
13455   bool isInc;
13456   bool isLegal = false;
13457   if (Subtarget->isThumb2())
13458     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13459                                        Offset, isInc, DAG);
13460   else
13461     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13462                                         Offset, isInc, DAG);
13463   if (!isLegal)
13464     return false;
13465 
13466   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
13467   return true;
13468 }
13469 
13470 /// getPostIndexedAddressParts - returns true by value, base pointer and
13471 /// offset pointer and addressing mode by reference if this node can be
13472 /// combined with a load / store to form a post-indexed load / store.
13473 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
13474                                                    SDValue &Base,
13475                                                    SDValue &Offset,
13476                                                    ISD::MemIndexedMode &AM,
13477                                                    SelectionDAG &DAG) const {
13478   EVT VT;
13479   SDValue Ptr;
13480   bool isSEXTLoad = false, isNonExt;
13481   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13482     VT  = LD->getMemoryVT();
13483     Ptr = LD->getBasePtr();
13484     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13485     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
13486   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13487     VT  = ST->getMemoryVT();
13488     Ptr = ST->getBasePtr();
13489     isNonExt = !ST->isTruncatingStore();
13490   } else
13491     return false;
13492 
13493   if (Subtarget->isThumb1Only()) {
13494     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
13495     // must be non-extending/truncating, i32, with an offset of 4.
13496     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
13497     if (Op->getOpcode() != ISD::ADD || !isNonExt)
13498       return false;
13499     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
13500     if (!RHS || RHS->getZExtValue() != 4)
13501       return false;
13502 
13503     Offset = Op->getOperand(1);
13504     Base = Op->getOperand(0);
13505     AM = ISD::POST_INC;
13506     return true;
13507   }
13508 
13509   bool isInc;
13510   bool isLegal = false;
13511   if (Subtarget->isThumb2())
13512     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13513                                        isInc, DAG);
13514   else
13515     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13516                                         isInc, DAG);
13517   if (!isLegal)
13518     return false;
13519 
13520   if (Ptr != Base) {
13521     // Swap base ptr and offset to catch more post-index load / store when
13522     // it's legal. In Thumb2 mode, offset must be an immediate.
13523     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
13524         !Subtarget->isThumb2())
13525       std::swap(Base, Offset);
13526 
13527     // Post-indexed load / store update the base pointer.
13528     if (Ptr != Base)
13529       return false;
13530   }
13531 
13532   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
13533   return true;
13534 }
13535 
13536 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13537                                                       KnownBits &Known,
13538                                                       const APInt &DemandedElts,
13539                                                       const SelectionDAG &DAG,
13540                                                       unsigned Depth) const {
13541   unsigned BitWidth = Known.getBitWidth();
13542   Known.resetAll();
13543   switch (Op.getOpcode()) {
13544   default: break;
13545   case ARMISD::ADDC:
13546   case ARMISD::ADDE:
13547   case ARMISD::SUBC:
13548   case ARMISD::SUBE:
13549     // Special cases when we convert a carry to a boolean.
13550     if (Op.getResNo() == 0) {
13551       SDValue LHS = Op.getOperand(0);
13552       SDValue RHS = Op.getOperand(1);
13553       // (ADDE 0, 0, C) will give us a single bit.
13554       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
13555           isNullConstant(RHS)) {
13556         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13557         return;
13558       }
13559     }
13560     break;
13561   case ARMISD::CMOV: {
13562     // Bits are known zero/one if known on the LHS and RHS.
13563     DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1);
13564     if (Known.isUnknown())
13565       return;
13566 
13567     KnownBits KnownRHS;
13568     DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1);
13569     Known.Zero &= KnownRHS.Zero;
13570     Known.One  &= KnownRHS.One;
13571     return;
13572   }
13573   case ISD::INTRINSIC_W_CHAIN: {
13574     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
13575     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
13576     switch (IntID) {
13577     default: return;
13578     case Intrinsic::arm_ldaex:
13579     case Intrinsic::arm_ldrex: {
13580       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
13581       unsigned MemBits = VT.getScalarSizeInBits();
13582       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
13583       return;
13584     }
13585     }
13586   }
13587   case ARMISD::BFI: {
13588     // Conservatively, we can recurse down the first operand
13589     // and just mask out all affected bits.
13590     DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1);
13591 
13592     // The operand to BFI is already a mask suitable for removing the bits it
13593     // sets.
13594     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
13595     const APInt &Mask = CI->getAPIntValue();
13596     Known.Zero &= Mask;
13597     Known.One &= Mask;
13598     return;
13599   }
13600   }
13601 }
13602 
13603 bool
13604 ARMTargetLowering::targetShrinkDemandedConstant(SDValue Op,
13605                                                 const APInt &DemandedAPInt,
13606                                                 TargetLoweringOpt &TLO) const {
13607   // Delay optimization, so we don't have to deal with illegal types, or block
13608   // optimizations.
13609   if (!TLO.LegalOps)
13610     return false;
13611 
13612   // Only optimize AND for now.
13613   if (Op.getOpcode() != ISD::AND)
13614     return false;
13615 
13616   EVT VT = Op.getValueType();
13617 
13618   // Ignore vectors.
13619   if (VT.isVector())
13620     return false;
13621 
13622   assert(VT == MVT::i32 && "Unexpected integer type");
13623 
13624   // Make sure the RHS really is a constant.
13625   ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13626   if (!C)
13627     return false;
13628 
13629   unsigned Mask = C->getZExtValue();
13630 
13631   unsigned Demanded = DemandedAPInt.getZExtValue();
13632   unsigned ShrunkMask = Mask & Demanded;
13633   unsigned ExpandedMask = Mask | ~Demanded;
13634 
13635   // If the mask is all zeros, let the target-independent code replace the
13636   // result with zero.
13637   if (ShrunkMask == 0)
13638     return false;
13639 
13640   // If the mask is all ones, erase the AND. (Currently, the target-independent
13641   // code won't do this, so we have to do it explicitly to avoid an infinite
13642   // loop in obscure cases.)
13643   if (ExpandedMask == ~0U)
13644     return TLO.CombineTo(Op, Op.getOperand(0));
13645 
13646   auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
13647     return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
13648   };
13649   auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
13650     if (NewMask == Mask)
13651       return true;
13652     SDLoc DL(Op);
13653     SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
13654     SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
13655     return TLO.CombineTo(Op, NewOp);
13656   };
13657 
13658   // Prefer uxtb mask.
13659   if (IsLegalMask(0xFF))
13660     return UseMask(0xFF);
13661 
13662   // Prefer uxth mask.
13663   if (IsLegalMask(0xFFFF))
13664     return UseMask(0xFFFF);
13665 
13666   // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
13667   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
13668   if (ShrunkMask < 256)
13669     return UseMask(ShrunkMask);
13670 
13671   // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
13672   // FIXME: Prefer a contiguous sequence of bits for other optimizations.
13673   if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
13674     return UseMask(ExpandedMask);
13675 
13676   // Potential improvements:
13677   //
13678   // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
13679   // We could try to prefer Thumb1 immediates which can be lowered to a
13680   // two-instruction sequence.
13681   // We could try to recognize more legal ARM/Thumb2 immediates here.
13682 
13683   return false;
13684 }
13685 
13686 
13687 //===----------------------------------------------------------------------===//
13688 //                           ARM Inline Assembly Support
13689 //===----------------------------------------------------------------------===//
13690 
13691 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
13692   // Looking for "rev" which is V6+.
13693   if (!Subtarget->hasV6Ops())
13694     return false;
13695 
13696   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13697   std::string AsmStr = IA->getAsmString();
13698   SmallVector<StringRef, 4> AsmPieces;
13699   SplitString(AsmStr, AsmPieces, ";\n");
13700 
13701   switch (AsmPieces.size()) {
13702   default: return false;
13703   case 1:
13704     AsmStr = AsmPieces[0];
13705     AsmPieces.clear();
13706     SplitString(AsmStr, AsmPieces, " \t,");
13707 
13708     // rev $0, $1
13709     if (AsmPieces.size() == 3 &&
13710         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
13711         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
13712       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13713       if (Ty && Ty->getBitWidth() == 32)
13714         return IntrinsicLowering::LowerToByteSwap(CI);
13715     }
13716     break;
13717   }
13718 
13719   return false;
13720 }
13721 
13722 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
13723   // At this point, we have to lower this constraint to something else, so we
13724   // lower it to an "r" or "w". However, by doing this we will force the result
13725   // to be in register, while the X constraint is much more permissive.
13726   //
13727   // Although we are correct (we are free to emit anything, without
13728   // constraints), we might break use cases that would expect us to be more
13729   // efficient and emit something else.
13730   if (!Subtarget->hasVFP2())
13731     return "r";
13732   if (ConstraintVT.isFloatingPoint())
13733     return "w";
13734   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
13735      (ConstraintVT.getSizeInBits() == 64 ||
13736       ConstraintVT.getSizeInBits() == 128))
13737     return "w";
13738 
13739   return "r";
13740 }
13741 
13742 /// getConstraintType - Given a constraint letter, return the type of
13743 /// constraint it is for this target.
13744 ARMTargetLowering::ConstraintType
13745 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
13746   if (Constraint.size() == 1) {
13747     switch (Constraint[0]) {
13748     default:  break;
13749     case 'l': return C_RegisterClass;
13750     case 'w': return C_RegisterClass;
13751     case 'h': return C_RegisterClass;
13752     case 'x': return C_RegisterClass;
13753     case 't': return C_RegisterClass;
13754     case 'j': return C_Other; // Constant for movw.
13755       // An address with a single base register. Due to the way we
13756       // currently handle addresses it is the same as an 'r' memory constraint.
13757     case 'Q': return C_Memory;
13758     }
13759   } else if (Constraint.size() == 2) {
13760     switch (Constraint[0]) {
13761     default: break;
13762     // All 'U+' constraints are addresses.
13763     case 'U': return C_Memory;
13764     }
13765   }
13766   return TargetLowering::getConstraintType(Constraint);
13767 }
13768 
13769 /// Examine constraint type and operand type and determine a weight value.
13770 /// This object must already have been set up with the operand type
13771 /// and the current alternative constraint selected.
13772 TargetLowering::ConstraintWeight
13773 ARMTargetLowering::getSingleConstraintMatchWeight(
13774     AsmOperandInfo &info, const char *constraint) const {
13775   ConstraintWeight weight = CW_Invalid;
13776   Value *CallOperandVal = info.CallOperandVal;
13777     // If we don't have a value, we can't do a match,
13778     // but allow it at the lowest weight.
13779   if (!CallOperandVal)
13780     return CW_Default;
13781   Type *type = CallOperandVal->getType();
13782   // Look at the constraint type.
13783   switch (*constraint) {
13784   default:
13785     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13786     break;
13787   case 'l':
13788     if (type->isIntegerTy()) {
13789       if (Subtarget->isThumb())
13790         weight = CW_SpecificReg;
13791       else
13792         weight = CW_Register;
13793     }
13794     break;
13795   case 'w':
13796     if (type->isFloatingPointTy())
13797       weight = CW_Register;
13798     break;
13799   }
13800   return weight;
13801 }
13802 
13803 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
13804 
13805 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
13806     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
13807   if (Constraint.size() == 1) {
13808     // GCC ARM Constraint Letters
13809     switch (Constraint[0]) {
13810     case 'l': // Low regs or general regs.
13811       if (Subtarget->isThumb())
13812         return RCPair(0U, &ARM::tGPRRegClass);
13813       return RCPair(0U, &ARM::GPRRegClass);
13814     case 'h': // High regs or no regs.
13815       if (Subtarget->isThumb())
13816         return RCPair(0U, &ARM::hGPRRegClass);
13817       break;
13818     case 'r':
13819       if (Subtarget->isThumb1Only())
13820         return RCPair(0U, &ARM::tGPRRegClass);
13821       return RCPair(0U, &ARM::GPRRegClass);
13822     case 'w':
13823       if (VT == MVT::Other)
13824         break;
13825       if (VT == MVT::f32)
13826         return RCPair(0U, &ARM::SPRRegClass);
13827       if (VT.getSizeInBits() == 64)
13828         return RCPair(0U, &ARM::DPRRegClass);
13829       if (VT.getSizeInBits() == 128)
13830         return RCPair(0U, &ARM::QPRRegClass);
13831       break;
13832     case 'x':
13833       if (VT == MVT::Other)
13834         break;
13835       if (VT == MVT::f32)
13836         return RCPair(0U, &ARM::SPR_8RegClass);
13837       if (VT.getSizeInBits() == 64)
13838         return RCPair(0U, &ARM::DPR_8RegClass);
13839       if (VT.getSizeInBits() == 128)
13840         return RCPair(0U, &ARM::QPR_8RegClass);
13841       break;
13842     case 't':
13843       if (VT == MVT::Other)
13844         break;
13845       if (VT == MVT::f32 || VT == MVT::i32)
13846         return RCPair(0U, &ARM::SPRRegClass);
13847       if (VT.getSizeInBits() == 64)
13848         return RCPair(0U, &ARM::DPR_VFP2RegClass);
13849       if (VT.getSizeInBits() == 128)
13850         return RCPair(0U, &ARM::QPR_VFP2RegClass);
13851       break;
13852     }
13853   }
13854   if (StringRef("{cc}").equals_lower(Constraint))
13855     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
13856 
13857   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13858 }
13859 
13860 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13861 /// vector.  If it is invalid, don't add anything to Ops.
13862 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13863                                                      std::string &Constraint,
13864                                                      std::vector<SDValue>&Ops,
13865                                                      SelectionDAG &DAG) const {
13866   SDValue Result;
13867 
13868   // Currently only support length 1 constraints.
13869   if (Constraint.length() != 1) return;
13870 
13871   char ConstraintLetter = Constraint[0];
13872   switch (ConstraintLetter) {
13873   default: break;
13874   case 'j':
13875   case 'I': case 'J': case 'K': case 'L':
13876   case 'M': case 'N': case 'O':
13877     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
13878     if (!C)
13879       return;
13880 
13881     int64_t CVal64 = C->getSExtValue();
13882     int CVal = (int) CVal64;
13883     // None of these constraints allow values larger than 32 bits.  Check
13884     // that the value fits in an int.
13885     if (CVal != CVal64)
13886       return;
13887 
13888     switch (ConstraintLetter) {
13889       case 'j':
13890         // Constant suitable for movw, must be between 0 and
13891         // 65535.
13892         if (Subtarget->hasV6T2Ops())
13893           if (CVal >= 0 && CVal <= 65535)
13894             break;
13895         return;
13896       case 'I':
13897         if (Subtarget->isThumb1Only()) {
13898           // This must be a constant between 0 and 255, for ADD
13899           // immediates.
13900           if (CVal >= 0 && CVal <= 255)
13901             break;
13902         } else if (Subtarget->isThumb2()) {
13903           // A constant that can be used as an immediate value in a
13904           // data-processing instruction.
13905           if (ARM_AM::getT2SOImmVal(CVal) != -1)
13906             break;
13907         } else {
13908           // A constant that can be used as an immediate value in a
13909           // data-processing instruction.
13910           if (ARM_AM::getSOImmVal(CVal) != -1)
13911             break;
13912         }
13913         return;
13914 
13915       case 'J':
13916         if (Subtarget->isThumb1Only()) {
13917           // This must be a constant between -255 and -1, for negated ADD
13918           // immediates. This can be used in GCC with an "n" modifier that
13919           // prints the negated value, for use with SUB instructions. It is
13920           // not useful otherwise but is implemented for compatibility.
13921           if (CVal >= -255 && CVal <= -1)
13922             break;
13923         } else {
13924           // This must be a constant between -4095 and 4095. It is not clear
13925           // what this constraint is intended for. Implemented for
13926           // compatibility with GCC.
13927           if (CVal >= -4095 && CVal <= 4095)
13928             break;
13929         }
13930         return;
13931 
13932       case 'K':
13933         if (Subtarget->isThumb1Only()) {
13934           // A 32-bit value where only one byte has a nonzero value. Exclude
13935           // zero to match GCC. This constraint is used by GCC internally for
13936           // constants that can be loaded with a move/shift combination.
13937           // It is not useful otherwise but is implemented for compatibility.
13938           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
13939             break;
13940         } else if (Subtarget->isThumb2()) {
13941           // A constant whose bitwise inverse can be used as an immediate
13942           // value in a data-processing instruction. This can be used in GCC
13943           // with a "B" modifier that prints the inverted value, for use with
13944           // BIC and MVN instructions. It is not useful otherwise but is
13945           // implemented for compatibility.
13946           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
13947             break;
13948         } else {
13949           // A constant whose bitwise inverse can be used as an immediate
13950           // value in a data-processing instruction. This can be used in GCC
13951           // with a "B" modifier that prints the inverted value, for use with
13952           // BIC and MVN instructions. It is not useful otherwise but is
13953           // implemented for compatibility.
13954           if (ARM_AM::getSOImmVal(~CVal) != -1)
13955             break;
13956         }
13957         return;
13958 
13959       case 'L':
13960         if (Subtarget->isThumb1Only()) {
13961           // This must be a constant between -7 and 7,
13962           // for 3-operand ADD/SUB immediate instructions.
13963           if (CVal >= -7 && CVal < 7)
13964             break;
13965         } else if (Subtarget->isThumb2()) {
13966           // A constant whose negation can be used as an immediate value in a
13967           // data-processing instruction. This can be used in GCC with an "n"
13968           // modifier that prints the negated value, for use with SUB
13969           // instructions. It is not useful otherwise but is implemented for
13970           // compatibility.
13971           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
13972             break;
13973         } else {
13974           // A constant whose negation can be used as an immediate value in a
13975           // data-processing instruction. This can be used in GCC with an "n"
13976           // modifier that prints the negated value, for use with SUB
13977           // instructions. It is not useful otherwise but is implemented for
13978           // compatibility.
13979           if (ARM_AM::getSOImmVal(-CVal) != -1)
13980             break;
13981         }
13982         return;
13983 
13984       case 'M':
13985         if (Subtarget->isThumb1Only()) {
13986           // This must be a multiple of 4 between 0 and 1020, for
13987           // ADD sp + immediate.
13988           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
13989             break;
13990         } else {
13991           // A power of two or a constant between 0 and 32.  This is used in
13992           // GCC for the shift amount on shifted register operands, but it is
13993           // useful in general for any shift amounts.
13994           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
13995             break;
13996         }
13997         return;
13998 
13999       case 'N':
14000         if (Subtarget->isThumb()) {  // FIXME thumb2
14001           // This must be a constant between 0 and 31, for shift amounts.
14002           if (CVal >= 0 && CVal <= 31)
14003             break;
14004         }
14005         return;
14006 
14007       case 'O':
14008         if (Subtarget->isThumb()) {  // FIXME thumb2
14009           // This must be a multiple of 4 between -508 and 508, for
14010           // ADD/SUB sp = sp + immediate.
14011           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
14012             break;
14013         }
14014         return;
14015     }
14016     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
14017     break;
14018   }
14019 
14020   if (Result.getNode()) {
14021     Ops.push_back(Result);
14022     return;
14023   }
14024   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
14025 }
14026 
14027 static RTLIB::Libcall getDivRemLibcall(
14028     const SDNode *N, MVT::SimpleValueType SVT) {
14029   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
14030           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
14031          "Unhandled Opcode in getDivRemLibcall");
14032   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
14033                   N->getOpcode() == ISD::SREM;
14034   RTLIB::Libcall LC;
14035   switch (SVT) {
14036   default: llvm_unreachable("Unexpected request for libcall!");
14037   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
14038   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
14039   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
14040   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
14041   }
14042   return LC;
14043 }
14044 
14045 static TargetLowering::ArgListTy getDivRemArgList(
14046     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
14047   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
14048           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
14049          "Unhandled Opcode in getDivRemArgList");
14050   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
14051                   N->getOpcode() == ISD::SREM;
14052   TargetLowering::ArgListTy Args;
14053   TargetLowering::ArgListEntry Entry;
14054   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
14055     EVT ArgVT = N->getOperand(i).getValueType();
14056     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
14057     Entry.Node = N->getOperand(i);
14058     Entry.Ty = ArgTy;
14059     Entry.IsSExt = isSigned;
14060     Entry.IsZExt = !isSigned;
14061     Args.push_back(Entry);
14062   }
14063   if (Subtarget->isTargetWindows() && Args.size() >= 2)
14064     std::swap(Args[0], Args[1]);
14065   return Args;
14066 }
14067 
14068 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
14069   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
14070           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
14071           Subtarget->isTargetWindows()) &&
14072          "Register-based DivRem lowering only");
14073   unsigned Opcode = Op->getOpcode();
14074   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
14075          "Invalid opcode for Div/Rem lowering");
14076   bool isSigned = (Opcode == ISD::SDIVREM);
14077   EVT VT = Op->getValueType(0);
14078   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
14079   SDLoc dl(Op);
14080 
14081   // If the target has hardware divide, use divide + multiply + subtract:
14082   //     div = a / b
14083   //     rem = a - b * div
14084   //     return {div, rem}
14085   // This should be lowered into UDIV/SDIV + MLS later on.
14086   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
14087                                         : Subtarget->hasDivideInARMMode();
14088   if (hasDivide && Op->getValueType(0).isSimple() &&
14089       Op->getSimpleValueType(0) == MVT::i32) {
14090     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
14091     const SDValue Dividend = Op->getOperand(0);
14092     const SDValue Divisor = Op->getOperand(1);
14093     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
14094     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
14095     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
14096 
14097     SDValue Values[2] = {Div, Rem};
14098     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
14099   }
14100 
14101   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
14102                                        VT.getSimpleVT().SimpleTy);
14103   SDValue InChain = DAG.getEntryNode();
14104 
14105   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
14106                                                     DAG.getContext(),
14107                                                     Subtarget);
14108 
14109   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
14110                                          getPointerTy(DAG.getDataLayout()));
14111 
14112   Type *RetTy = StructType::get(Ty, Ty);
14113 
14114   if (Subtarget->isTargetWindows())
14115     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
14116 
14117   TargetLowering::CallLoweringInfo CLI(DAG);
14118   CLI.setDebugLoc(dl).setChain(InChain)
14119     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
14120     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
14121 
14122   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
14123   return CallInfo.first;
14124 }
14125 
14126 // Lowers REM using divmod helpers
14127 // see RTABI section 4.2/4.3
14128 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
14129   // Build return types (div and rem)
14130   std::vector<Type*> RetTyParams;
14131   Type *RetTyElement;
14132 
14133   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
14134   default: llvm_unreachable("Unexpected request for libcall!");
14135   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
14136   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
14137   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
14138   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
14139   }
14140 
14141   RetTyParams.push_back(RetTyElement);
14142   RetTyParams.push_back(RetTyElement);
14143   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
14144   Type *RetTy = StructType::get(*DAG.getContext(), ret);
14145 
14146   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
14147                                                              SimpleTy);
14148   SDValue InChain = DAG.getEntryNode();
14149   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
14150                                                     Subtarget);
14151   bool isSigned = N->getOpcode() == ISD::SREM;
14152   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
14153                                          getPointerTy(DAG.getDataLayout()));
14154 
14155   if (Subtarget->isTargetWindows())
14156     InChain = WinDBZCheckDenominator(DAG, N, InChain);
14157 
14158   // Lower call
14159   CallLoweringInfo CLI(DAG);
14160   CLI.setChain(InChain)
14161      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
14162      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
14163   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
14164 
14165   // Return second (rem) result operand (first contains div)
14166   SDNode *ResNode = CallResult.first.getNode();
14167   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
14168   return ResNode->getOperand(1);
14169 }
14170 
14171 SDValue
14172 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
14173   assert(Subtarget->isTargetWindows() && "unsupported target platform");
14174   SDLoc DL(Op);
14175 
14176   // Get the inputs.
14177   SDValue Chain = Op.getOperand(0);
14178   SDValue Size  = Op.getOperand(1);
14179 
14180   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
14181           "no-stack-arg-probe")) {
14182     unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14183     SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
14184     Chain = SP.getValue(1);
14185     SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
14186     if (Align)
14187       SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
14188                        DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
14189     Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
14190     SDValue Ops[2] = { SP, Chain };
14191     return DAG.getMergeValues(Ops, DL);
14192   }
14193 
14194   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
14195                               DAG.getConstant(2, DL, MVT::i32));
14196 
14197   SDValue Flag;
14198   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
14199   Flag = Chain.getValue(1);
14200 
14201   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14202   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
14203 
14204   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
14205   Chain = NewSP.getValue(1);
14206 
14207   SDValue Ops[2] = { NewSP, Chain };
14208   return DAG.getMergeValues(Ops, DL);
14209 }
14210 
14211 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
14212   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
14213          "Unexpected type for custom-lowering FP_EXTEND");
14214 
14215   RTLIB::Libcall LC;
14216   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
14217 
14218   SDValue SrcVal = Op.getOperand(0);
14219   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
14220                      SDLoc(Op)).first;
14221 }
14222 
14223 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
14224   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
14225          Subtarget->isFPOnlySP() &&
14226          "Unexpected type for custom-lowering FP_ROUND");
14227 
14228   RTLIB::Libcall LC;
14229   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
14230 
14231   SDValue SrcVal = Op.getOperand(0);
14232   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
14233                      SDLoc(Op)).first;
14234 }
14235 
14236 bool
14237 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14238   // The ARM target isn't yet aware of offsets.
14239   return false;
14240 }
14241 
14242 bool ARM::isBitFieldInvertedMask(unsigned v) {
14243   if (v == 0xffffffff)
14244     return false;
14245 
14246   // there can be 1's on either or both "outsides", all the "inside"
14247   // bits must be 0's
14248   return isShiftedMask_32(~v);
14249 }
14250 
14251 /// isFPImmLegal - Returns true if the target can instruction select the
14252 /// specified FP immediate natively. If false, the legalizer will
14253 /// materialize the FP immediate as a load from a constant pool.
14254 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
14255   if (!Subtarget->hasVFP3())
14256     return false;
14257   if (VT == MVT::f16 && Subtarget->hasFullFP16())
14258     return ARM_AM::getFP16Imm(Imm) != -1;
14259   if (VT == MVT::f32)
14260     return ARM_AM::getFP32Imm(Imm) != -1;
14261   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
14262     return ARM_AM::getFP64Imm(Imm) != -1;
14263   return false;
14264 }
14265 
14266 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
14267 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
14268 /// specified in the intrinsic calls.
14269 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14270                                            const CallInst &I,
14271                                            MachineFunction &MF,
14272                                            unsigned Intrinsic) const {
14273   switch (Intrinsic) {
14274   case Intrinsic::arm_neon_vld1:
14275   case Intrinsic::arm_neon_vld2:
14276   case Intrinsic::arm_neon_vld3:
14277   case Intrinsic::arm_neon_vld4:
14278   case Intrinsic::arm_neon_vld2lane:
14279   case Intrinsic::arm_neon_vld3lane:
14280   case Intrinsic::arm_neon_vld4lane:
14281   case Intrinsic::arm_neon_vld2dup:
14282   case Intrinsic::arm_neon_vld3dup:
14283   case Intrinsic::arm_neon_vld4dup: {
14284     Info.opc = ISD::INTRINSIC_W_CHAIN;
14285     // Conservatively set memVT to the entire set of vectors loaded.
14286     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14287     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
14288     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14289     Info.ptrVal = I.getArgOperand(0);
14290     Info.offset = 0;
14291     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
14292     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
14293     // volatile loads with NEON intrinsics not supported
14294     Info.flags = MachineMemOperand::MOLoad;
14295     return true;
14296   }
14297   case Intrinsic::arm_neon_vld1x2:
14298   case Intrinsic::arm_neon_vld1x3:
14299   case Intrinsic::arm_neon_vld1x4: {
14300     Info.opc = ISD::INTRINSIC_W_CHAIN;
14301     // Conservatively set memVT to the entire set of vectors loaded.
14302     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14303     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
14304     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14305     Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
14306     Info.offset = 0;
14307     Info.align = 0;
14308     // volatile loads with NEON intrinsics not supported
14309     Info.flags = MachineMemOperand::MOLoad;
14310     return true;
14311   }
14312   case Intrinsic::arm_neon_vst1:
14313   case Intrinsic::arm_neon_vst2:
14314   case Intrinsic::arm_neon_vst3:
14315   case Intrinsic::arm_neon_vst4:
14316   case Intrinsic::arm_neon_vst2lane:
14317   case Intrinsic::arm_neon_vst3lane:
14318   case Intrinsic::arm_neon_vst4lane: {
14319     Info.opc = ISD::INTRINSIC_VOID;
14320     // Conservatively set memVT to the entire set of vectors stored.
14321     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14322     unsigned NumElts = 0;
14323     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
14324       Type *ArgTy = I.getArgOperand(ArgI)->getType();
14325       if (!ArgTy->isVectorTy())
14326         break;
14327       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
14328     }
14329     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14330     Info.ptrVal = I.getArgOperand(0);
14331     Info.offset = 0;
14332     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
14333     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
14334     // volatile stores with NEON intrinsics not supported
14335     Info.flags = MachineMemOperand::MOStore;
14336     return true;
14337   }
14338   case Intrinsic::arm_neon_vst1x2:
14339   case Intrinsic::arm_neon_vst1x3:
14340   case Intrinsic::arm_neon_vst1x4: {
14341     Info.opc = ISD::INTRINSIC_VOID;
14342     // Conservatively set memVT to the entire set of vectors stored.
14343     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14344     unsigned NumElts = 0;
14345     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
14346       Type *ArgTy = I.getArgOperand(ArgI)->getType();
14347       if (!ArgTy->isVectorTy())
14348         break;
14349       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
14350     }
14351     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14352     Info.ptrVal = I.getArgOperand(0);
14353     Info.offset = 0;
14354     Info.align = 0;
14355     // volatile stores with NEON intrinsics not supported
14356     Info.flags = MachineMemOperand::MOStore;
14357     return true;
14358   }
14359   case Intrinsic::arm_ldaex:
14360   case Intrinsic::arm_ldrex: {
14361     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14362     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
14363     Info.opc = ISD::INTRINSIC_W_CHAIN;
14364     Info.memVT = MVT::getVT(PtrTy->getElementType());
14365     Info.ptrVal = I.getArgOperand(0);
14366     Info.offset = 0;
14367     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
14368     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
14369     return true;
14370   }
14371   case Intrinsic::arm_stlex:
14372   case Intrinsic::arm_strex: {
14373     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14374     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
14375     Info.opc = ISD::INTRINSIC_W_CHAIN;
14376     Info.memVT = MVT::getVT(PtrTy->getElementType());
14377     Info.ptrVal = I.getArgOperand(1);
14378     Info.offset = 0;
14379     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
14380     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
14381     return true;
14382   }
14383   case Intrinsic::arm_stlexd:
14384   case Intrinsic::arm_strexd:
14385     Info.opc = ISD::INTRINSIC_W_CHAIN;
14386     Info.memVT = MVT::i64;
14387     Info.ptrVal = I.getArgOperand(2);
14388     Info.offset = 0;
14389     Info.align = 8;
14390     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
14391     return true;
14392 
14393   case Intrinsic::arm_ldaexd:
14394   case Intrinsic::arm_ldrexd:
14395     Info.opc = ISD::INTRINSIC_W_CHAIN;
14396     Info.memVT = MVT::i64;
14397     Info.ptrVal = I.getArgOperand(0);
14398     Info.offset = 0;
14399     Info.align = 8;
14400     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
14401     return true;
14402 
14403   default:
14404     break;
14405   }
14406 
14407   return false;
14408 }
14409 
14410 /// Returns true if it is beneficial to convert a load of a constant
14411 /// to just the constant itself.
14412 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
14413                                                           Type *Ty) const {
14414   assert(Ty->isIntegerTy());
14415 
14416   unsigned Bits = Ty->getPrimitiveSizeInBits();
14417   if (Bits == 0 || Bits > 32)
14418     return false;
14419   return true;
14420 }
14421 
14422 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
14423                                                 unsigned Index) const {
14424   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
14425     return false;
14426 
14427   return (Index == 0 || Index == ResVT.getVectorNumElements());
14428 }
14429 
14430 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
14431                                         ARM_MB::MemBOpt Domain) const {
14432   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14433 
14434   // First, if the target has no DMB, see what fallback we can use.
14435   if (!Subtarget->hasDataBarrier()) {
14436     // Some ARMv6 cpus can support data barriers with an mcr instruction.
14437     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
14438     // here.
14439     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
14440       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
14441       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
14442                         Builder.getInt32(0), Builder.getInt32(7),
14443                         Builder.getInt32(10), Builder.getInt32(5)};
14444       return Builder.CreateCall(MCR, args);
14445     } else {
14446       // Instead of using barriers, atomic accesses on these subtargets use
14447       // libcalls.
14448       llvm_unreachable("makeDMB on a target so old that it has no barriers");
14449     }
14450   } else {
14451     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
14452     // Only a full system barrier exists in the M-class architectures.
14453     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
14454     Constant *CDomain = Builder.getInt32(Domain);
14455     return Builder.CreateCall(DMB, CDomain);
14456   }
14457 }
14458 
14459 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
14460 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
14461                                                  Instruction *Inst,
14462                                                  AtomicOrdering Ord) const {
14463   switch (Ord) {
14464   case AtomicOrdering::NotAtomic:
14465   case AtomicOrdering::Unordered:
14466     llvm_unreachable("Invalid fence: unordered/non-atomic");
14467   case AtomicOrdering::Monotonic:
14468   case AtomicOrdering::Acquire:
14469     return nullptr; // Nothing to do
14470   case AtomicOrdering::SequentiallyConsistent:
14471     if (!Inst->hasAtomicStore())
14472       return nullptr; // Nothing to do
14473     LLVM_FALLTHROUGH;
14474   case AtomicOrdering::Release:
14475   case AtomicOrdering::AcquireRelease:
14476     if (Subtarget->preferISHSTBarriers())
14477       return makeDMB(Builder, ARM_MB::ISHST);
14478     // FIXME: add a comment with a link to documentation justifying this.
14479     else
14480       return makeDMB(Builder, ARM_MB::ISH);
14481   }
14482   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
14483 }
14484 
14485 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
14486                                                   Instruction *Inst,
14487                                                   AtomicOrdering Ord) const {
14488   switch (Ord) {
14489   case AtomicOrdering::NotAtomic:
14490   case AtomicOrdering::Unordered:
14491     llvm_unreachable("Invalid fence: unordered/not-atomic");
14492   case AtomicOrdering::Monotonic:
14493   case AtomicOrdering::Release:
14494     return nullptr; // Nothing to do
14495   case AtomicOrdering::Acquire:
14496   case AtomicOrdering::AcquireRelease:
14497   case AtomicOrdering::SequentiallyConsistent:
14498     return makeDMB(Builder, ARM_MB::ISH);
14499   }
14500   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
14501 }
14502 
14503 // Loads and stores less than 64-bits are already atomic; ones above that
14504 // are doomed anyway, so defer to the default libcall and blame the OS when
14505 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
14506 // anything for those.
14507 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
14508   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
14509   return (Size == 64) && !Subtarget->isMClass();
14510 }
14511 
14512 // Loads and stores less than 64-bits are already atomic; ones above that
14513 // are doomed anyway, so defer to the default libcall and blame the OS when
14514 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
14515 // anything for those.
14516 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
14517 // guarantee, see DDI0406C ARM architecture reference manual,
14518 // sections A8.8.72-74 LDRD)
14519 TargetLowering::AtomicExpansionKind
14520 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
14521   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
14522   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
14523                                                   : AtomicExpansionKind::None;
14524 }
14525 
14526 // For the real atomic operations, we have ldrex/strex up to 32 bits,
14527 // and up to 64 bits on the non-M profiles
14528 TargetLowering::AtomicExpansionKind
14529 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
14530   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
14531   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
14532   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
14533              ? AtomicExpansionKind::LLSC
14534              : AtomicExpansionKind::None;
14535 }
14536 
14537 TargetLowering::AtomicExpansionKind
14538 ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(AtomicCmpXchgInst *AI) const {
14539   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
14540   // implement cmpxchg without spilling. If the address being exchanged is also
14541   // on the stack and close enough to the spill slot, this can lead to a
14542   // situation where the monitor always gets cleared and the atomic operation
14543   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
14544   bool HasAtomicCmpXchg =
14545       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
14546   if (getTargetMachine().getOptLevel() != 0 && HasAtomicCmpXchg)
14547     return AtomicExpansionKind::LLSC;
14548   return AtomicExpansionKind::None;
14549 }
14550 
14551 bool ARMTargetLowering::shouldInsertFencesForAtomic(
14552     const Instruction *I) const {
14553   return InsertFencesForAtomic;
14554 }
14555 
14556 // This has so far only been implemented for MachO.
14557 bool ARMTargetLowering::useLoadStackGuardNode() const {
14558   return Subtarget->isTargetMachO();
14559 }
14560 
14561 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
14562                                                   unsigned &Cost) const {
14563   // If we do not have NEON, vector types are not natively supported.
14564   if (!Subtarget->hasNEON())
14565     return false;
14566 
14567   // Floating point values and vector values map to the same register file.
14568   // Therefore, although we could do a store extract of a vector type, this is
14569   // better to leave at float as we have more freedom in the addressing mode for
14570   // those.
14571   if (VectorTy->isFPOrFPVectorTy())
14572     return false;
14573 
14574   // If the index is unknown at compile time, this is very expensive to lower
14575   // and it is not possible to combine the store with the extract.
14576   if (!isa<ConstantInt>(Idx))
14577     return false;
14578 
14579   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
14580   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
14581   // We can do a store + vector extract on any vector that fits perfectly in a D
14582   // or Q register.
14583   if (BitWidth == 64 || BitWidth == 128) {
14584     Cost = 0;
14585     return true;
14586   }
14587   return false;
14588 }
14589 
14590 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
14591   return Subtarget->hasV6T2Ops();
14592 }
14593 
14594 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
14595   return Subtarget->hasV6T2Ops();
14596 }
14597 
14598 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
14599                                          AtomicOrdering Ord) const {
14600   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14601   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
14602   bool IsAcquire = isAcquireOrStronger(Ord);
14603 
14604   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
14605   // intrinsic must return {i32, i32} and we have to recombine them into a
14606   // single i64 here.
14607   if (ValTy->getPrimitiveSizeInBits() == 64) {
14608     Intrinsic::ID Int =
14609         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
14610     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
14611 
14612     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14613     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
14614 
14615     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
14616     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
14617     if (!Subtarget->isLittle())
14618       std::swap (Lo, Hi);
14619     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
14620     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
14621     return Builder.CreateOr(
14622         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
14623   }
14624 
14625   Type *Tys[] = { Addr->getType() };
14626   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
14627   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
14628 
14629   return Builder.CreateTruncOrBitCast(
14630       Builder.CreateCall(Ldrex, Addr),
14631       cast<PointerType>(Addr->getType())->getElementType());
14632 }
14633 
14634 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
14635     IRBuilder<> &Builder) const {
14636   if (!Subtarget->hasV7Ops())
14637     return;
14638   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14639   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
14640 }
14641 
14642 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
14643                                                Value *Addr,
14644                                                AtomicOrdering Ord) const {
14645   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14646   bool IsRelease = isReleaseOrStronger(Ord);
14647 
14648   // Since the intrinsics must have legal type, the i64 intrinsics take two
14649   // parameters: "i32, i32". We must marshal Val into the appropriate form
14650   // before the call.
14651   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
14652     Intrinsic::ID Int =
14653         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
14654     Function *Strex = Intrinsic::getDeclaration(M, Int);
14655     Type *Int32Ty = Type::getInt32Ty(M->getContext());
14656 
14657     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
14658     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
14659     if (!Subtarget->isLittle())
14660       std::swap(Lo, Hi);
14661     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14662     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
14663   }
14664 
14665   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
14666   Type *Tys[] = { Addr->getType() };
14667   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
14668 
14669   return Builder.CreateCall(
14670       Strex, {Builder.CreateZExtOrBitCast(
14671                   Val, Strex->getFunctionType()->getParamType(0)),
14672               Addr});
14673 }
14674 
14675 
14676 bool ARMTargetLowering::alignLoopsWithOptSize() const {
14677   return Subtarget->isMClass();
14678 }
14679 
14680 /// A helper function for determining the number of interleaved accesses we
14681 /// will generate when lowering accesses of the given type.
14682 unsigned
14683 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
14684                                              const DataLayout &DL) const {
14685   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
14686 }
14687 
14688 bool ARMTargetLowering::isLegalInterleavedAccessType(
14689     VectorType *VecTy, const DataLayout &DL) const {
14690 
14691   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
14692   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
14693 
14694   // Ensure the vector doesn't have f16 elements. Even though we could do an
14695   // i16 vldN, we can't hold the f16 vectors and will end up converting via
14696   // f32.
14697   if (VecTy->getElementType()->isHalfTy())
14698     return false;
14699 
14700   // Ensure the number of vector elements is greater than 1.
14701   if (VecTy->getNumElements() < 2)
14702     return false;
14703 
14704   // Ensure the element type is legal.
14705   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
14706     return false;
14707 
14708   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
14709   // 128 will be split into multiple interleaved accesses.
14710   return VecSize == 64 || VecSize % 128 == 0;
14711 }
14712 
14713 /// Lower an interleaved load into a vldN intrinsic.
14714 ///
14715 /// E.g. Lower an interleaved load (Factor = 2):
14716 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
14717 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
14718 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
14719 ///
14720 ///      Into:
14721 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
14722 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
14723 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
14724 bool ARMTargetLowering::lowerInterleavedLoad(
14725     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
14726     ArrayRef<unsigned> Indices, unsigned Factor) const {
14727   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14728          "Invalid interleave factor");
14729   assert(!Shuffles.empty() && "Empty shufflevector input");
14730   assert(Shuffles.size() == Indices.size() &&
14731          "Unmatched number of shufflevectors and indices");
14732 
14733   VectorType *VecTy = Shuffles[0]->getType();
14734   Type *EltTy = VecTy->getVectorElementType();
14735 
14736   const DataLayout &DL = LI->getModule()->getDataLayout();
14737 
14738   // Skip if we do not have NEON and skip illegal vector types. We can
14739   // "legalize" wide vector types into multiple interleaved accesses as long as
14740   // the vector types are divisible by 128.
14741   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
14742     return false;
14743 
14744   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
14745 
14746   // A pointer vector can not be the return type of the ldN intrinsics. Need to
14747   // load integer vectors first and then convert to pointer vectors.
14748   if (EltTy->isPointerTy())
14749     VecTy =
14750         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
14751 
14752   IRBuilder<> Builder(LI);
14753 
14754   // The base address of the load.
14755   Value *BaseAddr = LI->getPointerOperand();
14756 
14757   if (NumLoads > 1) {
14758     // If we're going to generate more than one load, reset the sub-vector type
14759     // to something legal.
14760     VecTy = VectorType::get(VecTy->getVectorElementType(),
14761                             VecTy->getVectorNumElements() / NumLoads);
14762 
14763     // We will compute the pointer operand of each load from the original base
14764     // address using GEPs. Cast the base address to a pointer to the scalar
14765     // element type.
14766     BaseAddr = Builder.CreateBitCast(
14767         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
14768                       LI->getPointerAddressSpace()));
14769   }
14770 
14771   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
14772 
14773   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
14774   Type *Tys[] = {VecTy, Int8Ptr};
14775   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
14776                                             Intrinsic::arm_neon_vld3,
14777                                             Intrinsic::arm_neon_vld4};
14778   Function *VldnFunc =
14779       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
14780 
14781   // Holds sub-vectors extracted from the load intrinsic return values. The
14782   // sub-vectors are associated with the shufflevector instructions they will
14783   // replace.
14784   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
14785 
14786   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
14787     // If we're generating more than one load, compute the base address of
14788     // subsequent loads as an offset from the previous.
14789     if (LoadCount > 0)
14790       BaseAddr = Builder.CreateConstGEP1_32(
14791           BaseAddr, VecTy->getVectorNumElements() * Factor);
14792 
14793     SmallVector<Value *, 2> Ops;
14794     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14795     Ops.push_back(Builder.getInt32(LI->getAlignment()));
14796 
14797     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
14798 
14799     // Replace uses of each shufflevector with the corresponding vector loaded
14800     // by ldN.
14801     for (unsigned i = 0; i < Shuffles.size(); i++) {
14802       ShuffleVectorInst *SV = Shuffles[i];
14803       unsigned Index = Indices[i];
14804 
14805       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
14806 
14807       // Convert the integer vector to pointer vector if the element is pointer.
14808       if (EltTy->isPointerTy())
14809         SubVec = Builder.CreateIntToPtr(
14810             SubVec, VectorType::get(SV->getType()->getVectorElementType(),
14811                                     VecTy->getVectorNumElements()));
14812 
14813       SubVecs[SV].push_back(SubVec);
14814     }
14815   }
14816 
14817   // Replace uses of the shufflevector instructions with the sub-vectors
14818   // returned by the load intrinsic. If a shufflevector instruction is
14819   // associated with more than one sub-vector, those sub-vectors will be
14820   // concatenated into a single wide vector.
14821   for (ShuffleVectorInst *SVI : Shuffles) {
14822     auto &SubVec = SubVecs[SVI];
14823     auto *WideVec =
14824         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
14825     SVI->replaceAllUsesWith(WideVec);
14826   }
14827 
14828   return true;
14829 }
14830 
14831 /// Lower an interleaved store into a vstN intrinsic.
14832 ///
14833 /// E.g. Lower an interleaved store (Factor = 3):
14834 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
14835 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
14836 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
14837 ///
14838 ///      Into:
14839 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
14840 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
14841 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
14842 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14843 ///
14844 /// Note that the new shufflevectors will be removed and we'll only generate one
14845 /// vst3 instruction in CodeGen.
14846 ///
14847 /// Example for a more general valid mask (Factor 3). Lower:
14848 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
14849 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
14850 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
14851 ///
14852 ///      Into:
14853 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
14854 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
14855 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
14856 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14857 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
14858                                               ShuffleVectorInst *SVI,
14859                                               unsigned Factor) const {
14860   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14861          "Invalid interleave factor");
14862 
14863   VectorType *VecTy = SVI->getType();
14864   assert(VecTy->getVectorNumElements() % Factor == 0 &&
14865          "Invalid interleaved store");
14866 
14867   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
14868   Type *EltTy = VecTy->getVectorElementType();
14869   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
14870 
14871   const DataLayout &DL = SI->getModule()->getDataLayout();
14872 
14873   // Skip if we do not have NEON and skip illegal vector types. We can
14874   // "legalize" wide vector types into multiple interleaved accesses as long as
14875   // the vector types are divisible by 128.
14876   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
14877     return false;
14878 
14879   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
14880 
14881   Value *Op0 = SVI->getOperand(0);
14882   Value *Op1 = SVI->getOperand(1);
14883   IRBuilder<> Builder(SI);
14884 
14885   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
14886   // vectors to integer vectors.
14887   if (EltTy->isPointerTy()) {
14888     Type *IntTy = DL.getIntPtrType(EltTy);
14889 
14890     // Convert to the corresponding integer vector.
14891     Type *IntVecTy =
14892         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
14893     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
14894     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
14895 
14896     SubVecTy = VectorType::get(IntTy, LaneLen);
14897   }
14898 
14899   // The base address of the store.
14900   Value *BaseAddr = SI->getPointerOperand();
14901 
14902   if (NumStores > 1) {
14903     // If we're going to generate more than one store, reset the lane length
14904     // and sub-vector type to something legal.
14905     LaneLen /= NumStores;
14906     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
14907 
14908     // We will compute the pointer operand of each store from the original base
14909     // address using GEPs. Cast the base address to a pointer to the scalar
14910     // element type.
14911     BaseAddr = Builder.CreateBitCast(
14912         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
14913                       SI->getPointerAddressSpace()));
14914   }
14915 
14916   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
14917 
14918   auto Mask = SVI->getShuffleMask();
14919 
14920   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
14921   Type *Tys[] = {Int8Ptr, SubVecTy};
14922   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
14923                                              Intrinsic::arm_neon_vst3,
14924                                              Intrinsic::arm_neon_vst4};
14925 
14926   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
14927     // If we generating more than one store, we compute the base address of
14928     // subsequent stores as an offset from the previous.
14929     if (StoreCount > 0)
14930       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
14931 
14932     SmallVector<Value *, 6> Ops;
14933     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14934 
14935     Function *VstNFunc =
14936         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
14937 
14938     // Split the shufflevector operands into sub vectors for the new vstN call.
14939     for (unsigned i = 0; i < Factor; i++) {
14940       unsigned IdxI = StoreCount * LaneLen * Factor + i;
14941       if (Mask[IdxI] >= 0) {
14942         Ops.push_back(Builder.CreateShuffleVector(
14943             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
14944       } else {
14945         unsigned StartMask = 0;
14946         for (unsigned j = 1; j < LaneLen; j++) {
14947           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
14948           if (Mask[IdxJ * Factor + IdxI] >= 0) {
14949             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
14950             break;
14951           }
14952         }
14953         // Note: If all elements in a chunk are undefs, StartMask=0!
14954         // Note: Filling undef gaps with random elements is ok, since
14955         // those elements were being written anyway (with undefs).
14956         // In the case of all undefs we're defaulting to using elems from 0
14957         // Note: StartMask cannot be negative, it's checked in
14958         // isReInterleaveMask
14959         Ops.push_back(Builder.CreateShuffleVector(
14960             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
14961       }
14962     }
14963 
14964     Ops.push_back(Builder.getInt32(SI->getAlignment()));
14965     Builder.CreateCall(VstNFunc, Ops);
14966   }
14967   return true;
14968 }
14969 
14970 enum HABaseType {
14971   HA_UNKNOWN = 0,
14972   HA_FLOAT,
14973   HA_DOUBLE,
14974   HA_VECT64,
14975   HA_VECT128
14976 };
14977 
14978 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
14979                                    uint64_t &Members) {
14980   if (auto *ST = dyn_cast<StructType>(Ty)) {
14981     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
14982       uint64_t SubMembers = 0;
14983       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
14984         return false;
14985       Members += SubMembers;
14986     }
14987   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
14988     uint64_t SubMembers = 0;
14989     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
14990       return false;
14991     Members += SubMembers * AT->getNumElements();
14992   } else if (Ty->isFloatTy()) {
14993     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
14994       return false;
14995     Members = 1;
14996     Base = HA_FLOAT;
14997   } else if (Ty->isDoubleTy()) {
14998     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
14999       return false;
15000     Members = 1;
15001     Base = HA_DOUBLE;
15002   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
15003     Members = 1;
15004     switch (Base) {
15005     case HA_FLOAT:
15006     case HA_DOUBLE:
15007       return false;
15008     case HA_VECT64:
15009       return VT->getBitWidth() == 64;
15010     case HA_VECT128:
15011       return VT->getBitWidth() == 128;
15012     case HA_UNKNOWN:
15013       switch (VT->getBitWidth()) {
15014       case 64:
15015         Base = HA_VECT64;
15016         return true;
15017       case 128:
15018         Base = HA_VECT128;
15019         return true;
15020       default:
15021         return false;
15022       }
15023     }
15024   }
15025 
15026   return (Members > 0 && Members <= 4);
15027 }
15028 
15029 /// Return the correct alignment for the current calling convention.
15030 unsigned
15031 ARMTargetLowering::getABIAlignmentForCallingConv(Type *ArgTy,
15032                                                  DataLayout DL) const {
15033   if (!ArgTy->isVectorTy())
15034     return DL.getABITypeAlignment(ArgTy);
15035 
15036   // Avoid over-aligning vector parameters. It would require realigning the
15037   // stack and waste space for no real benefit.
15038   return std::min(DL.getABITypeAlignment(ArgTy), DL.getStackAlignment());
15039 }
15040 
15041 /// Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
15042 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
15043 /// passing according to AAPCS rules.
15044 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
15045     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
15046   if (getEffectiveCallingConv(CallConv, isVarArg) !=
15047       CallingConv::ARM_AAPCS_VFP)
15048     return false;
15049 
15050   HABaseType Base = HA_UNKNOWN;
15051   uint64_t Members = 0;
15052   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
15053   LLVM_DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
15054 
15055   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
15056   return IsHA || IsIntArray;
15057 }
15058 
15059 unsigned ARMTargetLowering::getExceptionPointerRegister(
15060     const Constant *PersonalityFn) const {
15061   // Platforms which do not use SjLj EH may return values in these registers
15062   // via the personality function.
15063   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
15064 }
15065 
15066 unsigned ARMTargetLowering::getExceptionSelectorRegister(
15067     const Constant *PersonalityFn) const {
15068   // Platforms which do not use SjLj EH may return values in these registers
15069   // via the personality function.
15070   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
15071 }
15072 
15073 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
15074   // Update IsSplitCSR in ARMFunctionInfo.
15075   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
15076   AFI->setIsSplitCSR(true);
15077 }
15078 
15079 void ARMTargetLowering::insertCopiesSplitCSR(
15080     MachineBasicBlock *Entry,
15081     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
15082   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
15083   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
15084   if (!IStart)
15085     return;
15086 
15087   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
15088   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
15089   MachineBasicBlock::iterator MBBI = Entry->begin();
15090   for (const MCPhysReg *I = IStart; *I; ++I) {
15091     const TargetRegisterClass *RC = nullptr;
15092     if (ARM::GPRRegClass.contains(*I))
15093       RC = &ARM::GPRRegClass;
15094     else if (ARM::DPRRegClass.contains(*I))
15095       RC = &ARM::DPRRegClass;
15096     else
15097       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
15098 
15099     unsigned NewVR = MRI->createVirtualRegister(RC);
15100     // Create copy from CSR to a virtual register.
15101     // FIXME: this currently does not emit CFI pseudo-instructions, it works
15102     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
15103     // nounwind. If we want to generalize this later, we may need to emit
15104     // CFI pseudo-instructions.
15105     assert(Entry->getParent()->getFunction().hasFnAttribute(
15106                Attribute::NoUnwind) &&
15107            "Function should be nounwind in insertCopiesSplitCSR!");
15108     Entry->addLiveIn(*I);
15109     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
15110         .addReg(*I);
15111 
15112     // Insert the copy-back instructions right before the terminator.
15113     for (auto *Exit : Exits)
15114       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
15115               TII->get(TargetOpcode::COPY), *I)
15116           .addReg(NewVR);
15117   }
15118 }
15119 
15120 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
15121   MF.getFrameInfo().computeMaxCallFrameSize(MF);
15122   TargetLoweringBase::finalizeLowering(MF);
15123 }
15124