1 //===- ARMISelLowering.cpp - ARM DAG Lowering Implementation --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that ARM uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ARMISelLowering.h"
16 #include "ARMBaseInstrInfo.h"
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMMachineFunctionInfo.h"
21 #include "ARMPerfectShuffle.h"
22 #include "ARMRegisterInfo.h"
23 #include "ARMSelectionDAGInfo.h"
24 #include "ARMSubtarget.h"
25 #include "MCTargetDesc/ARMAddressingModes.h"
26 #include "MCTargetDesc/ARMBaseInfo.h"
27 #include "Utils/ARMBaseInfo.h"
28 #include "llvm/ADT/APFloat.h"
29 #include "llvm/ADT/APInt.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/BitVector.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/StringRef.h"
39 #include "llvm/ADT/StringSwitch.h"
40 #include "llvm/ADT/Triple.h"
41 #include "llvm/ADT/Twine.h"
42 #include "llvm/Analysis/VectorUtils.h"
43 #include "llvm/CodeGen/CallingConvLower.h"
44 #include "llvm/CodeGen/ISDOpcodes.h"
45 #include "llvm/CodeGen/IntrinsicLowering.h"
46 #include "llvm/CodeGen/MachineBasicBlock.h"
47 #include "llvm/CodeGen/MachineConstantPool.h"
48 #include "llvm/CodeGen/MachineFrameInfo.h"
49 #include "llvm/CodeGen/MachineFunction.h"
50 #include "llvm/CodeGen/MachineInstr.h"
51 #include "llvm/CodeGen/MachineInstrBuilder.h"
52 #include "llvm/CodeGen/MachineJumpTableInfo.h"
53 #include "llvm/CodeGen/MachineMemOperand.h"
54 #include "llvm/CodeGen/MachineOperand.h"
55 #include "llvm/CodeGen/MachineRegisterInfo.h"
56 #include "llvm/CodeGen/MachineValueType.h"
57 #include "llvm/CodeGen/RuntimeLibcalls.h"
58 #include "llvm/CodeGen/SelectionDAG.h"
59 #include "llvm/CodeGen/SelectionDAGNodes.h"
60 #include "llvm/CodeGen/TargetInstrInfo.h"
61 #include "llvm/CodeGen/TargetLowering.h"
62 #include "llvm/CodeGen/TargetOpcodes.h"
63 #include "llvm/CodeGen/TargetRegisterInfo.h"
64 #include "llvm/CodeGen/TargetSubtargetInfo.h"
65 #include "llvm/CodeGen/ValueTypes.h"
66 #include "llvm/IR/Attributes.h"
67 #include "llvm/IR/CallingConv.h"
68 #include "llvm/IR/Constant.h"
69 #include "llvm/IR/Constants.h"
70 #include "llvm/IR/DataLayout.h"
71 #include "llvm/IR/DebugLoc.h"
72 #include "llvm/IR/DerivedTypes.h"
73 #include "llvm/IR/Function.h"
74 #include "llvm/IR/GlobalAlias.h"
75 #include "llvm/IR/GlobalValue.h"
76 #include "llvm/IR/GlobalVariable.h"
77 #include "llvm/IR/IRBuilder.h"
78 #include "llvm/IR/InlineAsm.h"
79 #include "llvm/IR/Instruction.h"
80 #include "llvm/IR/Instructions.h"
81 #include "llvm/IR/IntrinsicInst.h"
82 #include "llvm/IR/Intrinsics.h"
83 #include "llvm/IR/Module.h"
84 #include "llvm/IR/Type.h"
85 #include "llvm/IR/User.h"
86 #include "llvm/IR/Value.h"
87 #include "llvm/MC/MCInstrDesc.h"
88 #include "llvm/MC/MCInstrItineraries.h"
89 #include "llvm/MC/MCRegisterInfo.h"
90 #include "llvm/MC/MCSchedule.h"
91 #include "llvm/Support/AtomicOrdering.h"
92 #include "llvm/Support/BranchProbability.h"
93 #include "llvm/Support/Casting.h"
94 #include "llvm/Support/CodeGen.h"
95 #include "llvm/Support/CommandLine.h"
96 #include "llvm/Support/Compiler.h"
97 #include "llvm/Support/Debug.h"
98 #include "llvm/Support/ErrorHandling.h"
99 #include "llvm/Support/KnownBits.h"
100 #include "llvm/Support/MathExtras.h"
101 #include "llvm/Support/raw_ostream.h"
102 #include "llvm/Target/TargetMachine.h"
103 #include "llvm/Target/TargetOptions.h"
104 #include <algorithm>
105 #include <cassert>
106 #include <cstdint>
107 #include <cstdlib>
108 #include <iterator>
109 #include <limits>
110 #include <string>
111 #include <tuple>
112 #include <utility>
113 #include <vector>
114 
115 using namespace llvm;
116 
117 #define DEBUG_TYPE "arm-isel"
118 
119 STATISTIC(NumTailCalls, "Number of tail calls");
120 STATISTIC(NumMovwMovt, "Number of GAs materialized with movw + movt");
121 STATISTIC(NumLoopByVals, "Number of loops generated for byval arguments");
122 STATISTIC(NumConstpoolPromoted,
123   "Number of constants with their storage promoted into constant pools");
124 
125 static cl::opt<bool>
126 ARMInterworking("arm-interworking", cl::Hidden,
127   cl::desc("Enable / disable ARM interworking (for debugging only)"),
128   cl::init(true));
129 
130 static cl::opt<bool> EnableConstpoolPromotion(
131     "arm-promote-constant", cl::Hidden,
132     cl::desc("Enable / disable promotion of unnamed_addr constants into "
133              "constant pools"),
134     cl::init(false)); // FIXME: set to true by default once PR32780 is fixed
135 static cl::opt<unsigned> ConstpoolPromotionMaxSize(
136     "arm-promote-constant-max-size", cl::Hidden,
137     cl::desc("Maximum size of constant to promote into a constant pool"),
138     cl::init(64));
139 static cl::opt<unsigned> ConstpoolPromotionMaxTotal(
140     "arm-promote-constant-max-total", cl::Hidden,
141     cl::desc("Maximum size of ALL constants to promote into a constant pool"),
142     cl::init(128));
143 
144 // The APCS parameter registers.
145 static const MCPhysReg GPRArgRegs[] = {
146   ARM::R0, ARM::R1, ARM::R2, ARM::R3
147 };
148 
149 void ARMTargetLowering::addTypeForNEON(MVT VT, MVT PromotedLdStVT,
150                                        MVT PromotedBitwiseVT) {
151   if (VT != PromotedLdStVT) {
152     setOperationAction(ISD::LOAD, VT, Promote);
153     AddPromotedToType (ISD::LOAD, VT, PromotedLdStVT);
154 
155     setOperationAction(ISD::STORE, VT, Promote);
156     AddPromotedToType (ISD::STORE, VT, PromotedLdStVT);
157   }
158 
159   MVT ElemTy = VT.getVectorElementType();
160   if (ElemTy != MVT::f64)
161     setOperationAction(ISD::SETCC, VT, Custom);
162   setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
163   setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
164   if (ElemTy == MVT::i32) {
165     setOperationAction(ISD::SINT_TO_FP, VT, Custom);
166     setOperationAction(ISD::UINT_TO_FP, VT, Custom);
167     setOperationAction(ISD::FP_TO_SINT, VT, Custom);
168     setOperationAction(ISD::FP_TO_UINT, VT, Custom);
169   } else {
170     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
171     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
172     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
173     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
174   }
175   setOperationAction(ISD::BUILD_VECTOR,      VT, Custom);
176   setOperationAction(ISD::VECTOR_SHUFFLE,    VT, Custom);
177   setOperationAction(ISD::CONCAT_VECTORS,    VT, Legal);
178   setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
179   setOperationAction(ISD::SELECT,            VT, Expand);
180   setOperationAction(ISD::SELECT_CC,         VT, Expand);
181   setOperationAction(ISD::VSELECT,           VT, Expand);
182   setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
183   if (VT.isInteger()) {
184     setOperationAction(ISD::SHL, VT, Custom);
185     setOperationAction(ISD::SRA, VT, Custom);
186     setOperationAction(ISD::SRL, VT, Custom);
187   }
188 
189   // Promote all bit-wise operations.
190   if (VT.isInteger() && VT != PromotedBitwiseVT) {
191     setOperationAction(ISD::AND, VT, Promote);
192     AddPromotedToType (ISD::AND, VT, PromotedBitwiseVT);
193     setOperationAction(ISD::OR,  VT, Promote);
194     AddPromotedToType (ISD::OR,  VT, PromotedBitwiseVT);
195     setOperationAction(ISD::XOR, VT, Promote);
196     AddPromotedToType (ISD::XOR, VT, PromotedBitwiseVT);
197   }
198 
199   // Neon does not support vector divide/remainder operations.
200   setOperationAction(ISD::SDIV, VT, Expand);
201   setOperationAction(ISD::UDIV, VT, Expand);
202   setOperationAction(ISD::FDIV, VT, Expand);
203   setOperationAction(ISD::SREM, VT, Expand);
204   setOperationAction(ISD::UREM, VT, Expand);
205   setOperationAction(ISD::FREM, VT, Expand);
206 
207   if (!VT.isFloatingPoint() &&
208       VT != MVT::v2i64 && VT != MVT::v1i64)
209     for (auto Opcode : {ISD::ABS, ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
210       setOperationAction(Opcode, VT, Legal);
211 }
212 
213 void ARMTargetLowering::addDRTypeForNEON(MVT VT) {
214   addRegisterClass(VT, &ARM::DPRRegClass);
215   addTypeForNEON(VT, MVT::f64, MVT::v2i32);
216 }
217 
218 void ARMTargetLowering::addQRTypeForNEON(MVT VT) {
219   addRegisterClass(VT, &ARM::DPairRegClass);
220   addTypeForNEON(VT, MVT::v2f64, MVT::v4i32);
221 }
222 
223 ARMTargetLowering::ARMTargetLowering(const TargetMachine &TM,
224                                      const ARMSubtarget &STI)
225     : TargetLowering(TM), Subtarget(&STI) {
226   RegInfo = Subtarget->getRegisterInfo();
227   Itins = Subtarget->getInstrItineraryData();
228 
229   setBooleanContents(ZeroOrOneBooleanContent);
230   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
231 
232   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetIOS() &&
233       !Subtarget->isTargetWatchOS()) {
234     bool IsHFTarget = TM.Options.FloatABIType == FloatABI::Hard;
235     for (int LCID = 0; LCID < RTLIB::UNKNOWN_LIBCALL; ++LCID)
236       setLibcallCallingConv(static_cast<RTLIB::Libcall>(LCID),
237                             IsHFTarget ? CallingConv::ARM_AAPCS_VFP
238                                        : CallingConv::ARM_AAPCS);
239   }
240 
241   if (Subtarget->isTargetMachO()) {
242     // Uses VFP for Thumb libfuncs if available.
243     if (Subtarget->isThumb() && Subtarget->hasVFP2() &&
244         Subtarget->hasARMOps() && !Subtarget->useSoftFloat()) {
245       static const struct {
246         const RTLIB::Libcall Op;
247         const char * const Name;
248         const ISD::CondCode Cond;
249       } LibraryCalls[] = {
250         // Single-precision floating-point arithmetic.
251         { RTLIB::ADD_F32, "__addsf3vfp", ISD::SETCC_INVALID },
252         { RTLIB::SUB_F32, "__subsf3vfp", ISD::SETCC_INVALID },
253         { RTLIB::MUL_F32, "__mulsf3vfp", ISD::SETCC_INVALID },
254         { RTLIB::DIV_F32, "__divsf3vfp", ISD::SETCC_INVALID },
255 
256         // Double-precision floating-point arithmetic.
257         { RTLIB::ADD_F64, "__adddf3vfp", ISD::SETCC_INVALID },
258         { RTLIB::SUB_F64, "__subdf3vfp", ISD::SETCC_INVALID },
259         { RTLIB::MUL_F64, "__muldf3vfp", ISD::SETCC_INVALID },
260         { RTLIB::DIV_F64, "__divdf3vfp", ISD::SETCC_INVALID },
261 
262         // Single-precision comparisons.
263         { RTLIB::OEQ_F32, "__eqsf2vfp",    ISD::SETNE },
264         { RTLIB::UNE_F32, "__nesf2vfp",    ISD::SETNE },
265         { RTLIB::OLT_F32, "__ltsf2vfp",    ISD::SETNE },
266         { RTLIB::OLE_F32, "__lesf2vfp",    ISD::SETNE },
267         { RTLIB::OGE_F32, "__gesf2vfp",    ISD::SETNE },
268         { RTLIB::OGT_F32, "__gtsf2vfp",    ISD::SETNE },
269         { RTLIB::UO_F32,  "__unordsf2vfp", ISD::SETNE },
270         { RTLIB::O_F32,   "__unordsf2vfp", ISD::SETEQ },
271 
272         // Double-precision comparisons.
273         { RTLIB::OEQ_F64, "__eqdf2vfp",    ISD::SETNE },
274         { RTLIB::UNE_F64, "__nedf2vfp",    ISD::SETNE },
275         { RTLIB::OLT_F64, "__ltdf2vfp",    ISD::SETNE },
276         { RTLIB::OLE_F64, "__ledf2vfp",    ISD::SETNE },
277         { RTLIB::OGE_F64, "__gedf2vfp",    ISD::SETNE },
278         { RTLIB::OGT_F64, "__gtdf2vfp",    ISD::SETNE },
279         { RTLIB::UO_F64,  "__unorddf2vfp", ISD::SETNE },
280         { RTLIB::O_F64,   "__unorddf2vfp", ISD::SETEQ },
281 
282         // Floating-point to integer conversions.
283         // i64 conversions are done via library routines even when generating VFP
284         // instructions, so use the same ones.
285         { RTLIB::FPTOSINT_F64_I32, "__fixdfsivfp",    ISD::SETCC_INVALID },
286         { RTLIB::FPTOUINT_F64_I32, "__fixunsdfsivfp", ISD::SETCC_INVALID },
287         { RTLIB::FPTOSINT_F32_I32, "__fixsfsivfp",    ISD::SETCC_INVALID },
288         { RTLIB::FPTOUINT_F32_I32, "__fixunssfsivfp", ISD::SETCC_INVALID },
289 
290         // Conversions between floating types.
291         { RTLIB::FPROUND_F64_F32, "__truncdfsf2vfp",  ISD::SETCC_INVALID },
292         { RTLIB::FPEXT_F32_F64,   "__extendsfdf2vfp", ISD::SETCC_INVALID },
293 
294         // Integer to floating-point conversions.
295         // i64 conversions are done via library routines even when generating VFP
296         // instructions, so use the same ones.
297         // FIXME: There appears to be some naming inconsistency in ARM libgcc:
298         // e.g., __floatunsidf vs. __floatunssidfvfp.
299         { RTLIB::SINTTOFP_I32_F64, "__floatsidfvfp",    ISD::SETCC_INVALID },
300         { RTLIB::UINTTOFP_I32_F64, "__floatunssidfvfp", ISD::SETCC_INVALID },
301         { RTLIB::SINTTOFP_I32_F32, "__floatsisfvfp",    ISD::SETCC_INVALID },
302         { RTLIB::UINTTOFP_I32_F32, "__floatunssisfvfp", ISD::SETCC_INVALID },
303       };
304 
305       for (const auto &LC : LibraryCalls) {
306         setLibcallName(LC.Op, LC.Name);
307         if (LC.Cond != ISD::SETCC_INVALID)
308           setCmpLibcallCC(LC.Op, LC.Cond);
309       }
310     }
311 
312     // Set the correct calling convention for ARMv7k WatchOS. It's just
313     // AAPCS_VFP for functions as simple as libcalls.
314     if (Subtarget->isTargetWatchABI()) {
315       for (int i = 0; i < RTLIB::UNKNOWN_LIBCALL; ++i)
316         setLibcallCallingConv((RTLIB::Libcall)i, CallingConv::ARM_AAPCS_VFP);
317     }
318   }
319 
320   // These libcalls are not available in 32-bit.
321   setLibcallName(RTLIB::SHL_I128, nullptr);
322   setLibcallName(RTLIB::SRL_I128, nullptr);
323   setLibcallName(RTLIB::SRA_I128, nullptr);
324 
325   // RTLIB
326   if (Subtarget->isAAPCS_ABI() &&
327       (Subtarget->isTargetAEABI() || Subtarget->isTargetGNUAEABI() ||
328        Subtarget->isTargetMuslAEABI() || Subtarget->isTargetAndroid())) {
329     static const struct {
330       const RTLIB::Libcall Op;
331       const char * const Name;
332       const CallingConv::ID CC;
333       const ISD::CondCode Cond;
334     } LibraryCalls[] = {
335       // Double-precision floating-point arithmetic helper functions
336       // RTABI chapter 4.1.2, Table 2
337       { RTLIB::ADD_F64, "__aeabi_dadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
338       { RTLIB::DIV_F64, "__aeabi_ddiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
339       { RTLIB::MUL_F64, "__aeabi_dmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
340       { RTLIB::SUB_F64, "__aeabi_dsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
341 
342       // Double-precision floating-point comparison helper functions
343       // RTABI chapter 4.1.2, Table 3
344       { RTLIB::OEQ_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
345       { RTLIB::UNE_F64, "__aeabi_dcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
346       { RTLIB::OLT_F64, "__aeabi_dcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
347       { RTLIB::OLE_F64, "__aeabi_dcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
348       { RTLIB::OGE_F64, "__aeabi_dcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
349       { RTLIB::OGT_F64, "__aeabi_dcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
350       { RTLIB::UO_F64,  "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
351       { RTLIB::O_F64,   "__aeabi_dcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
352 
353       // Single-precision floating-point arithmetic helper functions
354       // RTABI chapter 4.1.2, Table 4
355       { RTLIB::ADD_F32, "__aeabi_fadd", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
356       { RTLIB::DIV_F32, "__aeabi_fdiv", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
357       { RTLIB::MUL_F32, "__aeabi_fmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
358       { RTLIB::SUB_F32, "__aeabi_fsub", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
359 
360       // Single-precision floating-point comparison helper functions
361       // RTABI chapter 4.1.2, Table 5
362       { RTLIB::OEQ_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETNE },
363       { RTLIB::UNE_F32, "__aeabi_fcmpeq", CallingConv::ARM_AAPCS, ISD::SETEQ },
364       { RTLIB::OLT_F32, "__aeabi_fcmplt", CallingConv::ARM_AAPCS, ISD::SETNE },
365       { RTLIB::OLE_F32, "__aeabi_fcmple", CallingConv::ARM_AAPCS, ISD::SETNE },
366       { RTLIB::OGE_F32, "__aeabi_fcmpge", CallingConv::ARM_AAPCS, ISD::SETNE },
367       { RTLIB::OGT_F32, "__aeabi_fcmpgt", CallingConv::ARM_AAPCS, ISD::SETNE },
368       { RTLIB::UO_F32,  "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETNE },
369       { RTLIB::O_F32,   "__aeabi_fcmpun", CallingConv::ARM_AAPCS, ISD::SETEQ },
370 
371       // Floating-point to integer conversions.
372       // RTABI chapter 4.1.2, Table 6
373       { RTLIB::FPTOSINT_F64_I32, "__aeabi_d2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
374       { RTLIB::FPTOUINT_F64_I32, "__aeabi_d2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
375       { RTLIB::FPTOSINT_F64_I64, "__aeabi_d2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
376       { RTLIB::FPTOUINT_F64_I64, "__aeabi_d2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
377       { RTLIB::FPTOSINT_F32_I32, "__aeabi_f2iz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
378       { RTLIB::FPTOUINT_F32_I32, "__aeabi_f2uiz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
379       { RTLIB::FPTOSINT_F32_I64, "__aeabi_f2lz",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
380       { RTLIB::FPTOUINT_F32_I64, "__aeabi_f2ulz", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
381 
382       // Conversions between floating types.
383       // RTABI chapter 4.1.2, Table 7
384       { RTLIB::FPROUND_F64_F32, "__aeabi_d2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
385       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
386       { RTLIB::FPEXT_F32_F64,   "__aeabi_f2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
387 
388       // Integer to floating-point conversions.
389       // RTABI chapter 4.1.2, Table 8
390       { RTLIB::SINTTOFP_I32_F64, "__aeabi_i2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
391       { RTLIB::UINTTOFP_I32_F64, "__aeabi_ui2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
392       { RTLIB::SINTTOFP_I64_F64, "__aeabi_l2d",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
393       { RTLIB::UINTTOFP_I64_F64, "__aeabi_ul2d", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
394       { RTLIB::SINTTOFP_I32_F32, "__aeabi_i2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
395       { RTLIB::UINTTOFP_I32_F32, "__aeabi_ui2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
396       { RTLIB::SINTTOFP_I64_F32, "__aeabi_l2f",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
397       { RTLIB::UINTTOFP_I64_F32, "__aeabi_ul2f", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
398 
399       // Long long helper functions
400       // RTABI chapter 4.2, Table 9
401       { RTLIB::MUL_I64, "__aeabi_lmul", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
402       { RTLIB::SHL_I64, "__aeabi_llsl", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
403       { RTLIB::SRL_I64, "__aeabi_llsr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
404       { RTLIB::SRA_I64, "__aeabi_lasr", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
405 
406       // Integer division functions
407       // RTABI chapter 4.3.1
408       { RTLIB::SDIV_I8,  "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
409       { RTLIB::SDIV_I16, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
410       { RTLIB::SDIV_I32, "__aeabi_idiv",     CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
411       { RTLIB::SDIV_I64, "__aeabi_ldivmod",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
412       { RTLIB::UDIV_I8,  "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
413       { RTLIB::UDIV_I16, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
414       { RTLIB::UDIV_I32, "__aeabi_uidiv",    CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
415       { RTLIB::UDIV_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
416     };
417 
418     for (const auto &LC : LibraryCalls) {
419       setLibcallName(LC.Op, LC.Name);
420       setLibcallCallingConv(LC.Op, LC.CC);
421       if (LC.Cond != ISD::SETCC_INVALID)
422         setCmpLibcallCC(LC.Op, LC.Cond);
423     }
424 
425     // EABI dependent RTLIB
426     if (TM.Options.EABIVersion == EABI::EABI4 ||
427         TM.Options.EABIVersion == EABI::EABI5) {
428       static const struct {
429         const RTLIB::Libcall Op;
430         const char *const Name;
431         const CallingConv::ID CC;
432         const ISD::CondCode Cond;
433       } MemOpsLibraryCalls[] = {
434         // Memory operations
435         // RTABI chapter 4.3.4
436         { RTLIB::MEMCPY,  "__aeabi_memcpy",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
437         { RTLIB::MEMMOVE, "__aeabi_memmove", CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
438         { RTLIB::MEMSET,  "__aeabi_memset",  CallingConv::ARM_AAPCS, ISD::SETCC_INVALID },
439       };
440 
441       for (const auto &LC : MemOpsLibraryCalls) {
442         setLibcallName(LC.Op, LC.Name);
443         setLibcallCallingConv(LC.Op, LC.CC);
444         if (LC.Cond != ISD::SETCC_INVALID)
445           setCmpLibcallCC(LC.Op, LC.Cond);
446       }
447     }
448   }
449 
450   if (Subtarget->isTargetWindows()) {
451     static const struct {
452       const RTLIB::Libcall Op;
453       const char * const Name;
454       const CallingConv::ID CC;
455     } LibraryCalls[] = {
456       { RTLIB::FPTOSINT_F32_I64, "__stoi64", CallingConv::ARM_AAPCS_VFP },
457       { RTLIB::FPTOSINT_F64_I64, "__dtoi64", CallingConv::ARM_AAPCS_VFP },
458       { RTLIB::FPTOUINT_F32_I64, "__stou64", CallingConv::ARM_AAPCS_VFP },
459       { RTLIB::FPTOUINT_F64_I64, "__dtou64", CallingConv::ARM_AAPCS_VFP },
460       { RTLIB::SINTTOFP_I64_F32, "__i64tos", CallingConv::ARM_AAPCS_VFP },
461       { RTLIB::SINTTOFP_I64_F64, "__i64tod", CallingConv::ARM_AAPCS_VFP },
462       { RTLIB::UINTTOFP_I64_F32, "__u64tos", CallingConv::ARM_AAPCS_VFP },
463       { RTLIB::UINTTOFP_I64_F64, "__u64tod", CallingConv::ARM_AAPCS_VFP },
464     };
465 
466     for (const auto &LC : LibraryCalls) {
467       setLibcallName(LC.Op, LC.Name);
468       setLibcallCallingConv(LC.Op, LC.CC);
469     }
470   }
471 
472   // Use divmod compiler-rt calls for iOS 5.0 and later.
473   if (Subtarget->isTargetMachO() &&
474       !(Subtarget->isTargetIOS() &&
475         Subtarget->getTargetTriple().isOSVersionLT(5, 0))) {
476     setLibcallName(RTLIB::SDIVREM_I32, "__divmodsi4");
477     setLibcallName(RTLIB::UDIVREM_I32, "__udivmodsi4");
478   }
479 
480   // The half <-> float conversion functions are always soft-float on
481   // non-watchos platforms, but are needed for some targets which use a
482   // hard-float calling convention by default.
483   if (!Subtarget->isTargetWatchABI()) {
484     if (Subtarget->isAAPCS_ABI()) {
485       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_AAPCS);
486       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_AAPCS);
487       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_AAPCS);
488     } else {
489       setLibcallCallingConv(RTLIB::FPROUND_F32_F16, CallingConv::ARM_APCS);
490       setLibcallCallingConv(RTLIB::FPROUND_F64_F16, CallingConv::ARM_APCS);
491       setLibcallCallingConv(RTLIB::FPEXT_F16_F32, CallingConv::ARM_APCS);
492     }
493   }
494 
495   // In EABI, these functions have an __aeabi_ prefix, but in GNUEABI they have
496   // a __gnu_ prefix (which is the default).
497   if (Subtarget->isTargetAEABI()) {
498     static const struct {
499       const RTLIB::Libcall Op;
500       const char * const Name;
501       const CallingConv::ID CC;
502     } LibraryCalls[] = {
503       { RTLIB::FPROUND_F32_F16, "__aeabi_f2h", CallingConv::ARM_AAPCS },
504       { RTLIB::FPROUND_F64_F16, "__aeabi_d2h", CallingConv::ARM_AAPCS },
505       { RTLIB::FPEXT_F16_F32, "__aeabi_h2f", CallingConv::ARM_AAPCS },
506     };
507 
508     for (const auto &LC : LibraryCalls) {
509       setLibcallName(LC.Op, LC.Name);
510       setLibcallCallingConv(LC.Op, LC.CC);
511     }
512   }
513 
514   if (Subtarget->isThumb1Only())
515     addRegisterClass(MVT::i32, &ARM::tGPRRegClass);
516   else
517     addRegisterClass(MVT::i32, &ARM::GPRRegClass);
518 
519   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
520       !Subtarget->isThumb1Only()) {
521     addRegisterClass(MVT::f32, &ARM::SPRRegClass);
522     addRegisterClass(MVT::f64, &ARM::DPRRegClass);
523   }
524 
525   if (Subtarget->hasFullFP16()) {
526     addRegisterClass(MVT::f16, &ARM::HPRRegClass);
527     setOperationAction(ISD::BITCAST, MVT::i16, Custom);
528     setOperationAction(ISD::BITCAST, MVT::i32, Custom);
529     setOperationAction(ISD::BITCAST, MVT::f16, Custom);
530   }
531 
532   for (MVT VT : MVT::vector_valuetypes()) {
533     for (MVT InnerVT : MVT::vector_valuetypes()) {
534       setTruncStoreAction(VT, InnerVT, Expand);
535       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
536       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
537       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
538     }
539 
540     setOperationAction(ISD::MULHS, VT, Expand);
541     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
542     setOperationAction(ISD::MULHU, VT, Expand);
543     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
544 
545     setOperationAction(ISD::BSWAP, VT, Expand);
546   }
547 
548   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
549   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
550 
551   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
552   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
553 
554   if (Subtarget->hasNEON()) {
555     addDRTypeForNEON(MVT::v2f32);
556     addDRTypeForNEON(MVT::v8i8);
557     addDRTypeForNEON(MVT::v4i16);
558     addDRTypeForNEON(MVT::v2i32);
559     addDRTypeForNEON(MVT::v1i64);
560 
561     addQRTypeForNEON(MVT::v4f32);
562     addQRTypeForNEON(MVT::v2f64);
563     addQRTypeForNEON(MVT::v16i8);
564     addQRTypeForNEON(MVT::v8i16);
565     addQRTypeForNEON(MVT::v4i32);
566     addQRTypeForNEON(MVT::v2i64);
567 
568     if (Subtarget->hasFullFP16()) {
569       addQRTypeForNEON(MVT::v8f16);
570       addDRTypeForNEON(MVT::v4f16);
571     }
572 
573     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
574     // neither Neon nor VFP support any arithmetic operations on it.
575     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
576     // supported for v4f32.
577     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
578     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
579     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
580     // FIXME: Code duplication: FDIV and FREM are expanded always, see
581     // ARMTargetLowering::addTypeForNEON method for details.
582     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
583     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
584     // FIXME: Create unittest.
585     // In another words, find a way when "copysign" appears in DAG with vector
586     // operands.
587     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
588     // FIXME: Code duplication: SETCC has custom operation action, see
589     // ARMTargetLowering::addTypeForNEON method for details.
590     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
591     // FIXME: Create unittest for FNEG and for FABS.
592     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
593     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
594     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
595     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
596     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
597     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
598     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
599     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
600     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
601     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
602     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
603     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
604     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
605     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
606     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
607     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
608     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
609     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
610 
611     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
612     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
613     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
614     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
615     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
616     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
617     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
618     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
619     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
620     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
621     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
622     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
623     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
624     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
625 
626     // Mark v2f32 intrinsics.
627     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
628     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
629     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
630     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
631     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
632     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
633     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
634     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
635     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
636     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
637     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
638     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
639     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
640     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
641 
642     // Neon does not support some operations on v1i64 and v2i64 types.
643     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
644     // Custom handling for some quad-vector types to detect VMULL.
645     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
646     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
647     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
648     // Custom handling for some vector types to avoid expensive expansions
649     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
650     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
651     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
652     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
653     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
654     // a destination type that is wider than the source, and nor does
655     // it have a FP_TO_[SU]INT instruction with a narrower destination than
656     // source.
657     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
658     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
659     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
660     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, 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, Expand);
673     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
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   setOperationAction(ISD::ADDC,      MVT::i32, Custom);
843   setOperationAction(ISD::ADDE,      MVT::i32, Custom);
844   setOperationAction(ISD::SUBC,      MVT::i32, Custom);
845   setOperationAction(ISD::SUBE,      MVT::i32, Custom);
846 
847   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
848     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
849 
850   // ARM does not have ROTL.
851   setOperationAction(ISD::ROTL, MVT::i32, Expand);
852   for (MVT VT : MVT::vector_valuetypes()) {
853     setOperationAction(ISD::ROTL, VT, Expand);
854     setOperationAction(ISD::ROTR, VT, Expand);
855   }
856   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
857   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
858   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
859     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
860 
861   // @llvm.readcyclecounter requires the Performance Monitors extension.
862   // Default to the 0 expansion on unsupported platforms.
863   // FIXME: Technically there are older ARM CPUs that have
864   // implementation-specific ways of obtaining this information.
865   if (Subtarget->hasPerfMon())
866     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
867 
868   // Only ARMv6 has BSWAP.
869   if (!Subtarget->hasV6Ops())
870     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
871 
872   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
873                                         : Subtarget->hasDivideInARMMode();
874   if (!hasDivide) {
875     // These are expanded into libcalls if the cpu doesn't have HW divider.
876     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
877     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
878   }
879 
880   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
881     setOperationAction(ISD::SDIV, MVT::i32, Custom);
882     setOperationAction(ISD::UDIV, MVT::i32, Custom);
883 
884     setOperationAction(ISD::SDIV, MVT::i64, Custom);
885     setOperationAction(ISD::UDIV, MVT::i64, Custom);
886   }
887 
888   setOperationAction(ISD::SREM,  MVT::i32, Expand);
889   setOperationAction(ISD::UREM,  MVT::i32, Expand);
890 
891   // Register based DivRem for AEABI (RTABI 4.2)
892   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
893       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
894       Subtarget->isTargetWindows()) {
895     setOperationAction(ISD::SREM, MVT::i64, Custom);
896     setOperationAction(ISD::UREM, MVT::i64, Custom);
897     HasStandaloneRem = false;
898 
899     if (Subtarget->isTargetWindows()) {
900       const struct {
901         const RTLIB::Libcall Op;
902         const char * const Name;
903         const CallingConv::ID CC;
904       } LibraryCalls[] = {
905         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
906         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
907         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
908         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
909 
910         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
911         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
912         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
913         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
914       };
915 
916       for (const auto &LC : LibraryCalls) {
917         setLibcallName(LC.Op, LC.Name);
918         setLibcallCallingConv(LC.Op, LC.CC);
919       }
920     } else {
921       const struct {
922         const RTLIB::Libcall Op;
923         const char * const Name;
924         const CallingConv::ID CC;
925       } LibraryCalls[] = {
926         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
927         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
928         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
929         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
930 
931         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
932         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
933         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
934         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
935       };
936 
937       for (const auto &LC : LibraryCalls) {
938         setLibcallName(LC.Op, LC.Name);
939         setLibcallCallingConv(LC.Op, LC.CC);
940       }
941     }
942 
943     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
944     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
945     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
946     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
947   } else {
948     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
949     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
950   }
951 
952   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
953     for (auto &VT : {MVT::f32, MVT::f64})
954       setOperationAction(ISD::FPOWI, VT, Custom);
955 
956   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
957   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
958   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
959   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
960 
961   setOperationAction(ISD::TRAP, MVT::Other, Legal);
962 
963   // Use the default implementation.
964   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
965   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
966   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
967   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
968   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
969   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
970 
971   if (Subtarget->isTargetWindows())
972     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
973   else
974     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
975 
976   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
977   // the default expansion.
978   InsertFencesForAtomic = false;
979   if (Subtarget->hasAnyDataBarrier() &&
980       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
981     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
982     // to ldrex/strex loops already.
983     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
984     if (!Subtarget->isThumb() || !Subtarget->isMClass())
985       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
986 
987     // On v8, we have particularly efficient implementations of atomic fences
988     // if they can be combined with nearby atomic loads and stores.
989     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
990       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
991       InsertFencesForAtomic = true;
992     }
993   } else {
994     // If there's anything we can use as a barrier, go through custom lowering
995     // for ATOMIC_FENCE.
996     // If target has DMB in thumb, Fences can be inserted.
997     if (Subtarget->hasDataBarrier())
998       InsertFencesForAtomic = true;
999 
1000     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
1001                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
1002 
1003     // Set them all for expansion, which will force libcalls.
1004     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
1005     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
1006     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
1007     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
1008     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
1009     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
1010     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
1011     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1012     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1013     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1014     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1015     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1016     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1017     // Unordered/Monotonic case.
1018     if (!InsertFencesForAtomic) {
1019       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1020       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1021     }
1022   }
1023 
1024   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1025 
1026   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1027   if (!Subtarget->hasV6Ops()) {
1028     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1029     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1030   }
1031   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1032 
1033   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1034       !Subtarget->isThumb1Only()) {
1035     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1036     // iff target supports vfp2.
1037     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1038     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1039   }
1040 
1041   // We want to custom lower some of our intrinsics.
1042   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1043   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1044   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1045   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1046   if (Subtarget->useSjLjEH())
1047     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1048 
1049   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1050   setOperationAction(ISD::SETCC,     MVT::f16, Expand);
1051   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1052   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1053   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1054   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1055   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1056   setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
1057   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1058   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1059   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1060 
1061   // Thumb-1 cannot currently select ARMISD::SUBE.
1062   if (!Subtarget->isThumb1Only())
1063     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1064 
1065   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1066   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1067   setOperationAction(ISD::BR_CC,     MVT::f16,   Custom);
1068   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1069   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1070   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1071 
1072   // We don't support sin/cos/fmod/copysign/pow
1073   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1074   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1075   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1076   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1077   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1078   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1079   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1080   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1081   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1082       !Subtarget->isThumb1Only()) {
1083     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1084     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1085   }
1086   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1087   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1088 
1089   if (!Subtarget->hasVFP4()) {
1090     setOperationAction(ISD::FMA, MVT::f64, Expand);
1091     setOperationAction(ISD::FMA, MVT::f32, Expand);
1092   }
1093 
1094   // Various VFP goodness
1095   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1096     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1097     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1098       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1099       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1100     }
1101 
1102     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1103     if (!Subtarget->hasFP16()) {
1104       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1105       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1106     }
1107   }
1108 
1109   // Use __sincos_stret if available.
1110   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1111       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1112     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1113     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1114   }
1115 
1116   // FP-ARMv8 implements a lot of rounding-like FP operations.
1117   if (Subtarget->hasFPARMv8()) {
1118     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1119     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1120     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1121     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1122     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1123     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1124     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1125     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1126     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1127     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1128     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1129     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1130 
1131     if (!Subtarget->isFPOnlySP()) {
1132       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1133       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1134       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1135       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1136       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1137       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1138       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1139       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1140     }
1141   }
1142 
1143   if (Subtarget->hasNEON()) {
1144     // vmin and vmax aren't available in a scalar form, so we use
1145     // a NEON instruction with an undef lane instead.
1146     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1147     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1148     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1149     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1150     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1151     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1152   }
1153 
1154   // We have target-specific dag combine patterns for the following nodes:
1155   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1156   setTargetDAGCombine(ISD::ADD);
1157   setTargetDAGCombine(ISD::SUB);
1158   setTargetDAGCombine(ISD::MUL);
1159   setTargetDAGCombine(ISD::AND);
1160   setTargetDAGCombine(ISD::OR);
1161   setTargetDAGCombine(ISD::XOR);
1162 
1163   if (Subtarget->hasV6Ops())
1164     setTargetDAGCombine(ISD::SRL);
1165 
1166   setStackPointerRegisterToSaveRestore(ARM::SP);
1167 
1168   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1169       !Subtarget->hasVFP2())
1170     setSchedulingPreference(Sched::RegPressure);
1171   else
1172     setSchedulingPreference(Sched::Hybrid);
1173 
1174   //// temporary - rewrite interface to use type
1175   MaxStoresPerMemset = 8;
1176   MaxStoresPerMemsetOptSize = 4;
1177   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1178   MaxStoresPerMemcpyOptSize = 2;
1179   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1180   MaxStoresPerMemmoveOptSize = 2;
1181 
1182   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1183   // are at least 4 bytes aligned.
1184   setMinStackArgumentAlignment(4);
1185 
1186   // Prefer likely predicted branches to selects on out-of-order cores.
1187   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1188 
1189   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1190 }
1191 
1192 bool ARMTargetLowering::useSoftFloat() const {
1193   return Subtarget->useSoftFloat();
1194 }
1195 
1196 // FIXME: It might make sense to define the representative register class as the
1197 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1198 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1199 // SPR's representative would be DPR_VFP2. This should work well if register
1200 // pressure tracking were modified such that a register use would increment the
1201 // pressure of the register class's representative and all of it's super
1202 // classes' representatives transitively. We have not implemented this because
1203 // of the difficulty prior to coalescing of modeling operand register classes
1204 // due to the common occurrence of cross class copies and subregister insertions
1205 // and extractions.
1206 std::pair<const TargetRegisterClass *, uint8_t>
1207 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1208                                            MVT VT) const {
1209   const TargetRegisterClass *RRC = nullptr;
1210   uint8_t Cost = 1;
1211   switch (VT.SimpleTy) {
1212   default:
1213     return TargetLowering::findRepresentativeClass(TRI, VT);
1214   // Use DPR as representative register class for all floating point
1215   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1216   // the cost is 1 for both f32 and f64.
1217   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1218   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1219     RRC = &ARM::DPRRegClass;
1220     // When NEON is used for SP, only half of the register file is available
1221     // because operations that define both SP and DP results will be constrained
1222     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1223     // coalescing by double-counting the SP regs. See the FIXME above.
1224     if (Subtarget->useNEONForSinglePrecisionFP())
1225       Cost = 2;
1226     break;
1227   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1228   case MVT::v4f32: case MVT::v2f64:
1229     RRC = &ARM::DPRRegClass;
1230     Cost = 2;
1231     break;
1232   case MVT::v4i64:
1233     RRC = &ARM::DPRRegClass;
1234     Cost = 4;
1235     break;
1236   case MVT::v8i64:
1237     RRC = &ARM::DPRRegClass;
1238     Cost = 8;
1239     break;
1240   }
1241   return std::make_pair(RRC, Cost);
1242 }
1243 
1244 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1245   switch ((ARMISD::NodeType)Opcode) {
1246   case ARMISD::FIRST_NUMBER:  break;
1247   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1248   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1249   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1250   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1251   case ARMISD::CALL:          return "ARMISD::CALL";
1252   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1253   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1254   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1255   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1256   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1257   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1258   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1259   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1260   case ARMISD::CMP:           return "ARMISD::CMP";
1261   case ARMISD::CMN:           return "ARMISD::CMN";
1262   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1263   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1264   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1265   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1266   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1267 
1268   case ARMISD::CMOV:          return "ARMISD::CMOV";
1269 
1270   case ARMISD::SSAT:          return "ARMISD::SSAT";
1271   case ARMISD::USAT:          return "ARMISD::USAT";
1272 
1273   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1274   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1275   case ARMISD::RRX:           return "ARMISD::RRX";
1276 
1277   case ARMISD::ADDC:          return "ARMISD::ADDC";
1278   case ARMISD::ADDE:          return "ARMISD::ADDE";
1279   case ARMISD::SUBC:          return "ARMISD::SUBC";
1280   case ARMISD::SUBE:          return "ARMISD::SUBE";
1281 
1282   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1283   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1284   case ARMISD::VMOVhr:        return "ARMISD::VMOVhr";
1285   case ARMISD::VMOVrh:        return "ARMISD::VMOVrh";
1286 
1287   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1288   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1289   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1290 
1291   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1292 
1293   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1294 
1295   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1296 
1297   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1298 
1299   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1300 
1301   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1302   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1303 
1304   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1305   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1306   case ARMISD::VCGE:          return "ARMISD::VCGE";
1307   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1308   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1309   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1310   case ARMISD::VCGT:          return "ARMISD::VCGT";
1311   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1312   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1313   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1314   case ARMISD::VTST:          return "ARMISD::VTST";
1315 
1316   case ARMISD::VSHL:          return "ARMISD::VSHL";
1317   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1318   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1319   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1320   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1321   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1322   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1323   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1324   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1325   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1326   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1327   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1328   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1329   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1330   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1331   case ARMISD::VSLI:          return "ARMISD::VSLI";
1332   case ARMISD::VSRI:          return "ARMISD::VSRI";
1333   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1334   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1335   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1336   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1337   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1338   case ARMISD::VDUP:          return "ARMISD::VDUP";
1339   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1340   case ARMISD::VEXT:          return "ARMISD::VEXT";
1341   case ARMISD::VREV64:        return "ARMISD::VREV64";
1342   case ARMISD::VREV32:        return "ARMISD::VREV32";
1343   case ARMISD::VREV16:        return "ARMISD::VREV16";
1344   case ARMISD::VZIP:          return "ARMISD::VZIP";
1345   case ARMISD::VUZP:          return "ARMISD::VUZP";
1346   case ARMISD::VTRN:          return "ARMISD::VTRN";
1347   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1348   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1349   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1350   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1351   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1352   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1353   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1354   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1355   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1356   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1357   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1358   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1359   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1360   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1361   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1362   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1363   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1364   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1365   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1366   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1367   case ARMISD::BFI:           return "ARMISD::BFI";
1368   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1369   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1370   case ARMISD::VBSL:          return "ARMISD::VBSL";
1371   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1372   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1373   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1374   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1375   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1376   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1377   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1378   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1379   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1380   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1381   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1382   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1383   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1384   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1385   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1386   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1387   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1388   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1389   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1390   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1391   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1392   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1393   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1394   }
1395   return nullptr;
1396 }
1397 
1398 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1399                                           EVT VT) const {
1400   if (!VT.isVector())
1401     return getPointerTy(DL);
1402   return VT.changeVectorElementTypeToInteger();
1403 }
1404 
1405 /// getRegClassFor - Return the register class that should be used for the
1406 /// specified value type.
1407 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1408   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1409   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1410   // load / store 4 to 8 consecutive D registers.
1411   if (Subtarget->hasNEON()) {
1412     if (VT == MVT::v4i64)
1413       return &ARM::QQPRRegClass;
1414     if (VT == MVT::v8i64)
1415       return &ARM::QQQQPRRegClass;
1416   }
1417   return TargetLowering::getRegClassFor(VT);
1418 }
1419 
1420 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1421 // source/dest is aligned and the copy size is large enough. We therefore want
1422 // to align such objects passed to memory intrinsics.
1423 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1424                                                unsigned &PrefAlign) const {
1425   if (!isa<MemIntrinsic>(CI))
1426     return false;
1427   MinSize = 8;
1428   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1429   // cycle faster than 4-byte aligned LDM.
1430   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1431   return true;
1432 }
1433 
1434 // Create a fast isel object.
1435 FastISel *
1436 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1437                                   const TargetLibraryInfo *libInfo) const {
1438   return ARM::createFastISel(funcInfo, libInfo);
1439 }
1440 
1441 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1442   unsigned NumVals = N->getNumValues();
1443   if (!NumVals)
1444     return Sched::RegPressure;
1445 
1446   for (unsigned i = 0; i != NumVals; ++i) {
1447     EVT VT = N->getValueType(i);
1448     if (VT == MVT::Glue || VT == MVT::Other)
1449       continue;
1450     if (VT.isFloatingPoint() || VT.isVector())
1451       return Sched::ILP;
1452   }
1453 
1454   if (!N->isMachineOpcode())
1455     return Sched::RegPressure;
1456 
1457   // Load are scheduled for latency even if there instruction itinerary
1458   // is not available.
1459   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1460   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1461 
1462   if (MCID.getNumDefs() == 0)
1463     return Sched::RegPressure;
1464   if (!Itins->isEmpty() &&
1465       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1466     return Sched::ILP;
1467 
1468   return Sched::RegPressure;
1469 }
1470 
1471 //===----------------------------------------------------------------------===//
1472 // Lowering Code
1473 //===----------------------------------------------------------------------===//
1474 
1475 static bool isSRL16(const SDValue &Op) {
1476   if (Op.getOpcode() != ISD::SRL)
1477     return false;
1478   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1479     return Const->getZExtValue() == 16;
1480   return false;
1481 }
1482 
1483 static bool isSRA16(const SDValue &Op) {
1484   if (Op.getOpcode() != ISD::SRA)
1485     return false;
1486   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1487     return Const->getZExtValue() == 16;
1488   return false;
1489 }
1490 
1491 static bool isSHL16(const SDValue &Op) {
1492   if (Op.getOpcode() != ISD::SHL)
1493     return false;
1494   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1495     return Const->getZExtValue() == 16;
1496   return false;
1497 }
1498 
1499 // Check for a signed 16-bit value. We special case SRA because it makes it
1500 // more simple when also looking for SRAs that aren't sign extending a
1501 // smaller value. Without the check, we'd need to take extra care with
1502 // checking order for some operations.
1503 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1504   if (isSRA16(Op))
1505     return isSHL16(Op.getOperand(0));
1506   return DAG.ComputeNumSignBits(Op) == 17;
1507 }
1508 
1509 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1510 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1511   switch (CC) {
1512   default: llvm_unreachable("Unknown condition code!");
1513   case ISD::SETNE:  return ARMCC::NE;
1514   case ISD::SETEQ:  return ARMCC::EQ;
1515   case ISD::SETGT:  return ARMCC::GT;
1516   case ISD::SETGE:  return ARMCC::GE;
1517   case ISD::SETLT:  return ARMCC::LT;
1518   case ISD::SETLE:  return ARMCC::LE;
1519   case ISD::SETUGT: return ARMCC::HI;
1520   case ISD::SETUGE: return ARMCC::HS;
1521   case ISD::SETULT: return ARMCC::LO;
1522   case ISD::SETULE: return ARMCC::LS;
1523   }
1524 }
1525 
1526 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1527 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1528                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1529   CondCode2 = ARMCC::AL;
1530   InvalidOnQNaN = true;
1531   switch (CC) {
1532   default: llvm_unreachable("Unknown FP condition!");
1533   case ISD::SETEQ:
1534   case ISD::SETOEQ:
1535     CondCode = ARMCC::EQ;
1536     InvalidOnQNaN = false;
1537     break;
1538   case ISD::SETGT:
1539   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1540   case ISD::SETGE:
1541   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1542   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1543   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1544   case ISD::SETONE:
1545     CondCode = ARMCC::MI;
1546     CondCode2 = ARMCC::GT;
1547     InvalidOnQNaN = false;
1548     break;
1549   case ISD::SETO:   CondCode = ARMCC::VC; break;
1550   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1551   case ISD::SETUEQ:
1552     CondCode = ARMCC::EQ;
1553     CondCode2 = ARMCC::VS;
1554     InvalidOnQNaN = false;
1555     break;
1556   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1557   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1558   case ISD::SETLT:
1559   case ISD::SETULT: CondCode = ARMCC::LT; break;
1560   case ISD::SETLE:
1561   case ISD::SETULE: CondCode = ARMCC::LE; break;
1562   case ISD::SETNE:
1563   case ISD::SETUNE:
1564     CondCode = ARMCC::NE;
1565     InvalidOnQNaN = false;
1566     break;
1567   }
1568 }
1569 
1570 //===----------------------------------------------------------------------===//
1571 //                      Calling Convention Implementation
1572 //===----------------------------------------------------------------------===//
1573 
1574 #include "ARMGenCallingConv.inc"
1575 
1576 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1577 /// account presence of floating point hardware and calling convention
1578 /// limitations, such as support for variadic functions.
1579 CallingConv::ID
1580 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1581                                            bool isVarArg) const {
1582   switch (CC) {
1583   default:
1584     report_fatal_error("Unsupported calling convention");
1585   case CallingConv::ARM_AAPCS:
1586   case CallingConv::ARM_APCS:
1587   case CallingConv::GHC:
1588     return CC;
1589   case CallingConv::PreserveMost:
1590     return CallingConv::PreserveMost;
1591   case CallingConv::ARM_AAPCS_VFP:
1592   case CallingConv::Swift:
1593     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1594   case CallingConv::C:
1595     if (!Subtarget->isAAPCS_ABI())
1596       return CallingConv::ARM_APCS;
1597     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1598              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1599              !isVarArg)
1600       return CallingConv::ARM_AAPCS_VFP;
1601     else
1602       return CallingConv::ARM_AAPCS;
1603   case CallingConv::Fast:
1604   case CallingConv::CXX_FAST_TLS:
1605     if (!Subtarget->isAAPCS_ABI()) {
1606       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1607         return CallingConv::Fast;
1608       return CallingConv::ARM_APCS;
1609     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1610       return CallingConv::ARM_AAPCS_VFP;
1611     else
1612       return CallingConv::ARM_AAPCS;
1613   }
1614 }
1615 
1616 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1617                                                  bool isVarArg) const {
1618   return CCAssignFnForNode(CC, false, isVarArg);
1619 }
1620 
1621 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1622                                                    bool isVarArg) const {
1623   return CCAssignFnForNode(CC, true, isVarArg);
1624 }
1625 
1626 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1627 /// CallingConvention.
1628 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1629                                                  bool Return,
1630                                                  bool isVarArg) const {
1631   switch (getEffectiveCallingConv(CC, isVarArg)) {
1632   default:
1633     report_fatal_error("Unsupported calling convention");
1634   case CallingConv::ARM_APCS:
1635     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1636   case CallingConv::ARM_AAPCS:
1637     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1638   case CallingConv::ARM_AAPCS_VFP:
1639     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1640   case CallingConv::Fast:
1641     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1642   case CallingConv::GHC:
1643     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1644   case CallingConv::PreserveMost:
1645     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1646   }
1647 }
1648 
1649 /// LowerCallResult - Lower the result values of a call into the
1650 /// appropriate copies out of appropriate physical registers.
1651 SDValue ARMTargetLowering::LowerCallResult(
1652     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1653     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1654     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1655     SDValue ThisVal) const {
1656   // Assign locations to each value returned by this call.
1657   SmallVector<CCValAssign, 16> RVLocs;
1658   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1659                  *DAG.getContext());
1660   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1661 
1662   // Copy all of the result registers out of their specified physreg.
1663   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1664     CCValAssign VA = RVLocs[i];
1665 
1666     // Pass 'this' value directly from the argument to return value, to avoid
1667     // reg unit interference
1668     if (i == 0 && isThisReturn) {
1669       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1670              "unexpected return calling convention register assignment");
1671       InVals.push_back(ThisVal);
1672       continue;
1673     }
1674 
1675     SDValue Val;
1676     if (VA.needsCustom()) {
1677       // Handle f64 or half of a v2f64.
1678       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1679                                       InFlag);
1680       Chain = Lo.getValue(1);
1681       InFlag = Lo.getValue(2);
1682       VA = RVLocs[++i]; // skip ahead to next loc
1683       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1684                                       InFlag);
1685       Chain = Hi.getValue(1);
1686       InFlag = Hi.getValue(2);
1687       if (!Subtarget->isLittle())
1688         std::swap (Lo, Hi);
1689       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1690 
1691       if (VA.getLocVT() == MVT::v2f64) {
1692         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1693         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1694                           DAG.getConstant(0, dl, MVT::i32));
1695 
1696         VA = RVLocs[++i]; // skip ahead to next loc
1697         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1698         Chain = Lo.getValue(1);
1699         InFlag = Lo.getValue(2);
1700         VA = RVLocs[++i]; // skip ahead to next loc
1701         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1702         Chain = Hi.getValue(1);
1703         InFlag = Hi.getValue(2);
1704         if (!Subtarget->isLittle())
1705           std::swap (Lo, Hi);
1706         Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1707         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1708                           DAG.getConstant(1, dl, MVT::i32));
1709       }
1710     } else {
1711       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1712                                InFlag);
1713       Chain = Val.getValue(1);
1714       InFlag = Val.getValue(2);
1715     }
1716 
1717     switch (VA.getLocInfo()) {
1718     default: llvm_unreachable("Unknown loc info!");
1719     case CCValAssign::Full: break;
1720     case CCValAssign::BCvt:
1721       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1722       break;
1723     }
1724 
1725     InVals.push_back(Val);
1726   }
1727 
1728   return Chain;
1729 }
1730 
1731 /// LowerMemOpCallTo - Store the argument to the stack.
1732 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1733                                             SDValue Arg, const SDLoc &dl,
1734                                             SelectionDAG &DAG,
1735                                             const CCValAssign &VA,
1736                                             ISD::ArgFlagsTy Flags) const {
1737   unsigned LocMemOffset = VA.getLocMemOffset();
1738   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1739   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1740                        StackPtr, PtrOff);
1741   return DAG.getStore(
1742       Chain, dl, Arg, PtrOff,
1743       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1744 }
1745 
1746 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1747                                          SDValue Chain, SDValue &Arg,
1748                                          RegsToPassVector &RegsToPass,
1749                                          CCValAssign &VA, CCValAssign &NextVA,
1750                                          SDValue &StackPtr,
1751                                          SmallVectorImpl<SDValue> &MemOpChains,
1752                                          ISD::ArgFlagsTy Flags) const {
1753   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1754                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1755   unsigned id = Subtarget->isLittle() ? 0 : 1;
1756   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1757 
1758   if (NextVA.isRegLoc())
1759     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1760   else {
1761     assert(NextVA.isMemLoc());
1762     if (!StackPtr.getNode())
1763       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1764                                     getPointerTy(DAG.getDataLayout()));
1765 
1766     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1767                                            dl, DAG, NextVA,
1768                                            Flags));
1769   }
1770 }
1771 
1772 /// LowerCall - Lowering a call into a callseq_start <-
1773 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1774 /// nodes.
1775 SDValue
1776 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1777                              SmallVectorImpl<SDValue> &InVals) const {
1778   SelectionDAG &DAG                     = CLI.DAG;
1779   SDLoc &dl                             = CLI.DL;
1780   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1781   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1782   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1783   SDValue Chain                         = CLI.Chain;
1784   SDValue Callee                        = CLI.Callee;
1785   bool &isTailCall                      = CLI.IsTailCall;
1786   CallingConv::ID CallConv              = CLI.CallConv;
1787   bool doesNotRet                       = CLI.DoesNotReturn;
1788   bool isVarArg                         = CLI.IsVarArg;
1789 
1790   MachineFunction &MF = DAG.getMachineFunction();
1791   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1792   bool isThisReturn   = false;
1793   bool isSibCall      = false;
1794   auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
1795 
1796   // Disable tail calls if they're not supported.
1797   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1798     isTailCall = false;
1799 
1800   if (isTailCall) {
1801     // Check if it's really possible to do a tail call.
1802     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1803                     isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(),
1804                                                    Outs, OutVals, Ins, DAG);
1805     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1806       report_fatal_error("failed to perform tail call elimination on a call "
1807                          "site marked musttail");
1808     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1809     // detected sibcalls.
1810     if (isTailCall) {
1811       ++NumTailCalls;
1812       isSibCall = true;
1813     }
1814   }
1815 
1816   // Analyze operands of the call, assigning locations to each operand.
1817   SmallVector<CCValAssign, 16> ArgLocs;
1818   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1819                  *DAG.getContext());
1820   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1821 
1822   // Get a count of how many bytes are to be pushed on the stack.
1823   unsigned NumBytes = CCInfo.getNextStackOffset();
1824 
1825   // For tail calls, memory operands are available in our caller's stack.
1826   if (isSibCall)
1827     NumBytes = 0;
1828 
1829   // Adjust the stack pointer for the new arguments...
1830   // These operations are automatically eliminated by the prolog/epilog pass
1831   if (!isSibCall)
1832     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1833 
1834   SDValue StackPtr =
1835       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1836 
1837   RegsToPassVector RegsToPass;
1838   SmallVector<SDValue, 8> MemOpChains;
1839 
1840   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1841   // of tail call optimization, arguments are handled later.
1842   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1843        i != e;
1844        ++i, ++realArgIdx) {
1845     CCValAssign &VA = ArgLocs[i];
1846     SDValue Arg = OutVals[realArgIdx];
1847     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1848     bool isByVal = Flags.isByVal();
1849 
1850     // Promote the value if needed.
1851     switch (VA.getLocInfo()) {
1852     default: llvm_unreachable("Unknown loc info!");
1853     case CCValAssign::Full: break;
1854     case CCValAssign::SExt:
1855       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1856       break;
1857     case CCValAssign::ZExt:
1858       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1859       break;
1860     case CCValAssign::AExt:
1861       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1862       break;
1863     case CCValAssign::BCvt:
1864       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1865       break;
1866     }
1867 
1868     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1869     if (VA.needsCustom()) {
1870       if (VA.getLocVT() == MVT::v2f64) {
1871         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1872                                   DAG.getConstant(0, dl, MVT::i32));
1873         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1874                                   DAG.getConstant(1, dl, MVT::i32));
1875 
1876         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1877                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1878 
1879         VA = ArgLocs[++i]; // skip ahead to next loc
1880         if (VA.isRegLoc()) {
1881           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1882                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1883         } else {
1884           assert(VA.isMemLoc());
1885 
1886           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1887                                                  dl, DAG, VA, Flags));
1888         }
1889       } else {
1890         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1891                          StackPtr, MemOpChains, Flags);
1892       }
1893     } else if (VA.isRegLoc()) {
1894       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1895           Outs[0].VT == MVT::i32) {
1896         assert(VA.getLocVT() == MVT::i32 &&
1897                "unexpected calling convention register assignment");
1898         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1899                "unexpected use of 'returned'");
1900         isThisReturn = true;
1901       }
1902       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1903     } else if (isByVal) {
1904       assert(VA.isMemLoc());
1905       unsigned offset = 0;
1906 
1907       // True if this byval aggregate will be split between registers
1908       // and memory.
1909       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1910       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1911 
1912       if (CurByValIdx < ByValArgsCount) {
1913 
1914         unsigned RegBegin, RegEnd;
1915         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1916 
1917         EVT PtrVT =
1918             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1919         unsigned int i, j;
1920         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1921           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1922           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1923           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1924                                      MachinePointerInfo(),
1925                                      DAG.InferPtrAlignment(AddArg));
1926           MemOpChains.push_back(Load.getValue(1));
1927           RegsToPass.push_back(std::make_pair(j, Load));
1928         }
1929 
1930         // If parameter size outsides register area, "offset" value
1931         // helps us to calculate stack slot for remained part properly.
1932         offset = RegEnd - RegBegin;
1933 
1934         CCInfo.nextInRegsParam();
1935       }
1936 
1937       if (Flags.getByValSize() > 4*offset) {
1938         auto PtrVT = getPointerTy(DAG.getDataLayout());
1939         unsigned LocMemOffset = VA.getLocMemOffset();
1940         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1941         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1942         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1943         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1944         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1945                                            MVT::i32);
1946         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1947                                             MVT::i32);
1948 
1949         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1950         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1951         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1952                                           Ops));
1953       }
1954     } else if (!isSibCall) {
1955       assert(VA.isMemLoc());
1956 
1957       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1958                                              dl, DAG, VA, Flags));
1959     }
1960   }
1961 
1962   if (!MemOpChains.empty())
1963     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1964 
1965   // Build a sequence of copy-to-reg nodes chained together with token chain
1966   // and flag operands which copy the outgoing args into the appropriate regs.
1967   SDValue InFlag;
1968   // Tail call byval lowering might overwrite argument registers so in case of
1969   // tail call optimization the copies to registers are lowered later.
1970   if (!isTailCall)
1971     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1972       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1973                                RegsToPass[i].second, InFlag);
1974       InFlag = Chain.getValue(1);
1975     }
1976 
1977   // For tail calls lower the arguments to the 'real' stack slot.
1978   if (isTailCall) {
1979     // Force all the incoming stack arguments to be loaded from the stack
1980     // before any new outgoing arguments are stored to the stack, because the
1981     // outgoing stack slots may alias the incoming argument stack slots, and
1982     // the alias isn't otherwise explicit. This is slightly more conservative
1983     // than necessary, because it means that each store effectively depends
1984     // on every argument instead of just those arguments it would clobber.
1985 
1986     // Do not flag preceding copytoreg stuff together with the following stuff.
1987     InFlag = SDValue();
1988     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1989       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1990                                RegsToPass[i].second, InFlag);
1991       InFlag = Chain.getValue(1);
1992     }
1993     InFlag = SDValue();
1994   }
1995 
1996   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1997   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1998   // node so that legalize doesn't hack it.
1999   bool isDirect = false;
2000 
2001   const TargetMachine &TM = getTargetMachine();
2002   const Module *Mod = MF.getFunction().getParent();
2003   const GlobalValue *GV = nullptr;
2004   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
2005     GV = G->getGlobal();
2006   bool isStub =
2007       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
2008 
2009   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
2010   bool isLocalARMFunc = false;
2011   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2012   auto PtrVt = getPointerTy(DAG.getDataLayout());
2013 
2014   if (Subtarget->genLongCalls()) {
2015     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
2016            "long-calls codegen is not position independent!");
2017     // Handle a global address or an external symbol. If it's not one of
2018     // those, the target's already in a register, so we don't need to do
2019     // anything extra.
2020     if (isa<GlobalAddressSDNode>(Callee)) {
2021       // Create a constant pool entry for the callee address
2022       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2023       ARMConstantPoolValue *CPV =
2024         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2025 
2026       // Get the address of the callee into a register
2027       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2028       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2029       Callee = DAG.getLoad(
2030           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2031           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2032     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2033       const char *Sym = S->getSymbol();
2034 
2035       // Create a constant pool entry for the callee address
2036       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2037       ARMConstantPoolValue *CPV =
2038         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2039                                       ARMPCLabelIndex, 0);
2040       // Get the address of the callee into a register
2041       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2042       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2043       Callee = DAG.getLoad(
2044           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2045           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2046     }
2047   } else if (isa<GlobalAddressSDNode>(Callee)) {
2048     // If we're optimizing for minimum size and the function is called three or
2049     // more times in this block, we can improve codesize by calling indirectly
2050     // as BLXr has a 16-bit encoding.
2051     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2052     auto *BB = CLI.CS.getParent();
2053     bool PreferIndirect =
2054         Subtarget->isThumb() && MF.getFunction().optForMinSize() &&
2055         count_if(GV->users(), [&BB](const User *U) {
2056           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2057         }) > 2;
2058 
2059     if (!PreferIndirect) {
2060       isDirect = true;
2061       bool isDef = GV->isStrongDefinitionForLinker();
2062 
2063       // ARM call to a local ARM function is predicable.
2064       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2065       // tBX takes a register source operand.
2066       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2067         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2068         Callee = DAG.getNode(
2069             ARMISD::WrapperPIC, dl, PtrVt,
2070             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2071         Callee = DAG.getLoad(
2072             PtrVt, dl, DAG.getEntryNode(), Callee,
2073             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2074             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2075                                      MachineMemOperand::MOInvariant);
2076       } else if (Subtarget->isTargetCOFF()) {
2077         assert(Subtarget->isTargetWindows() &&
2078                "Windows is the only supported COFF target");
2079         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2080                                    ? ARMII::MO_DLLIMPORT
2081                                    : ARMII::MO_NO_FLAG;
2082         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2083                                             TargetFlags);
2084         if (GV->hasDLLImportStorageClass())
2085           Callee =
2086               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2087                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2088                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2089       } else {
2090         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2091       }
2092     }
2093   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2094     isDirect = true;
2095     // tBX takes a register source operand.
2096     const char *Sym = S->getSymbol();
2097     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2098       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2099       ARMConstantPoolValue *CPV =
2100         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2101                                       ARMPCLabelIndex, 4);
2102       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2103       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2104       Callee = DAG.getLoad(
2105           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2106           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2107       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2108       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2109     } else {
2110       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2111     }
2112   }
2113 
2114   // FIXME: handle tail calls differently.
2115   unsigned CallOpc;
2116   if (Subtarget->isThumb()) {
2117     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2118       CallOpc = ARMISD::CALL_NOLINK;
2119     else
2120       CallOpc = ARMISD::CALL;
2121   } else {
2122     if (!isDirect && !Subtarget->hasV5TOps())
2123       CallOpc = ARMISD::CALL_NOLINK;
2124     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2125              // Emit regular call when code size is the priority
2126              !MF.getFunction().optForMinSize())
2127       // "mov lr, pc; b _foo" to avoid confusing the RSP
2128       CallOpc = ARMISD::CALL_NOLINK;
2129     else
2130       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2131   }
2132 
2133   std::vector<SDValue> Ops;
2134   Ops.push_back(Chain);
2135   Ops.push_back(Callee);
2136 
2137   // Add argument registers to the end of the list so that they are known live
2138   // into the call.
2139   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2140     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2141                                   RegsToPass[i].second.getValueType()));
2142 
2143   // Add a register mask operand representing the call-preserved registers.
2144   if (!isTailCall) {
2145     const uint32_t *Mask;
2146     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2147     if (isThisReturn) {
2148       // For 'this' returns, use the R0-preserving mask if applicable
2149       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2150       if (!Mask) {
2151         // Set isThisReturn to false if the calling convention is not one that
2152         // allows 'returned' to be modeled in this way, so LowerCallResult does
2153         // not try to pass 'this' straight through
2154         isThisReturn = false;
2155         Mask = ARI->getCallPreservedMask(MF, CallConv);
2156       }
2157     } else
2158       Mask = ARI->getCallPreservedMask(MF, CallConv);
2159 
2160     assert(Mask && "Missing call preserved mask for calling convention");
2161     Ops.push_back(DAG.getRegisterMask(Mask));
2162   }
2163 
2164   if (InFlag.getNode())
2165     Ops.push_back(InFlag);
2166 
2167   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2168   if (isTailCall) {
2169     MF.getFrameInfo().setHasTailCall();
2170     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2171   }
2172 
2173   // Returns a chain and a flag for retval copy to use.
2174   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2175   InFlag = Chain.getValue(1);
2176 
2177   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2178                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2179   if (!Ins.empty())
2180     InFlag = Chain.getValue(1);
2181 
2182   // Handle result values, copying them out of physregs into vregs that we
2183   // return.
2184   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2185                          InVals, isThisReturn,
2186                          isThisReturn ? OutVals[0] : SDValue());
2187 }
2188 
2189 /// HandleByVal - Every parameter *after* a byval parameter is passed
2190 /// on the stack.  Remember the next parameter register to allocate,
2191 /// and then confiscate the rest of the parameter registers to insure
2192 /// this.
2193 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2194                                     unsigned Align) const {
2195   // Byval (as with any stack) slots are always at least 4 byte aligned.
2196   Align = std::max(Align, 4U);
2197 
2198   unsigned Reg = State->AllocateReg(GPRArgRegs);
2199   if (!Reg)
2200     return;
2201 
2202   unsigned AlignInRegs = Align / 4;
2203   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2204   for (unsigned i = 0; i < Waste; ++i)
2205     Reg = State->AllocateReg(GPRArgRegs);
2206 
2207   if (!Reg)
2208     return;
2209 
2210   unsigned Excess = 4 * (ARM::R4 - Reg);
2211 
2212   // Special case when NSAA != SP and parameter size greater than size of
2213   // all remained GPR regs. In that case we can't split parameter, we must
2214   // send it to stack. We also must set NCRN to R4, so waste all
2215   // remained registers.
2216   const unsigned NSAAOffset = State->getNextStackOffset();
2217   if (NSAAOffset != 0 && Size > Excess) {
2218     while (State->AllocateReg(GPRArgRegs))
2219       ;
2220     return;
2221   }
2222 
2223   // First register for byval parameter is the first register that wasn't
2224   // allocated before this method call, so it would be "reg".
2225   // If parameter is small enough to be saved in range [reg, r4), then
2226   // the end (first after last) register would be reg + param-size-in-regs,
2227   // else parameter would be splitted between registers and stack,
2228   // end register would be r4 in this case.
2229   unsigned ByValRegBegin = Reg;
2230   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2231   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2232   // Note, first register is allocated in the beginning of function already,
2233   // allocate remained amount of registers we need.
2234   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2235     State->AllocateReg(GPRArgRegs);
2236   // A byval parameter that is split between registers and memory needs its
2237   // size truncated here.
2238   // In the case where the entire structure fits in registers, we set the
2239   // size in memory to zero.
2240   Size = std::max<int>(Size - Excess, 0);
2241 }
2242 
2243 /// MatchingStackOffset - Return true if the given stack call argument is
2244 /// already available in the same position (relatively) of the caller's
2245 /// incoming argument stack.
2246 static
2247 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2248                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2249                          const TargetInstrInfo *TII) {
2250   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2251   int FI = std::numeric_limits<int>::max();
2252   if (Arg.getOpcode() == ISD::CopyFromReg) {
2253     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2254     if (!TargetRegisterInfo::isVirtualRegister(VR))
2255       return false;
2256     MachineInstr *Def = MRI->getVRegDef(VR);
2257     if (!Def)
2258       return false;
2259     if (!Flags.isByVal()) {
2260       if (!TII->isLoadFromStackSlot(*Def, FI))
2261         return false;
2262     } else {
2263       return false;
2264     }
2265   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2266     if (Flags.isByVal())
2267       // ByVal argument is passed in as a pointer but it's now being
2268       // dereferenced. e.g.
2269       // define @foo(%struct.X* %A) {
2270       //   tail call @bar(%struct.X* byval %A)
2271       // }
2272       return false;
2273     SDValue Ptr = Ld->getBasePtr();
2274     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2275     if (!FINode)
2276       return false;
2277     FI = FINode->getIndex();
2278   } else
2279     return false;
2280 
2281   assert(FI != std::numeric_limits<int>::max());
2282   if (!MFI.isFixedObjectIndex(FI))
2283     return false;
2284   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2285 }
2286 
2287 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2288 /// for tail call optimization. Targets which want to do tail call
2289 /// optimization should implement this function.
2290 bool
2291 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2292                                                      CallingConv::ID CalleeCC,
2293                                                      bool isVarArg,
2294                                                      bool isCalleeStructRet,
2295                                                      bool isCallerStructRet,
2296                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2297                                     const SmallVectorImpl<SDValue> &OutVals,
2298                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2299                                                      SelectionDAG& DAG) const {
2300   MachineFunction &MF = DAG.getMachineFunction();
2301   const Function &CallerF = MF.getFunction();
2302   CallingConv::ID CallerCC = CallerF.getCallingConv();
2303 
2304   assert(Subtarget->supportsTailCall());
2305 
2306   // Tail calls to function pointers cannot be optimized for Thumb1 if the args
2307   // to the call take up r0-r3. The reason is that there are no legal registers
2308   // left to hold the pointer to the function to be called.
2309   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2310       !isa<GlobalAddressSDNode>(Callee.getNode()))
2311       return false;
2312 
2313   // Look for obvious safe cases to perform tail call optimization that do not
2314   // require ABI changes. This is what gcc calls sibcall.
2315 
2316   // Exception-handling functions need a special set of instructions to indicate
2317   // a return to the hardware. Tail-calling another function would probably
2318   // break this.
2319   if (CallerF.hasFnAttribute("interrupt"))
2320     return false;
2321 
2322   // Also avoid sibcall optimization if either caller or callee uses struct
2323   // return semantics.
2324   if (isCalleeStructRet || isCallerStructRet)
2325     return false;
2326 
2327   // Externally-defined functions with weak linkage should not be
2328   // tail-called on ARM when the OS does not support dynamic
2329   // pre-emption of symbols, as the AAELF spec requires normal calls
2330   // to undefined weak functions to be replaced with a NOP or jump to the
2331   // next instruction. The behaviour of branch instructions in this
2332   // situation (as used for tail calls) is implementation-defined, so we
2333   // cannot rely on the linker replacing the tail call with a return.
2334   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2335     const GlobalValue *GV = G->getGlobal();
2336     const Triple &TT = getTargetMachine().getTargetTriple();
2337     if (GV->hasExternalWeakLinkage() &&
2338         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2339       return false;
2340   }
2341 
2342   // Check that the call results are passed in the same way.
2343   LLVMContext &C = *DAG.getContext();
2344   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2345                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2346                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2347     return false;
2348   // The callee has to preserve all registers the caller needs to preserve.
2349   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2350   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2351   if (CalleeCC != CallerCC) {
2352     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2353     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2354       return false;
2355   }
2356 
2357   // If Caller's vararg or byval argument has been split between registers and
2358   // stack, do not perform tail call, since part of the argument is in caller's
2359   // local frame.
2360   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2361   if (AFI_Caller->getArgRegsSaveSize())
2362     return false;
2363 
2364   // If the callee takes no arguments then go on to check the results of the
2365   // call.
2366   if (!Outs.empty()) {
2367     // Check if stack adjustment is needed. For now, do not do this if any
2368     // argument is passed on the stack.
2369     SmallVector<CCValAssign, 16> ArgLocs;
2370     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2371     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2372     if (CCInfo.getNextStackOffset()) {
2373       // Check if the arguments are already laid out in the right way as
2374       // the caller's fixed stack objects.
2375       MachineFrameInfo &MFI = MF.getFrameInfo();
2376       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2377       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2378       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2379            i != e;
2380            ++i, ++realArgIdx) {
2381         CCValAssign &VA = ArgLocs[i];
2382         EVT RegVT = VA.getLocVT();
2383         SDValue Arg = OutVals[realArgIdx];
2384         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2385         if (VA.getLocInfo() == CCValAssign::Indirect)
2386           return false;
2387         if (VA.needsCustom()) {
2388           // f64 and vector types are split into multiple registers or
2389           // register/stack-slot combinations.  The types will not match
2390           // the registers; give up on memory f64 refs until we figure
2391           // out what to do about this.
2392           if (!VA.isRegLoc())
2393             return false;
2394           if (!ArgLocs[++i].isRegLoc())
2395             return false;
2396           if (RegVT == MVT::v2f64) {
2397             if (!ArgLocs[++i].isRegLoc())
2398               return false;
2399             if (!ArgLocs[++i].isRegLoc())
2400               return false;
2401           }
2402         } else if (!VA.isRegLoc()) {
2403           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2404                                    MFI, MRI, TII))
2405             return false;
2406         }
2407       }
2408     }
2409 
2410     const MachineRegisterInfo &MRI = MF.getRegInfo();
2411     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2412       return false;
2413   }
2414 
2415   return true;
2416 }
2417 
2418 bool
2419 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2420                                   MachineFunction &MF, bool isVarArg,
2421                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2422                                   LLVMContext &Context) const {
2423   SmallVector<CCValAssign, 16> RVLocs;
2424   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2425   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2426 }
2427 
2428 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2429                                     const SDLoc &DL, SelectionDAG &DAG) {
2430   const MachineFunction &MF = DAG.getMachineFunction();
2431   const Function &F = MF.getFunction();
2432 
2433   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2434 
2435   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2436   // version of the "preferred return address". These offsets affect the return
2437   // instruction if this is a return from PL1 without hypervisor extensions.
2438   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2439   //    SWI:     0      "subs pc, lr, #0"
2440   //    ABORT:   +4     "subs pc, lr, #4"
2441   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2442   // UNDEF varies depending on where the exception came from ARM or Thumb
2443   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2444 
2445   int64_t LROffset;
2446   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2447       IntKind == "ABORT")
2448     LROffset = 4;
2449   else if (IntKind == "SWI" || IntKind == "UNDEF")
2450     LROffset = 0;
2451   else
2452     report_fatal_error("Unsupported interrupt attribute. If present, value "
2453                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2454 
2455   RetOps.insert(RetOps.begin() + 1,
2456                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2457 
2458   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2459 }
2460 
2461 SDValue
2462 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2463                                bool isVarArg,
2464                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2465                                const SmallVectorImpl<SDValue> &OutVals,
2466                                const SDLoc &dl, SelectionDAG &DAG) const {
2467   // CCValAssign - represent the assignment of the return value to a location.
2468   SmallVector<CCValAssign, 16> RVLocs;
2469 
2470   // CCState - Info about the registers and stack slots.
2471   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2472                  *DAG.getContext());
2473 
2474   // Analyze outgoing return values.
2475   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2476 
2477   SDValue Flag;
2478   SmallVector<SDValue, 4> RetOps;
2479   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2480   bool isLittleEndian = Subtarget->isLittle();
2481 
2482   MachineFunction &MF = DAG.getMachineFunction();
2483   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2484   AFI->setReturnRegsCount(RVLocs.size());
2485 
2486   // Copy the result values into the output registers.
2487   for (unsigned i = 0, realRVLocIdx = 0;
2488        i != RVLocs.size();
2489        ++i, ++realRVLocIdx) {
2490     CCValAssign &VA = RVLocs[i];
2491     assert(VA.isRegLoc() && "Can only return in registers!");
2492 
2493     SDValue Arg = OutVals[realRVLocIdx];
2494     bool ReturnF16 = false;
2495 
2496     if (Subtarget->hasFullFP16() && Subtarget->isTargetHardFloat()) {
2497       // Half-precision return values can be returned like this:
2498       //
2499       // t11 f16 = fadd ...
2500       // t12: i16 = bitcast t11
2501       //   t13: i32 = zero_extend t12
2502       // t14: f32 = bitcast t13  <~~~~~~~ Arg
2503       //
2504       // to avoid code generation for bitcasts, we simply set Arg to the node
2505       // that produces the f16 value, t11 in this case.
2506       //
2507       if (Arg.getValueType() == MVT::f32 && Arg.getOpcode() == ISD::BITCAST) {
2508         SDValue ZE = Arg.getOperand(0);
2509         if (ZE.getOpcode() == ISD::ZERO_EXTEND && ZE.getValueType() == MVT::i32) {
2510           SDValue BC = ZE.getOperand(0);
2511           if (BC.getOpcode() == ISD::BITCAST && BC.getValueType() == MVT::i16) {
2512             Arg = BC.getOperand(0);
2513             ReturnF16 = true;
2514           }
2515         }
2516       }
2517     }
2518 
2519     switch (VA.getLocInfo()) {
2520     default: llvm_unreachable("Unknown loc info!");
2521     case CCValAssign::Full: break;
2522     case CCValAssign::BCvt:
2523       if (!ReturnF16)
2524         Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2525       break;
2526     }
2527 
2528     if (VA.needsCustom()) {
2529       if (VA.getLocVT() == MVT::v2f64) {
2530         // Extract the first half and return it in two registers.
2531         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2532                                    DAG.getConstant(0, dl, MVT::i32));
2533         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2534                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2535 
2536         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2537                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2538                                  Flag);
2539         Flag = Chain.getValue(1);
2540         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2541         VA = RVLocs[++i]; // skip ahead to next loc
2542         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2543                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2544                                  Flag);
2545         Flag = Chain.getValue(1);
2546         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2547         VA = RVLocs[++i]; // skip ahead to next loc
2548 
2549         // Extract the 2nd half and fall through to handle it as an f64 value.
2550         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2551                           DAG.getConstant(1, dl, MVT::i32));
2552       }
2553       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2554       // available.
2555       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2556                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2557       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2558                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2559                                Flag);
2560       Flag = Chain.getValue(1);
2561       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2562       VA = RVLocs[++i]; // skip ahead to next loc
2563       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2564                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2565                                Flag);
2566     } else
2567       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2568 
2569     // Guarantee that all emitted copies are
2570     // stuck together, avoiding something bad.
2571     Flag = Chain.getValue(1);
2572     RetOps.push_back(DAG.getRegister(VA.getLocReg(),
2573                                      ReturnF16 ? MVT::f16 : VA.getLocVT()));
2574   }
2575   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2576   const MCPhysReg *I =
2577       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2578   if (I) {
2579     for (; *I; ++I) {
2580       if (ARM::GPRRegClass.contains(*I))
2581         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2582       else if (ARM::DPRRegClass.contains(*I))
2583         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2584       else
2585         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2586     }
2587   }
2588 
2589   // Update chain and glue.
2590   RetOps[0] = Chain;
2591   if (Flag.getNode())
2592     RetOps.push_back(Flag);
2593 
2594   // CPUs which aren't M-class use a special sequence to return from
2595   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2596   // though we use "subs pc, lr, #N").
2597   //
2598   // M-class CPUs actually use a normal return sequence with a special
2599   // (hardware-provided) value in LR, so the normal code path works.
2600   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2601       !Subtarget->isMClass()) {
2602     if (Subtarget->isThumb1Only())
2603       report_fatal_error("interrupt attribute is not supported in Thumb1");
2604     return LowerInterruptReturn(RetOps, dl, DAG);
2605   }
2606 
2607   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2608 }
2609 
2610 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2611   if (N->getNumValues() != 1)
2612     return false;
2613   if (!N->hasNUsesOfValue(1, 0))
2614     return false;
2615 
2616   SDValue TCChain = Chain;
2617   SDNode *Copy = *N->use_begin();
2618   if (Copy->getOpcode() == ISD::CopyToReg) {
2619     // If the copy has a glue operand, we conservatively assume it isn't safe to
2620     // perform a tail call.
2621     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2622       return false;
2623     TCChain = Copy->getOperand(0);
2624   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2625     SDNode *VMov = Copy;
2626     // f64 returned in a pair of GPRs.
2627     SmallPtrSet<SDNode*, 2> Copies;
2628     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2629          UI != UE; ++UI) {
2630       if (UI->getOpcode() != ISD::CopyToReg)
2631         return false;
2632       Copies.insert(*UI);
2633     }
2634     if (Copies.size() > 2)
2635       return false;
2636 
2637     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2638          UI != UE; ++UI) {
2639       SDValue UseChain = UI->getOperand(0);
2640       if (Copies.count(UseChain.getNode()))
2641         // Second CopyToReg
2642         Copy = *UI;
2643       else {
2644         // We are at the top of this chain.
2645         // If the copy has a glue operand, we conservatively assume it
2646         // isn't safe to perform a tail call.
2647         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2648           return false;
2649         // First CopyToReg
2650         TCChain = UseChain;
2651       }
2652     }
2653   } else if (Copy->getOpcode() == ISD::BITCAST) {
2654     // f32 returned in a single GPR.
2655     if (!Copy->hasOneUse())
2656       return false;
2657     Copy = *Copy->use_begin();
2658     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2659       return false;
2660     // If the copy has a glue operand, we conservatively assume it isn't safe to
2661     // perform a tail call.
2662     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2663       return false;
2664     TCChain = Copy->getOperand(0);
2665   } else {
2666     return false;
2667   }
2668 
2669   bool HasRet = false;
2670   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2671        UI != UE; ++UI) {
2672     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2673         UI->getOpcode() != ARMISD::INTRET_FLAG)
2674       return false;
2675     HasRet = true;
2676   }
2677 
2678   if (!HasRet)
2679     return false;
2680 
2681   Chain = TCChain;
2682   return true;
2683 }
2684 
2685 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2686   if (!Subtarget->supportsTailCall())
2687     return false;
2688 
2689   auto Attr =
2690       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2691   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2692     return false;
2693 
2694   return true;
2695 }
2696 
2697 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2698 // and pass the lower and high parts through.
2699 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2700   SDLoc DL(Op);
2701   SDValue WriteValue = Op->getOperand(2);
2702 
2703   // This function is only supposed to be called for i64 type argument.
2704   assert(WriteValue.getValueType() == MVT::i64
2705           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2706 
2707   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2708                            DAG.getConstant(0, DL, MVT::i32));
2709   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2710                            DAG.getConstant(1, DL, MVT::i32));
2711   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2712   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2713 }
2714 
2715 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2716 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2717 // one of the above mentioned nodes. It has to be wrapped because otherwise
2718 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2719 // be used to form addressing mode. These wrapped nodes will be selected
2720 // into MOVi.
2721 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2722                                              SelectionDAG &DAG) const {
2723   EVT PtrVT = Op.getValueType();
2724   // FIXME there is no actual debug info here
2725   SDLoc dl(Op);
2726   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2727   SDValue Res;
2728 
2729   // When generating execute-only code Constant Pools must be promoted to the
2730   // global data section. It's a bit ugly that we can't share them across basic
2731   // blocks, but this way we guarantee that execute-only behaves correct with
2732   // position-independent addressing modes.
2733   if (Subtarget->genExecuteOnly()) {
2734     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2735     auto T = const_cast<Type*>(CP->getType());
2736     auto C = const_cast<Constant*>(CP->getConstVal());
2737     auto M = const_cast<Module*>(DAG.getMachineFunction().
2738                                  getFunction().getParent());
2739     auto GV = new GlobalVariable(
2740                     *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2741                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2742                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2743                     Twine(AFI->createPICLabelUId())
2744                   );
2745     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2746                                             dl, PtrVT);
2747     return LowerGlobalAddress(GA, DAG);
2748   }
2749 
2750   if (CP->isMachineConstantPoolEntry())
2751     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2752                                     CP->getAlignment());
2753   else
2754     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2755                                     CP->getAlignment());
2756   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2757 }
2758 
2759 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2760   return MachineJumpTableInfo::EK_Inline;
2761 }
2762 
2763 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2764                                              SelectionDAG &DAG) const {
2765   MachineFunction &MF = DAG.getMachineFunction();
2766   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2767   unsigned ARMPCLabelIndex = 0;
2768   SDLoc DL(Op);
2769   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2770   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2771   SDValue CPAddr;
2772   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2773   if (!IsPositionIndependent) {
2774     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2775   } else {
2776     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2777     ARMPCLabelIndex = AFI->createPICLabelUId();
2778     ARMConstantPoolValue *CPV =
2779       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2780                                       ARMCP::CPBlockAddress, PCAdj);
2781     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2782   }
2783   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2784   SDValue Result = DAG.getLoad(
2785       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2786       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2787   if (!IsPositionIndependent)
2788     return Result;
2789   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2790   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2791 }
2792 
2793 /// \brief Convert a TLS address reference into the correct sequence of loads
2794 /// and calls to compute the variable's address for Darwin, and return an
2795 /// SDValue containing the final node.
2796 
2797 /// Darwin only has one TLS scheme which must be capable of dealing with the
2798 /// fully general situation, in the worst case. This means:
2799 ///     + "extern __thread" declaration.
2800 ///     + Defined in a possibly unknown dynamic library.
2801 ///
2802 /// The general system is that each __thread variable has a [3 x i32] descriptor
2803 /// which contains information used by the runtime to calculate the address. The
2804 /// only part of this the compiler needs to know about is the first word, which
2805 /// contains a function pointer that must be called with the address of the
2806 /// entire descriptor in "r0".
2807 ///
2808 /// Since this descriptor may be in a different unit, in general access must
2809 /// proceed along the usual ARM rules. A common sequence to produce is:
2810 ///
2811 ///     movw rT1, :lower16:_var$non_lazy_ptr
2812 ///     movt rT1, :upper16:_var$non_lazy_ptr
2813 ///     ldr r0, [rT1]
2814 ///     ldr rT2, [r0]
2815 ///     blx rT2
2816 ///     [...address now in r0...]
2817 SDValue
2818 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2819                                                SelectionDAG &DAG) const {
2820   assert(Subtarget->isTargetDarwin() &&
2821          "This function expects a Darwin target");
2822   SDLoc DL(Op);
2823 
2824   // First step is to get the address of the actua global symbol. This is where
2825   // the TLS descriptor lives.
2826   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2827 
2828   // The first entry in the descriptor is a function pointer that we must call
2829   // to obtain the address of the variable.
2830   SDValue Chain = DAG.getEntryNode();
2831   SDValue FuncTLVGet = DAG.getLoad(
2832       MVT::i32, DL, Chain, DescAddr,
2833       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2834       /* Alignment = */ 4,
2835       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2836           MachineMemOperand::MOInvariant);
2837   Chain = FuncTLVGet.getValue(1);
2838 
2839   MachineFunction &F = DAG.getMachineFunction();
2840   MachineFrameInfo &MFI = F.getFrameInfo();
2841   MFI.setAdjustsStack(true);
2842 
2843   // TLS calls preserve all registers except those that absolutely must be
2844   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2845   // silly).
2846   auto TRI =
2847       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
2848   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2849   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2850 
2851   // Finally, we can make the call. This is just a degenerate version of a
2852   // normal AArch64 call node: r0 takes the address of the descriptor, and
2853   // returns the address of the variable in this thread.
2854   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2855   Chain =
2856       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2857                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2858                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2859   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2860 }
2861 
2862 SDValue
2863 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2864                                                 SelectionDAG &DAG) const {
2865   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2866 
2867   SDValue Chain = DAG.getEntryNode();
2868   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2869   SDLoc DL(Op);
2870 
2871   // Load the current TEB (thread environment block)
2872   SDValue Ops[] = {Chain,
2873                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2874                    DAG.getConstant(15, DL, MVT::i32),
2875                    DAG.getConstant(0, DL, MVT::i32),
2876                    DAG.getConstant(13, DL, MVT::i32),
2877                    DAG.getConstant(0, DL, MVT::i32),
2878                    DAG.getConstant(2, DL, MVT::i32)};
2879   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2880                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2881 
2882   SDValue TEB = CurrentTEB.getValue(0);
2883   Chain = CurrentTEB.getValue(1);
2884 
2885   // Load the ThreadLocalStoragePointer from the TEB
2886   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2887   SDValue TLSArray =
2888       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2889   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2890 
2891   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2892   // offset into the TLSArray.
2893 
2894   // Load the TLS index from the C runtime
2895   SDValue TLSIndex =
2896       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2897   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2898   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2899 
2900   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2901                               DAG.getConstant(2, DL, MVT::i32));
2902   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2903                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2904                             MachinePointerInfo());
2905 
2906   // Get the offset of the start of the .tls section (section base)
2907   const auto *GA = cast<GlobalAddressSDNode>(Op);
2908   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2909   SDValue Offset = DAG.getLoad(
2910       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2911                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2912       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2913 
2914   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2915 }
2916 
2917 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2918 SDValue
2919 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2920                                                  SelectionDAG &DAG) const {
2921   SDLoc dl(GA);
2922   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2923   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2924   MachineFunction &MF = DAG.getMachineFunction();
2925   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2926   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2927   ARMConstantPoolValue *CPV =
2928     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2929                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2930   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2931   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2932   Argument = DAG.getLoad(
2933       PtrVT, dl, DAG.getEntryNode(), Argument,
2934       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2935   SDValue Chain = Argument.getValue(1);
2936 
2937   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2938   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2939 
2940   // call __tls_get_addr.
2941   ArgListTy Args;
2942   ArgListEntry Entry;
2943   Entry.Node = Argument;
2944   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2945   Args.push_back(Entry);
2946 
2947   // FIXME: is there useful debug info available here?
2948   TargetLowering::CallLoweringInfo CLI(DAG);
2949   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2950       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2951       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2952 
2953   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2954   return CallResult.first;
2955 }
2956 
2957 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2958 // "local exec" model.
2959 SDValue
2960 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2961                                         SelectionDAG &DAG,
2962                                         TLSModel::Model model) const {
2963   const GlobalValue *GV = GA->getGlobal();
2964   SDLoc dl(GA);
2965   SDValue Offset;
2966   SDValue Chain = DAG.getEntryNode();
2967   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2968   // Get the Thread Pointer
2969   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2970 
2971   if (model == TLSModel::InitialExec) {
2972     MachineFunction &MF = DAG.getMachineFunction();
2973     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2974     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2975     // Initial exec model.
2976     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2977     ARMConstantPoolValue *CPV =
2978       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2979                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2980                                       true);
2981     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2982     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2983     Offset = DAG.getLoad(
2984         PtrVT, dl, Chain, Offset,
2985         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2986     Chain = Offset.getValue(1);
2987 
2988     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2989     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2990 
2991     Offset = DAG.getLoad(
2992         PtrVT, dl, Chain, Offset,
2993         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2994   } else {
2995     // local exec model
2996     assert(model == TLSModel::LocalExec);
2997     ARMConstantPoolValue *CPV =
2998       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2999     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3000     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
3001     Offset = DAG.getLoad(
3002         PtrVT, dl, Chain, Offset,
3003         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3004   }
3005 
3006   // The address of the thread local variable is the add of the thread
3007   // pointer with the offset of the variable.
3008   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
3009 }
3010 
3011 SDValue
3012 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
3013   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
3014   if (DAG.getTarget().useEmulatedTLS())
3015     return LowerToTLSEmulatedModel(GA, DAG);
3016 
3017   if (Subtarget->isTargetDarwin())
3018     return LowerGlobalTLSAddressDarwin(Op, DAG);
3019 
3020   if (Subtarget->isTargetWindows())
3021     return LowerGlobalTLSAddressWindows(Op, DAG);
3022 
3023   // TODO: implement the "local dynamic" model
3024   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
3025   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
3026 
3027   switch (model) {
3028     case TLSModel::GeneralDynamic:
3029     case TLSModel::LocalDynamic:
3030       return LowerToTLSGeneralDynamicModel(GA, DAG);
3031     case TLSModel::InitialExec:
3032     case TLSModel::LocalExec:
3033       return LowerToTLSExecModels(GA, DAG, model);
3034   }
3035   llvm_unreachable("bogus TLS model");
3036 }
3037 
3038 /// Return true if all users of V are within function F, looking through
3039 /// ConstantExprs.
3040 static bool allUsersAreInFunction(const Value *V, const Function *F) {
3041   SmallVector<const User*,4> Worklist;
3042   for (auto *U : V->users())
3043     Worklist.push_back(U);
3044   while (!Worklist.empty()) {
3045     auto *U = Worklist.pop_back_val();
3046     if (isa<ConstantExpr>(U)) {
3047       for (auto *UU : U->users())
3048         Worklist.push_back(UU);
3049       continue;
3050     }
3051 
3052     auto *I = dyn_cast<Instruction>(U);
3053     if (!I || I->getParent()->getParent() != F)
3054       return false;
3055   }
3056   return true;
3057 }
3058 
3059 /// Return true if all users of V are within some (any) function, looking through
3060 /// ConstantExprs. In other words, are there any global constant users?
3061 static bool allUsersAreInFunctions(const Value *V) {
3062   SmallVector<const User*,4> Worklist;
3063   for (auto *U : V->users())
3064     Worklist.push_back(U);
3065   while (!Worklist.empty()) {
3066     auto *U = Worklist.pop_back_val();
3067     if (isa<ConstantExpr>(U)) {
3068       for (auto *UU : U->users())
3069         Worklist.push_back(UU);
3070       continue;
3071     }
3072 
3073     if (!isa<Instruction>(U))
3074       return false;
3075   }
3076   return true;
3077 }
3078 
3079 // Return true if T is an integer, float or an array/vector of either.
3080 static bool isSimpleType(Type *T) {
3081   if (T->isIntegerTy() || T->isFloatingPointTy())
3082     return true;
3083   Type *SubT = nullptr;
3084   if (T->isArrayTy())
3085     SubT = T->getArrayElementType();
3086   else if (T->isVectorTy())
3087     SubT = T->getVectorElementType();
3088   else
3089     return false;
3090   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3091 }
3092 
3093 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3094                                      EVT PtrVT, const SDLoc &dl) {
3095   // If we're creating a pool entry for a constant global with unnamed address,
3096   // and the global is small enough, we can emit it inline into the constant pool
3097   // to save ourselves an indirection.
3098   //
3099   // This is a win if the constant is only used in one function (so it doesn't
3100   // need to be duplicated) or duplicating the constant wouldn't increase code
3101   // size (implying the constant is no larger than 4 bytes).
3102   const Function &F = DAG.getMachineFunction().getFunction();
3103 
3104   // We rely on this decision to inline being idemopotent and unrelated to the
3105   // use-site. We know that if we inline a variable at one use site, we'll
3106   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3107   // doesn't know about this optimization, so bail out if it's enabled else
3108   // we could decide to inline here (and thus never emit the GV) but require
3109   // the GV from fast-isel generated code.
3110   if (!EnableConstpoolPromotion ||
3111       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3112       return SDValue();
3113 
3114   auto *GVar = dyn_cast<GlobalVariable>(GV);
3115   if (!GVar || !GVar->hasInitializer() ||
3116       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3117       !GVar->hasLocalLinkage())
3118     return SDValue();
3119 
3120   // Ensure that we don't try and inline any type that contains pointers. If
3121   // we inline a value that contains relocations, we move the relocations from
3122   // .data to .text which is not ideal.
3123   auto *Init = GVar->getInitializer();
3124   if (!isSimpleType(Init->getType()))
3125     return SDValue();
3126 
3127   // The constant islands pass can only really deal with alignment requests
3128   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3129   // any type wanting greater alignment requirements than 4 bytes. We also
3130   // can only promote constants that are multiples of 4 bytes in size or
3131   // are paddable to a multiple of 4. Currently we only try and pad constants
3132   // that are strings for simplicity.
3133   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3134   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3135   unsigned Align = GVar->getAlignment();
3136   unsigned RequiredPadding = 4 - (Size % 4);
3137   bool PaddingPossible =
3138     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3139   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3140       Size == 0)
3141     return SDValue();
3142 
3143   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3144   MachineFunction &MF = DAG.getMachineFunction();
3145   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3146 
3147   // We can't bloat the constant pool too much, else the ConstantIslands pass
3148   // may fail to converge. If we haven't promoted this global yet (it may have
3149   // multiple uses), and promoting it would increase the constant pool size (Sz
3150   // > 4), ensure we have space to do so up to MaxTotal.
3151   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3152     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3153         ConstpoolPromotionMaxTotal)
3154       return SDValue();
3155 
3156   // This is only valid if all users are in a single function OR it has users
3157   // in multiple functions but it no larger than a pointer. We also check if
3158   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3159   // address taken.
3160   if (!allUsersAreInFunction(GVar, &F) &&
3161       !(Size <= 4 && allUsersAreInFunctions(GVar)))
3162     return SDValue();
3163 
3164   // We're going to inline this global. Pad it out if needed.
3165   if (RequiredPadding != 4) {
3166     StringRef S = CDAInit->getAsString();
3167 
3168     SmallVector<uint8_t,16> V(S.size());
3169     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3170     while (RequiredPadding--)
3171       V.push_back(0);
3172     Init = ConstantDataArray::get(*DAG.getContext(), V);
3173   }
3174 
3175   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3176   SDValue CPAddr =
3177     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3178   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3179     AFI->markGlobalAsPromotedToConstantPool(GVar);
3180     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3181                                       PaddedSize - 4);
3182   }
3183   ++NumConstpoolPromoted;
3184   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3185 }
3186 
3187 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3188   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3189     GV = GA->getBaseObject();
3190   return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3191          isa<Function>(GV);
3192 }
3193 
3194 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3195                                               SelectionDAG &DAG) const {
3196   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3197   default: llvm_unreachable("unknown object format");
3198   case Triple::COFF:
3199     return LowerGlobalAddressWindows(Op, DAG);
3200   case Triple::ELF:
3201     return LowerGlobalAddressELF(Op, DAG);
3202   case Triple::MachO:
3203     return LowerGlobalAddressDarwin(Op, DAG);
3204   }
3205 }
3206 
3207 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3208                                                  SelectionDAG &DAG) const {
3209   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3210   SDLoc dl(Op);
3211   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3212   const TargetMachine &TM = getTargetMachine();
3213   bool IsRO = isReadOnly(GV);
3214 
3215   // promoteToConstantPool only if not generating XO text section
3216   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3217     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3218       return V;
3219 
3220   if (isPositionIndependent()) {
3221     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3222     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3223                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3224     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3225     if (UseGOT_PREL)
3226       Result =
3227           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3228                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3229     return Result;
3230   } else if (Subtarget->isROPI() && IsRO) {
3231     // PC-relative.
3232     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3233     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3234     return Result;
3235   } else if (Subtarget->isRWPI() && !IsRO) {
3236     // SB-relative.
3237     SDValue RelAddr;
3238     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3239       ++NumMovwMovt;
3240       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3241       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3242     } else { // use literal pool for address constant
3243       ARMConstantPoolValue *CPV =
3244         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3245       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3246       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3247       RelAddr = DAG.getLoad(
3248           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3249           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3250     }
3251     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3252     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3253     return Result;
3254   }
3255 
3256   // If we have T2 ops, we can materialize the address directly via movt/movw
3257   // pair. This is always cheaper.
3258   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3259     ++NumMovwMovt;
3260     // FIXME: Once remat is capable of dealing with instructions with register
3261     // operands, expand this into two nodes.
3262     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3263                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3264   } else {
3265     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3266     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3267     return DAG.getLoad(
3268         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3269         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3270   }
3271 }
3272 
3273 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3274                                                     SelectionDAG &DAG) const {
3275   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3276          "ROPI/RWPI not currently supported for Darwin");
3277   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3278   SDLoc dl(Op);
3279   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3280 
3281   if (Subtarget->useMovt(DAG.getMachineFunction()))
3282     ++NumMovwMovt;
3283 
3284   // FIXME: Once remat is capable of dealing with instructions with register
3285   // operands, expand this into multiple nodes
3286   unsigned Wrapper =
3287       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3288 
3289   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3290   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3291 
3292   if (Subtarget->isGVIndirectSymbol(GV))
3293     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3294                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3295   return Result;
3296 }
3297 
3298 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3299                                                      SelectionDAG &DAG) const {
3300   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3301   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3302          "Windows on ARM expects to use movw/movt");
3303   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3304          "ROPI/RWPI not currently supported for Windows");
3305 
3306   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3307   const ARMII::TOF TargetFlags =
3308     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3309   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3310   SDValue Result;
3311   SDLoc DL(Op);
3312 
3313   ++NumMovwMovt;
3314 
3315   // FIXME: Once remat is capable of dealing with instructions with register
3316   // operands, expand this into two nodes.
3317   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3318                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3319                                                   TargetFlags));
3320   if (GV->hasDLLImportStorageClass())
3321     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3322                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3323   return Result;
3324 }
3325 
3326 SDValue
3327 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3328   SDLoc dl(Op);
3329   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3330   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3331                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3332                      Op.getOperand(1), Val);
3333 }
3334 
3335 SDValue
3336 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3337   SDLoc dl(Op);
3338   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3339                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3340 }
3341 
3342 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3343                                                       SelectionDAG &DAG) const {
3344   SDLoc dl(Op);
3345   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3346                      Op.getOperand(0));
3347 }
3348 
3349 SDValue
3350 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3351                                           const ARMSubtarget *Subtarget) const {
3352   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3353   SDLoc dl(Op);
3354   switch (IntNo) {
3355   default: return SDValue();    // Don't custom lower most intrinsics.
3356   case Intrinsic::thread_pointer: {
3357     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3358     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3359   }
3360   case Intrinsic::eh_sjlj_lsda: {
3361     MachineFunction &MF = DAG.getMachineFunction();
3362     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3363     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3364     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3365     SDValue CPAddr;
3366     bool IsPositionIndependent = isPositionIndependent();
3367     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3368     ARMConstantPoolValue *CPV =
3369       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3370                                       ARMCP::CPLSDA, PCAdj);
3371     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3372     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3373     SDValue Result = DAG.getLoad(
3374         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3375         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3376 
3377     if (IsPositionIndependent) {
3378       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3379       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3380     }
3381     return Result;
3382   }
3383   case Intrinsic::arm_neon_vabs:
3384     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3385                         Op.getOperand(1));
3386   case Intrinsic::arm_neon_vmulls:
3387   case Intrinsic::arm_neon_vmullu: {
3388     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3389       ? ARMISD::VMULLs : ARMISD::VMULLu;
3390     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3391                        Op.getOperand(1), Op.getOperand(2));
3392   }
3393   case Intrinsic::arm_neon_vminnm:
3394   case Intrinsic::arm_neon_vmaxnm: {
3395     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3396       ? ISD::FMINNUM : ISD::FMAXNUM;
3397     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3398                        Op.getOperand(1), Op.getOperand(2));
3399   }
3400   case Intrinsic::arm_neon_vminu:
3401   case Intrinsic::arm_neon_vmaxu: {
3402     if (Op.getValueType().isFloatingPoint())
3403       return SDValue();
3404     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3405       ? ISD::UMIN : ISD::UMAX;
3406     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3407                          Op.getOperand(1), Op.getOperand(2));
3408   }
3409   case Intrinsic::arm_neon_vmins:
3410   case Intrinsic::arm_neon_vmaxs: {
3411     // v{min,max}s is overloaded between signed integers and floats.
3412     if (!Op.getValueType().isFloatingPoint()) {
3413       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3414         ? ISD::SMIN : ISD::SMAX;
3415       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3416                          Op.getOperand(1), Op.getOperand(2));
3417     }
3418     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3419       ? ISD::FMINNAN : ISD::FMAXNAN;
3420     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3421                        Op.getOperand(1), Op.getOperand(2));
3422   }
3423   case Intrinsic::arm_neon_vtbl1:
3424     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3425                        Op.getOperand(1), Op.getOperand(2));
3426   case Intrinsic::arm_neon_vtbl2:
3427     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3428                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3429   }
3430 }
3431 
3432 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3433                                  const ARMSubtarget *Subtarget) {
3434   SDLoc dl(Op);
3435   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3436   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3437   if (SSID == SyncScope::SingleThread)
3438     return Op;
3439 
3440   if (!Subtarget->hasDataBarrier()) {
3441     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3442     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3443     // here.
3444     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3445            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3446     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3447                        DAG.getConstant(0, dl, MVT::i32));
3448   }
3449 
3450   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3451   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3452   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3453   if (Subtarget->isMClass()) {
3454     // Only a full system barrier exists in the M-class architectures.
3455     Domain = ARM_MB::SY;
3456   } else if (Subtarget->preferISHSTBarriers() &&
3457              Ord == AtomicOrdering::Release) {
3458     // Swift happens to implement ISHST barriers in a way that's compatible with
3459     // Release semantics but weaker than ISH so we'd be fools not to use
3460     // it. Beware: other processors probably don't!
3461     Domain = ARM_MB::ISHST;
3462   }
3463 
3464   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3465                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3466                      DAG.getConstant(Domain, dl, MVT::i32));
3467 }
3468 
3469 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3470                              const ARMSubtarget *Subtarget) {
3471   // ARM pre v5TE and Thumb1 does not have preload instructions.
3472   if (!(Subtarget->isThumb2() ||
3473         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3474     // Just preserve the chain.
3475     return Op.getOperand(0);
3476 
3477   SDLoc dl(Op);
3478   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3479   if (!isRead &&
3480       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3481     // ARMv7 with MP extension has PLDW.
3482     return Op.getOperand(0);
3483 
3484   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3485   if (Subtarget->isThumb()) {
3486     // Invert the bits.
3487     isRead = ~isRead & 1;
3488     isData = ~isData & 1;
3489   }
3490 
3491   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3492                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3493                      DAG.getConstant(isData, dl, MVT::i32));
3494 }
3495 
3496 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3497   MachineFunction &MF = DAG.getMachineFunction();
3498   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3499 
3500   // vastart just stores the address of the VarArgsFrameIndex slot into the
3501   // memory location argument.
3502   SDLoc dl(Op);
3503   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3504   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3505   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3506   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3507                       MachinePointerInfo(SV));
3508 }
3509 
3510 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3511                                                 CCValAssign &NextVA,
3512                                                 SDValue &Root,
3513                                                 SelectionDAG &DAG,
3514                                                 const SDLoc &dl) const {
3515   MachineFunction &MF = DAG.getMachineFunction();
3516   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3517 
3518   const TargetRegisterClass *RC;
3519   if (AFI->isThumb1OnlyFunction())
3520     RC = &ARM::tGPRRegClass;
3521   else
3522     RC = &ARM::GPRRegClass;
3523 
3524   // Transform the arguments stored in physical registers into virtual ones.
3525   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3526   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3527 
3528   SDValue ArgValue2;
3529   if (NextVA.isMemLoc()) {
3530     MachineFrameInfo &MFI = MF.getFrameInfo();
3531     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3532 
3533     // Create load node to retrieve arguments from the stack.
3534     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3535     ArgValue2 = DAG.getLoad(
3536         MVT::i32, dl, Root, FIN,
3537         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3538   } else {
3539     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3540     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3541   }
3542   if (!Subtarget->isLittle())
3543     std::swap (ArgValue, ArgValue2);
3544   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3545 }
3546 
3547 // The remaining GPRs hold either the beginning of variable-argument
3548 // data, or the beginning of an aggregate passed by value (usually
3549 // byval).  Either way, we allocate stack slots adjacent to the data
3550 // provided by our caller, and store the unallocated registers there.
3551 // If this is a variadic function, the va_list pointer will begin with
3552 // these values; otherwise, this reassembles a (byval) structure that
3553 // was split between registers and memory.
3554 // Return: The frame index registers were stored into.
3555 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3556                                       const SDLoc &dl, SDValue &Chain,
3557                                       const Value *OrigArg,
3558                                       unsigned InRegsParamRecordIdx,
3559                                       int ArgOffset, unsigned ArgSize) const {
3560   // Currently, two use-cases possible:
3561   // Case #1. Non-var-args function, and we meet first byval parameter.
3562   //          Setup first unallocated register as first byval register;
3563   //          eat all remained registers
3564   //          (these two actions are performed by HandleByVal method).
3565   //          Then, here, we initialize stack frame with
3566   //          "store-reg" instructions.
3567   // Case #2. Var-args function, that doesn't contain byval parameters.
3568   //          The same: eat all remained unallocated registers,
3569   //          initialize stack frame.
3570 
3571   MachineFunction &MF = DAG.getMachineFunction();
3572   MachineFrameInfo &MFI = MF.getFrameInfo();
3573   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3574   unsigned RBegin, REnd;
3575   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3576     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3577   } else {
3578     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3579     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3580     REnd = ARM::R4;
3581   }
3582 
3583   if (REnd != RBegin)
3584     ArgOffset = -4 * (ARM::R4 - RBegin);
3585 
3586   auto PtrVT = getPointerTy(DAG.getDataLayout());
3587   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3588   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3589 
3590   SmallVector<SDValue, 4> MemOps;
3591   const TargetRegisterClass *RC =
3592       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3593 
3594   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3595     unsigned VReg = MF.addLiveIn(Reg, RC);
3596     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3597     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3598                                  MachinePointerInfo(OrigArg, 4 * i));
3599     MemOps.push_back(Store);
3600     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3601   }
3602 
3603   if (!MemOps.empty())
3604     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3605   return FrameIndex;
3606 }
3607 
3608 // Setup stack frame, the va_list pointer will start from.
3609 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3610                                              const SDLoc &dl, SDValue &Chain,
3611                                              unsigned ArgOffset,
3612                                              unsigned TotalArgRegsSaveSize,
3613                                              bool ForceMutable) const {
3614   MachineFunction &MF = DAG.getMachineFunction();
3615   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3616 
3617   // Try to store any remaining integer argument regs
3618   // to their spots on the stack so that they may be loaded by dereferencing
3619   // the result of va_next.
3620   // If there is no regs to be stored, just point address after last
3621   // argument passed via stack.
3622   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3623                                   CCInfo.getInRegsParamsCount(),
3624                                   CCInfo.getNextStackOffset(), 4);
3625   AFI->setVarArgsFrameIndex(FrameIndex);
3626 }
3627 
3628 SDValue ARMTargetLowering::LowerFormalArguments(
3629     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3630     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3631     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3632   MachineFunction &MF = DAG.getMachineFunction();
3633   MachineFrameInfo &MFI = MF.getFrameInfo();
3634 
3635   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3636 
3637   // Assign locations to all of the incoming arguments.
3638   SmallVector<CCValAssign, 16> ArgLocs;
3639   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3640                  *DAG.getContext());
3641   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3642 
3643   SmallVector<SDValue, 16> ArgValues;
3644   SDValue ArgValue;
3645   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3646   unsigned CurArgIdx = 0;
3647 
3648   // Initially ArgRegsSaveSize is zero.
3649   // Then we increase this value each time we meet byval parameter.
3650   // We also increase this value in case of varargs function.
3651   AFI->setArgRegsSaveSize(0);
3652 
3653   // Calculate the amount of stack space that we need to allocate to store
3654   // byval and variadic arguments that are passed in registers.
3655   // We need to know this before we allocate the first byval or variadic
3656   // argument, as they will be allocated a stack slot below the CFA (Canonical
3657   // Frame Address, the stack pointer at entry to the function).
3658   unsigned ArgRegBegin = ARM::R4;
3659   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3660     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3661       break;
3662 
3663     CCValAssign &VA = ArgLocs[i];
3664     unsigned Index = VA.getValNo();
3665     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3666     if (!Flags.isByVal())
3667       continue;
3668 
3669     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3670     unsigned RBegin, REnd;
3671     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3672     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3673 
3674     CCInfo.nextInRegsParam();
3675   }
3676   CCInfo.rewindByValRegsInfo();
3677 
3678   int lastInsIndex = -1;
3679   if (isVarArg && MFI.hasVAStart()) {
3680     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3681     if (RegIdx != array_lengthof(GPRArgRegs))
3682       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3683   }
3684 
3685   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3686   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3687   auto PtrVT = getPointerTy(DAG.getDataLayout());
3688 
3689   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3690     CCValAssign &VA = ArgLocs[i];
3691     if (Ins[VA.getValNo()].isOrigArg()) {
3692       std::advance(CurOrigArg,
3693                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3694       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3695     }
3696     // Arguments stored in registers.
3697     if (VA.isRegLoc()) {
3698       EVT RegVT = VA.getLocVT();
3699 
3700       if (VA.needsCustom()) {
3701         // f64 and vector types are split up into multiple registers or
3702         // combinations of registers and stack slots.
3703         if (VA.getLocVT() == MVT::v2f64) {
3704           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3705                                                    Chain, DAG, dl);
3706           VA = ArgLocs[++i]; // skip ahead to next loc
3707           SDValue ArgValue2;
3708           if (VA.isMemLoc()) {
3709             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3710             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3711             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3712                                     MachinePointerInfo::getFixedStack(
3713                                         DAG.getMachineFunction(), FI));
3714           } else {
3715             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3716                                              Chain, DAG, dl);
3717           }
3718           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3719           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3720                                  ArgValue, ArgValue1,
3721                                  DAG.getIntPtrConstant(0, dl));
3722           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3723                                  ArgValue, ArgValue2,
3724                                  DAG.getIntPtrConstant(1, dl));
3725         } else
3726           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3727       } else {
3728         const TargetRegisterClass *RC;
3729 
3730 
3731         if (RegVT == MVT::f16)
3732           RC = &ARM::HPRRegClass;
3733         else if (RegVT == MVT::f32)
3734           RC = &ARM::SPRRegClass;
3735         else if (RegVT == MVT::f64 || RegVT == MVT::v4f16)
3736           RC = &ARM::DPRRegClass;
3737         else if (RegVT == MVT::v2f64 || RegVT == MVT::v8f16)
3738           RC = &ARM::QPRRegClass;
3739         else if (RegVT == MVT::i32)
3740           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3741                                            : &ARM::GPRRegClass;
3742         else
3743           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3744 
3745         // Transform the arguments in physical registers into virtual ones.
3746         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3747         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3748       }
3749 
3750       // If this is an 8 or 16-bit value, it is really passed promoted
3751       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3752       // truncate to the right size.
3753       switch (VA.getLocInfo()) {
3754       default: llvm_unreachable("Unknown loc info!");
3755       case CCValAssign::Full: break;
3756       case CCValAssign::BCvt:
3757         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3758         break;
3759       case CCValAssign::SExt:
3760         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3761                                DAG.getValueType(VA.getValVT()));
3762         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3763         break;
3764       case CCValAssign::ZExt:
3765         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3766                                DAG.getValueType(VA.getValVT()));
3767         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3768         break;
3769       }
3770 
3771       InVals.push_back(ArgValue);
3772     } else { // VA.isRegLoc()
3773       // sanity check
3774       assert(VA.isMemLoc());
3775       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3776 
3777       int index = VA.getValNo();
3778 
3779       // Some Ins[] entries become multiple ArgLoc[] entries.
3780       // Process them only once.
3781       if (index != lastInsIndex)
3782         {
3783           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3784           // FIXME: For now, all byval parameter objects are marked mutable.
3785           // This can be changed with more analysis.
3786           // In case of tail call optimization mark all arguments mutable.
3787           // Since they could be overwritten by lowering of arguments in case of
3788           // a tail call.
3789           if (Flags.isByVal()) {
3790             assert(Ins[index].isOrigArg() &&
3791                    "Byval arguments cannot be implicit");
3792             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3793 
3794             int FrameIndex = StoreByValRegs(
3795                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3796                 VA.getLocMemOffset(), Flags.getByValSize());
3797             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3798             CCInfo.nextInRegsParam();
3799           } else {
3800             unsigned FIOffset = VA.getLocMemOffset();
3801             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3802                                            FIOffset, true);
3803 
3804             // Create load nodes to retrieve arguments from the stack.
3805             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3806             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3807                                          MachinePointerInfo::getFixedStack(
3808                                              DAG.getMachineFunction(), FI)));
3809           }
3810           lastInsIndex = index;
3811         }
3812     }
3813   }
3814 
3815   // varargs
3816   if (isVarArg && MFI.hasVAStart())
3817     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3818                          CCInfo.getNextStackOffset(),
3819                          TotalArgRegsSaveSize);
3820 
3821   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3822 
3823   return Chain;
3824 }
3825 
3826 /// isFloatingPointZero - Return true if this is +0.0.
3827 static bool isFloatingPointZero(SDValue Op) {
3828   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3829     return CFP->getValueAPF().isPosZero();
3830   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3831     // Maybe this has already been legalized into the constant pool?
3832     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3833       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3834       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3835         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3836           return CFP->getValueAPF().isPosZero();
3837     }
3838   } else if (Op->getOpcode() == ISD::BITCAST &&
3839              Op->getValueType(0) == MVT::f64) {
3840     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3841     // created by LowerConstantFP().
3842     SDValue BitcastOp = Op->getOperand(0);
3843     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3844         isNullConstant(BitcastOp->getOperand(0)))
3845       return true;
3846   }
3847   return false;
3848 }
3849 
3850 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3851 /// the given operands.
3852 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3853                                      SDValue &ARMcc, SelectionDAG &DAG,
3854                                      const SDLoc &dl) const {
3855   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3856     unsigned C = RHSC->getZExtValue();
3857     if (!isLegalICmpImmediate(C)) {
3858       // Constant does not fit, try adjusting it by one?
3859       switch (CC) {
3860       default: break;
3861       case ISD::SETLT:
3862       case ISD::SETGE:
3863         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3864           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3865           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3866         }
3867         break;
3868       case ISD::SETULT:
3869       case ISD::SETUGE:
3870         if (C != 0 && isLegalICmpImmediate(C-1)) {
3871           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3872           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3873         }
3874         break;
3875       case ISD::SETLE:
3876       case ISD::SETGT:
3877         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3878           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3879           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3880         }
3881         break;
3882       case ISD::SETULE:
3883       case ISD::SETUGT:
3884         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3885           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3886           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3887         }
3888         break;
3889       }
3890     }
3891   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
3892              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
3893     // In ARM and Thumb-2, the compare instructions can shift their second
3894     // operand.
3895     CC = ISD::getSetCCSwappedOperands(CC);
3896     std::swap(LHS, RHS);
3897   }
3898 
3899   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3900   ARMISD::NodeType CompareType;
3901   switch (CondCode) {
3902   default:
3903     CompareType = ARMISD::CMP;
3904     break;
3905   case ARMCC::EQ:
3906   case ARMCC::NE:
3907     // Uses only Z Flag
3908     CompareType = ARMISD::CMPZ;
3909     break;
3910   }
3911   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3912   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3913 }
3914 
3915 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3916 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3917                                      SelectionDAG &DAG, const SDLoc &dl,
3918                                      bool InvalidOnQNaN) const {
3919   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3920   SDValue Cmp;
3921   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3922   if (!isFloatingPointZero(RHS))
3923     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3924   else
3925     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3926   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3927 }
3928 
3929 /// duplicateCmp - Glue values can have only one use, so this function
3930 /// duplicates a comparison node.
3931 SDValue
3932 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3933   unsigned Opc = Cmp.getOpcode();
3934   SDLoc DL(Cmp);
3935   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3936     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3937 
3938   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3939   Cmp = Cmp.getOperand(0);
3940   Opc = Cmp.getOpcode();
3941   if (Opc == ARMISD::CMPFP)
3942     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3943                       Cmp.getOperand(1), Cmp.getOperand(2));
3944   else {
3945     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3946     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3947                       Cmp.getOperand(1));
3948   }
3949   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3950 }
3951 
3952 // This function returns three things: the arithmetic computation itself
3953 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
3954 // comparison and the condition code define the case in which the arithmetic
3955 // computation *does not* overflow.
3956 std::pair<SDValue, SDValue>
3957 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3958                                  SDValue &ARMcc) const {
3959   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3960 
3961   SDValue Value, OverflowCmp;
3962   SDValue LHS = Op.getOperand(0);
3963   SDValue RHS = Op.getOperand(1);
3964   SDLoc dl(Op);
3965 
3966   // FIXME: We are currently always generating CMPs because we don't support
3967   // generating CMN through the backend. This is not as good as the natural
3968   // CMP case because it causes a register dependency and cannot be folded
3969   // later.
3970 
3971   switch (Op.getOpcode()) {
3972   default:
3973     llvm_unreachable("Unknown overflow instruction!");
3974   case ISD::SADDO:
3975     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3976     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3977     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3978     break;
3979   case ISD::UADDO:
3980     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3981     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
3982     // We do not use it in the USUBO case as Value may not be used.
3983     Value = DAG.getNode(ARMISD::ADDC, dl,
3984                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
3985                 .getValue(0);
3986     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3987     break;
3988   case ISD::SSUBO:
3989     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3990     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3991     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3992     break;
3993   case ISD::USUBO:
3994     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3995     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3996     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3997     break;
3998   case ISD::UMULO:
3999     // We generate a UMUL_LOHI and then check if the high word is 0.
4000     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4001     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
4002                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4003                         LHS, RHS);
4004     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4005                               DAG.getConstant(0, dl, MVT::i32));
4006     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4007     break;
4008   case ISD::SMULO:
4009     // We generate a SMUL_LOHI and then check if all the bits of the high word
4010     // are the same as the sign bit of the low word.
4011     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
4012     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
4013                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
4014                         LHS, RHS);
4015     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
4016                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
4017                                           Value.getValue(0),
4018                                           DAG.getConstant(31, dl, MVT::i32)));
4019     Value = Value.getValue(0); // We only want the low 32 bits for the result.
4020     break;
4021   } // switch (...)
4022 
4023   return std::make_pair(Value, OverflowCmp);
4024 }
4025 
4026 SDValue
4027 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
4028   // Let legalize expand this if it isn't a legal type yet.
4029   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4030     return SDValue();
4031 
4032   SDValue Value, OverflowCmp;
4033   SDValue ARMcc;
4034   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
4035   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4036   SDLoc dl(Op);
4037   // We use 0 and 1 as false and true values.
4038   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
4039   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
4040   EVT VT = Op.getValueType();
4041 
4042   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
4043                                  ARMcc, CCR, OverflowCmp);
4044 
4045   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4046   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4047 }
4048 
4049 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4050                                               SelectionDAG &DAG) {
4051   SDLoc DL(BoolCarry);
4052   EVT CarryVT = BoolCarry.getValueType();
4053 
4054   // This converts the boolean value carry into the carry flag by doing
4055   // ARMISD::SUBC Carry, 1
4056   return DAG.getNode(ARMISD::SUBC, DL, DAG.getVTList(CarryVT, MVT::i32),
4057                      BoolCarry, DAG.getConstant(1, DL, CarryVT));
4058 }
4059 
4060 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4061                                               SelectionDAG &DAG) {
4062   SDLoc DL(Flags);
4063 
4064   // Now convert the carry flag into a boolean carry. We do this
4065   // using ARMISD:ADDE 0, 0, Carry
4066   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4067                      DAG.getConstant(0, DL, MVT::i32),
4068                      DAG.getConstant(0, DL, MVT::i32), Flags);
4069 }
4070 
4071 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4072                                              SelectionDAG &DAG) const {
4073   // Let legalize expand this if it isn't a legal type yet.
4074   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
4075     return SDValue();
4076 
4077   SDValue LHS = Op.getOperand(0);
4078   SDValue RHS = Op.getOperand(1);
4079   SDLoc dl(Op);
4080 
4081   EVT VT = Op.getValueType();
4082   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4083   SDValue Value;
4084   SDValue Overflow;
4085   switch (Op.getOpcode()) {
4086   default:
4087     llvm_unreachable("Unknown overflow instruction!");
4088   case ISD::UADDO:
4089     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4090     // Convert the carry flag into a boolean value.
4091     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4092     break;
4093   case ISD::USUBO: {
4094     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4095     // Convert the carry flag into a boolean value.
4096     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4097     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4098     // value. So compute 1 - C.
4099     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4100                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4101     break;
4102   }
4103   }
4104 
4105   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4106 }
4107 
4108 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4109   SDValue Cond = Op.getOperand(0);
4110   SDValue SelectTrue = Op.getOperand(1);
4111   SDValue SelectFalse = Op.getOperand(2);
4112   SDLoc dl(Op);
4113   unsigned Opc = Cond.getOpcode();
4114 
4115   if (Cond.getResNo() == 1 &&
4116       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4117        Opc == ISD::USUBO)) {
4118     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4119       return SDValue();
4120 
4121     SDValue Value, OverflowCmp;
4122     SDValue ARMcc;
4123     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4124     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4125     EVT VT = Op.getValueType();
4126 
4127     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4128                    OverflowCmp, DAG);
4129   }
4130 
4131   // Convert:
4132   //
4133   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4134   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4135   //
4136   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4137     const ConstantSDNode *CMOVTrue =
4138       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4139     const ConstantSDNode *CMOVFalse =
4140       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4141 
4142     if (CMOVTrue && CMOVFalse) {
4143       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4144       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4145 
4146       SDValue True;
4147       SDValue False;
4148       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4149         True = SelectTrue;
4150         False = SelectFalse;
4151       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4152         True = SelectFalse;
4153         False = SelectTrue;
4154       }
4155 
4156       if (True.getNode() && False.getNode()) {
4157         EVT VT = Op.getValueType();
4158         SDValue ARMcc = Cond.getOperand(2);
4159         SDValue CCR = Cond.getOperand(3);
4160         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4161         assert(True.getValueType() == VT);
4162         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4163       }
4164     }
4165   }
4166 
4167   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4168   // undefined bits before doing a full-word comparison with zero.
4169   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4170                      DAG.getConstant(1, dl, Cond.getValueType()));
4171 
4172   return DAG.getSelectCC(dl, Cond,
4173                          DAG.getConstant(0, dl, Cond.getValueType()),
4174                          SelectTrue, SelectFalse, ISD::SETNE);
4175 }
4176 
4177 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4178                                  bool &swpCmpOps, bool &swpVselOps) {
4179   // Start by selecting the GE condition code for opcodes that return true for
4180   // 'equality'
4181   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4182       CC == ISD::SETULE)
4183     CondCode = ARMCC::GE;
4184 
4185   // and GT for opcodes that return false for 'equality'.
4186   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4187            CC == ISD::SETULT)
4188     CondCode = ARMCC::GT;
4189 
4190   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4191   // to swap the compare operands.
4192   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4193       CC == ISD::SETULT)
4194     swpCmpOps = true;
4195 
4196   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4197   // If we have an unordered opcode, we need to swap the operands to the VSEL
4198   // instruction (effectively negating the condition).
4199   //
4200   // This also has the effect of swapping which one of 'less' or 'greater'
4201   // returns true, so we also swap the compare operands. It also switches
4202   // whether we return true for 'equality', so we compensate by picking the
4203   // opposite condition code to our original choice.
4204   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4205       CC == ISD::SETUGT) {
4206     swpCmpOps = !swpCmpOps;
4207     swpVselOps = !swpVselOps;
4208     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4209   }
4210 
4211   // 'ordered' is 'anything but unordered', so use the VS condition code and
4212   // swap the VSEL operands.
4213   if (CC == ISD::SETO) {
4214     CondCode = ARMCC::VS;
4215     swpVselOps = true;
4216   }
4217 
4218   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4219   // code and swap the VSEL operands.
4220   if (CC == ISD::SETUNE) {
4221     CondCode = ARMCC::EQ;
4222     swpVselOps = true;
4223   }
4224 }
4225 
4226 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4227                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4228                                    SDValue Cmp, SelectionDAG &DAG) const {
4229   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4230     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4231                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4232     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4233                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4234 
4235     SDValue TrueLow = TrueVal.getValue(0);
4236     SDValue TrueHigh = TrueVal.getValue(1);
4237     SDValue FalseLow = FalseVal.getValue(0);
4238     SDValue FalseHigh = FalseVal.getValue(1);
4239 
4240     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4241                               ARMcc, CCR, Cmp);
4242     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4243                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4244 
4245     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4246   } else {
4247     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4248                        Cmp);
4249   }
4250 }
4251 
4252 static bool isGTorGE(ISD::CondCode CC) {
4253   return CC == ISD::SETGT || CC == ISD::SETGE;
4254 }
4255 
4256 static bool isLTorLE(ISD::CondCode CC) {
4257   return CC == ISD::SETLT || CC == ISD::SETLE;
4258 }
4259 
4260 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4261 // All of these conditions (and their <= and >= counterparts) will do:
4262 //          x < k ? k : x
4263 //          x > k ? x : k
4264 //          k < x ? x : k
4265 //          k > x ? k : x
4266 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4267                             const SDValue TrueVal, const SDValue FalseVal,
4268                             const ISD::CondCode CC, const SDValue K) {
4269   return (isGTorGE(CC) &&
4270           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4271          (isLTorLE(CC) &&
4272           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4273 }
4274 
4275 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4276 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4277                             const SDValue TrueVal, const SDValue FalseVal,
4278                             const ISD::CondCode CC, const SDValue K) {
4279   return (isGTorGE(CC) &&
4280           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4281          (isLTorLE(CC) &&
4282           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4283 }
4284 
4285 // Check if two chained conditionals could be converted into SSAT or USAT.
4286 //
4287 // SSAT can replace a set of two conditional selectors that bound a number to an
4288 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4289 //
4290 //     x < -k ? -k : (x > k ? k : x)
4291 //     x < -k ? -k : (x < k ? x : k)
4292 //     x > -k ? (x > k ? k : x) : -k
4293 //     x < k ? (x < -k ? -k : x) : k
4294 //     etc.
4295 //
4296 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4297 // a power of 2.
4298 //
4299 // It returns true if the conversion can be done, false otherwise.
4300 // Additionally, the variable is returned in parameter V, the constant in K and
4301 // usat is set to true if the conditional represents an unsigned saturation
4302 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4303                                     uint64_t &K, bool &usat) {
4304   SDValue LHS1 = Op.getOperand(0);
4305   SDValue RHS1 = Op.getOperand(1);
4306   SDValue TrueVal1 = Op.getOperand(2);
4307   SDValue FalseVal1 = Op.getOperand(3);
4308   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4309 
4310   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4311   if (Op2.getOpcode() != ISD::SELECT_CC)
4312     return false;
4313 
4314   SDValue LHS2 = Op2.getOperand(0);
4315   SDValue RHS2 = Op2.getOperand(1);
4316   SDValue TrueVal2 = Op2.getOperand(2);
4317   SDValue FalseVal2 = Op2.getOperand(3);
4318   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4319 
4320   // Find out which are the constants and which are the variables
4321   // in each conditional
4322   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4323                                                         ? &RHS1
4324                                                         : nullptr;
4325   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4326                                                         ? &RHS2
4327                                                         : nullptr;
4328   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4329   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4330   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4331   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4332 
4333   // We must detect cases where the original operations worked with 16- or
4334   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4335   // must work with sign-extended values but the select operations return
4336   // the original non-extended value.
4337   SDValue V2TmpReg = V2Tmp;
4338   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4339     V2TmpReg = V2Tmp->getOperand(0);
4340 
4341   // Check that the registers and the constants have the correct values
4342   // in both conditionals
4343   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4344       V2TmpReg != V2)
4345     return false;
4346 
4347   // Figure out which conditional is saturating the lower/upper bound.
4348   const SDValue *LowerCheckOp =
4349       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4350           ? &Op
4351           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4352                 ? &Op2
4353                 : nullptr;
4354   const SDValue *UpperCheckOp =
4355       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4356           ? &Op
4357           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4358                 ? &Op2
4359                 : nullptr;
4360 
4361   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4362     return false;
4363 
4364   // Check that the constant in the lower-bound check is
4365   // the opposite of the constant in the upper-bound check
4366   // in 1's complement.
4367   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4368   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4369   int64_t PosVal = std::max(Val1, Val2);
4370   int64_t NegVal = std::min(Val1, Val2);
4371 
4372   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4373        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4374       isPowerOf2_64(PosVal + 1)) {
4375 
4376     // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4377     if (Val1 == ~Val2)
4378       usat = false;
4379     else if (NegVal == 0)
4380       usat = true;
4381     else
4382       return false;
4383 
4384     V = V2;
4385     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4386 
4387     return true;
4388   }
4389 
4390   return false;
4391 }
4392 
4393 // Check if a condition of the type x < k ? k : x can be converted into a
4394 // bit operation instead of conditional moves.
4395 // Currently this is allowed given:
4396 // - The conditions and values match up
4397 // - k is 0 or -1 (all ones)
4398 // This function will not check the last condition, thats up to the caller
4399 // It returns true if the transformation can be made, and in such case
4400 // returns x in V, and k in SatK.
4401 static bool isLowerSaturatingConditional(const SDValue &Op, SDValue &V,
4402                                          SDValue &SatK)
4403 {
4404   SDValue LHS = Op.getOperand(0);
4405   SDValue RHS = Op.getOperand(1);
4406   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4407   SDValue TrueVal = Op.getOperand(2);
4408   SDValue FalseVal = Op.getOperand(3);
4409 
4410   SDValue *K = isa<ConstantSDNode>(LHS) ? &LHS : isa<ConstantSDNode>(RHS)
4411                                                ? &RHS
4412                                                : nullptr;
4413 
4414   // No constant operation in comparison, early out
4415   if (!K)
4416     return false;
4417 
4418   SDValue KTmp = isa<ConstantSDNode>(TrueVal) ? TrueVal : FalseVal;
4419   V = (KTmp == TrueVal) ? FalseVal : TrueVal;
4420   SDValue VTmp = (K && *K == LHS) ? RHS : LHS;
4421 
4422   // If the constant on left and right side, or variable on left and right,
4423   // does not match, early out
4424   if (*K != KTmp || V != VTmp)
4425     return false;
4426 
4427   if (isLowerSaturate(LHS, RHS, TrueVal, FalseVal, CC, *K)) {
4428     SatK = *K;
4429     return true;
4430   }
4431 
4432   return false;
4433 }
4434 
4435 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4436   EVT VT = Op.getValueType();
4437   SDLoc dl(Op);
4438 
4439   // Try to convert two saturating conditional selects into a single SSAT
4440   SDValue SatValue;
4441   uint64_t SatConstant;
4442   bool SatUSat;
4443   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4444       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4445     if (SatUSat)
4446       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4447                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4448     else
4449       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4450                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4451   }
4452 
4453   // Try to convert expressions of the form x < k ? k : x (and similar forms)
4454   // into more efficient bit operations, which is possible when k is 0 or -1
4455   // On ARM and Thumb-2 which have flexible operand 2 this will result in
4456   // single instructions. On Thumb the shift and the bit operation will be two
4457   // instructions.
4458   // Only allow this transformation on full-width (32-bit) operations
4459   SDValue LowerSatConstant;
4460   if (VT == MVT::i32 &&
4461       isLowerSaturatingConditional(Op, SatValue, LowerSatConstant)) {
4462     SDValue ShiftV = DAG.getNode(ISD::SRA, dl, VT, SatValue,
4463                                  DAG.getConstant(31, dl, VT));
4464     if (isNullConstant(LowerSatConstant)) {
4465       SDValue NotShiftV = DAG.getNode(ISD::XOR, dl, VT, ShiftV,
4466                                       DAG.getAllOnesConstant(dl, VT));
4467       return DAG.getNode(ISD::AND, dl, VT, SatValue, NotShiftV);
4468     } else if (isAllOnesConstant(LowerSatConstant))
4469       return DAG.getNode(ISD::OR, dl, VT, SatValue, ShiftV);
4470   }
4471 
4472   SDValue LHS = Op.getOperand(0);
4473   SDValue RHS = Op.getOperand(1);
4474   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4475   SDValue TrueVal = Op.getOperand(2);
4476   SDValue FalseVal = Op.getOperand(3);
4477 
4478   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4479     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4480                                                     dl);
4481 
4482     // If softenSetCCOperands only returned one value, we should compare it to
4483     // zero.
4484     if (!RHS.getNode()) {
4485       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4486       CC = ISD::SETNE;
4487     }
4488   }
4489 
4490   if (LHS.getValueType() == MVT::i32) {
4491     // Try to generate VSEL on ARMv8.
4492     // The VSEL instruction can't use all the usual ARM condition
4493     // codes: it only has two bits to select the condition code, so it's
4494     // constrained to use only GE, GT, VS and EQ.
4495     //
4496     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4497     // swap the operands of the previous compare instruction (effectively
4498     // inverting the compare condition, swapping 'less' and 'greater') and
4499     // sometimes need to swap the operands to the VSEL (which inverts the
4500     // condition in the sense of firing whenever the previous condition didn't)
4501     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4502                                     TrueVal.getValueType() == MVT::f64)) {
4503       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4504       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4505           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4506         CC = ISD::getSetCCInverse(CC, true);
4507         std::swap(TrueVal, FalseVal);
4508       }
4509     }
4510 
4511     SDValue ARMcc;
4512     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4513     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4514     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4515   }
4516 
4517   ARMCC::CondCodes CondCode, CondCode2;
4518   bool InvalidOnQNaN;
4519   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4520 
4521   // Try to generate VMAXNM/VMINNM on ARMv8.
4522   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4523                                   TrueVal.getValueType() == MVT::f64)) {
4524     bool swpCmpOps = false;
4525     bool swpVselOps = false;
4526     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4527 
4528     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4529         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4530       if (swpCmpOps)
4531         std::swap(LHS, RHS);
4532       if (swpVselOps)
4533         std::swap(TrueVal, FalseVal);
4534     }
4535   }
4536 
4537   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4538   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4539   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4540   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4541   if (CondCode2 != ARMCC::AL) {
4542     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4543     // FIXME: Needs another CMP because flag can have but one use.
4544     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4545     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4546   }
4547   return Result;
4548 }
4549 
4550 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4551 /// to morph to an integer compare sequence.
4552 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4553                            const ARMSubtarget *Subtarget) {
4554   SDNode *N = Op.getNode();
4555   if (!N->hasOneUse())
4556     // Otherwise it requires moving the value from fp to integer registers.
4557     return false;
4558   if (!N->getNumValues())
4559     return false;
4560   EVT VT = Op.getValueType();
4561   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4562     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4563     // vmrs are very slow, e.g. cortex-a8.
4564     return false;
4565 
4566   if (isFloatingPointZero(Op)) {
4567     SeenZero = true;
4568     return true;
4569   }
4570   return ISD::isNormalLoad(N);
4571 }
4572 
4573 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4574   if (isFloatingPointZero(Op))
4575     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4576 
4577   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4578     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4579                        Ld->getPointerInfo(), Ld->getAlignment(),
4580                        Ld->getMemOperand()->getFlags());
4581 
4582   llvm_unreachable("Unknown VFP cmp argument!");
4583 }
4584 
4585 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4586                            SDValue &RetVal1, SDValue &RetVal2) {
4587   SDLoc dl(Op);
4588 
4589   if (isFloatingPointZero(Op)) {
4590     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4591     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4592     return;
4593   }
4594 
4595   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4596     SDValue Ptr = Ld->getBasePtr();
4597     RetVal1 =
4598         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4599                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4600 
4601     EVT PtrType = Ptr.getValueType();
4602     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4603     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4604                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4605     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4606                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4607                           Ld->getMemOperand()->getFlags());
4608     return;
4609   }
4610 
4611   llvm_unreachable("Unknown VFP cmp argument!");
4612 }
4613 
4614 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4615 /// f32 and even f64 comparisons to integer ones.
4616 SDValue
4617 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4618   SDValue Chain = Op.getOperand(0);
4619   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4620   SDValue LHS = Op.getOperand(2);
4621   SDValue RHS = Op.getOperand(3);
4622   SDValue Dest = Op.getOperand(4);
4623   SDLoc dl(Op);
4624 
4625   bool LHSSeenZero = false;
4626   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4627   bool RHSSeenZero = false;
4628   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4629   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4630     // If unsafe fp math optimization is enabled and there are no other uses of
4631     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4632     // to an integer comparison.
4633     if (CC == ISD::SETOEQ)
4634       CC = ISD::SETEQ;
4635     else if (CC == ISD::SETUNE)
4636       CC = ISD::SETNE;
4637 
4638     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4639     SDValue ARMcc;
4640     if (LHS.getValueType() == MVT::f32) {
4641       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4642                         bitcastf32Toi32(LHS, DAG), Mask);
4643       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4644                         bitcastf32Toi32(RHS, DAG), Mask);
4645       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4646       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4647       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4648                          Chain, Dest, ARMcc, CCR, Cmp);
4649     }
4650 
4651     SDValue LHS1, LHS2;
4652     SDValue RHS1, RHS2;
4653     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4654     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4655     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4656     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4657     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4658     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4659     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4660     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4661     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4662   }
4663 
4664   return SDValue();
4665 }
4666 
4667 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4668   SDValue Chain = Op.getOperand(0);
4669   SDValue Cond = Op.getOperand(1);
4670   SDValue Dest = Op.getOperand(2);
4671   SDLoc dl(Op);
4672 
4673   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4674   // instruction.
4675   unsigned Opc = Cond.getOpcode();
4676   if (Cond.getResNo() == 1 &&
4677       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4678        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4679     // Only lower legal XALUO ops.
4680     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4681       return SDValue();
4682 
4683     // The actual operation with overflow check.
4684     SDValue Value, OverflowCmp;
4685     SDValue ARMcc;
4686     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4687 
4688     // Reverse the condition code.
4689     ARMCC::CondCodes CondCode =
4690         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4691     CondCode = ARMCC::getOppositeCondition(CondCode);
4692     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4693     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4694 
4695     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4696                        OverflowCmp);
4697   }
4698 
4699   return SDValue();
4700 }
4701 
4702 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4703   SDValue Chain = Op.getOperand(0);
4704   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4705   SDValue LHS = Op.getOperand(2);
4706   SDValue RHS = Op.getOperand(3);
4707   SDValue Dest = Op.getOperand(4);
4708   SDLoc dl(Op);
4709 
4710   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4711     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4712                                                     dl);
4713 
4714     // If softenSetCCOperands only returned one value, we should compare it to
4715     // zero.
4716     if (!RHS.getNode()) {
4717       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4718       CC = ISD::SETNE;
4719     }
4720   }
4721 
4722   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4723   // instruction.
4724   unsigned Opc = LHS.getOpcode();
4725   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
4726       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4727        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4728       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4729     // Only lower legal XALUO ops.
4730     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4731       return SDValue();
4732 
4733     // The actual operation with overflow check.
4734     SDValue Value, OverflowCmp;
4735     SDValue ARMcc;
4736     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
4737 
4738     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
4739       // Reverse the condition code.
4740       ARMCC::CondCodes CondCode =
4741           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4742       CondCode = ARMCC::getOppositeCondition(CondCode);
4743       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4744     }
4745     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4746 
4747     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4748                        OverflowCmp);
4749   }
4750 
4751   if (LHS.getValueType() == MVT::i32) {
4752     SDValue ARMcc;
4753     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4754     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4755     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4756                        Chain, Dest, ARMcc, CCR, Cmp);
4757   }
4758 
4759   if (getTargetMachine().Options.UnsafeFPMath &&
4760       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4761        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4762     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4763       return Result;
4764   }
4765 
4766   ARMCC::CondCodes CondCode, CondCode2;
4767   bool InvalidOnQNaN;
4768   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4769 
4770   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4771   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4772   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4773   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4774   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4775   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4776   if (CondCode2 != ARMCC::AL) {
4777     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4778     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4779     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4780   }
4781   return Res;
4782 }
4783 
4784 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4785   SDValue Chain = Op.getOperand(0);
4786   SDValue Table = Op.getOperand(1);
4787   SDValue Index = Op.getOperand(2);
4788   SDLoc dl(Op);
4789 
4790   EVT PTy = getPointerTy(DAG.getDataLayout());
4791   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4792   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4793   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4794   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4795   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
4796   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4797     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4798     // which does another jump to the destination. This also makes it easier
4799     // to translate it to TBB / TBH later (Thumb2 only).
4800     // FIXME: This might not work if the function is extremely large.
4801     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4802                        Addr, Op.getOperand(2), JTI);
4803   }
4804   if (isPositionIndependent() || Subtarget->isROPI()) {
4805     Addr =
4806         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4807                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4808     Chain = Addr.getValue(1);
4809     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
4810     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4811   } else {
4812     Addr =
4813         DAG.getLoad(PTy, dl, Chain, Addr,
4814                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4815     Chain = Addr.getValue(1);
4816     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4817   }
4818 }
4819 
4820 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4821   EVT VT = Op.getValueType();
4822   SDLoc dl(Op);
4823 
4824   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4825     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4826       return Op;
4827     return DAG.UnrollVectorOp(Op.getNode());
4828   }
4829 
4830   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4831          "Invalid type for custom lowering!");
4832   if (VT != MVT::v4i16)
4833     return DAG.UnrollVectorOp(Op.getNode());
4834 
4835   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4836   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4837 }
4838 
4839 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4840   EVT VT = Op.getValueType();
4841   if (VT.isVector())
4842     return LowerVectorFP_TO_INT(Op, DAG);
4843   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4844     RTLIB::Libcall LC;
4845     if (Op.getOpcode() == ISD::FP_TO_SINT)
4846       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4847                               Op.getValueType());
4848     else
4849       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4850                               Op.getValueType());
4851     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4852                        /*isSigned*/ false, SDLoc(Op)).first;
4853   }
4854 
4855   return Op;
4856 }
4857 
4858 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4859   EVT VT = Op.getValueType();
4860   SDLoc dl(Op);
4861 
4862   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4863     if (VT.getVectorElementType() == MVT::f32)
4864       return Op;
4865     return DAG.UnrollVectorOp(Op.getNode());
4866   }
4867 
4868   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4869          "Invalid type for custom lowering!");
4870   if (VT != MVT::v4f32)
4871     return DAG.UnrollVectorOp(Op.getNode());
4872 
4873   unsigned CastOpc;
4874   unsigned Opc;
4875   switch (Op.getOpcode()) {
4876   default: llvm_unreachable("Invalid opcode!");
4877   case ISD::SINT_TO_FP:
4878     CastOpc = ISD::SIGN_EXTEND;
4879     Opc = ISD::SINT_TO_FP;
4880     break;
4881   case ISD::UINT_TO_FP:
4882     CastOpc = ISD::ZERO_EXTEND;
4883     Opc = ISD::UINT_TO_FP;
4884     break;
4885   }
4886 
4887   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4888   return DAG.getNode(Opc, dl, VT, Op);
4889 }
4890 
4891 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4892   EVT VT = Op.getValueType();
4893   if (VT.isVector())
4894     return LowerVectorINT_TO_FP(Op, DAG);
4895   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4896     RTLIB::Libcall LC;
4897     if (Op.getOpcode() == ISD::SINT_TO_FP)
4898       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4899                               Op.getValueType());
4900     else
4901       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4902                               Op.getValueType());
4903     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4904                        /*isSigned*/ false, SDLoc(Op)).first;
4905   }
4906 
4907   return Op;
4908 }
4909 
4910 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4911   // Implement fcopysign with a fabs and a conditional fneg.
4912   SDValue Tmp0 = Op.getOperand(0);
4913   SDValue Tmp1 = Op.getOperand(1);
4914   SDLoc dl(Op);
4915   EVT VT = Op.getValueType();
4916   EVT SrcVT = Tmp1.getValueType();
4917   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4918     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4919   bool UseNEON = !InGPR && Subtarget->hasNEON();
4920 
4921   if (UseNEON) {
4922     // Use VBSL to copy the sign bit.
4923     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4924     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4925                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4926     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4927     if (VT == MVT::f64)
4928       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4929                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4930                          DAG.getConstant(32, dl, MVT::i32));
4931     else /*if (VT == MVT::f32)*/
4932       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4933     if (SrcVT == MVT::f32) {
4934       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4935       if (VT == MVT::f64)
4936         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4937                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4938                            DAG.getConstant(32, dl, MVT::i32));
4939     } else if (VT == MVT::f32)
4940       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4941                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4942                          DAG.getConstant(32, dl, MVT::i32));
4943     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4944     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4945 
4946     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4947                                             dl, MVT::i32);
4948     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4949     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4950                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4951 
4952     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4953                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4954                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4955     if (VT == MVT::f32) {
4956       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4957       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4958                         DAG.getConstant(0, dl, MVT::i32));
4959     } else {
4960       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4961     }
4962 
4963     return Res;
4964   }
4965 
4966   // Bitcast operand 1 to i32.
4967   if (SrcVT == MVT::f64)
4968     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4969                        Tmp1).getValue(1);
4970   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4971 
4972   // Or in the signbit with integer operations.
4973   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4974   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4975   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4976   if (VT == MVT::f32) {
4977     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4978                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4979     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4980                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4981   }
4982 
4983   // f64: Or the high part with signbit and then combine two parts.
4984   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4985                      Tmp0);
4986   SDValue Lo = Tmp0.getValue(0);
4987   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4988   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4989   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4990 }
4991 
4992 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4993   MachineFunction &MF = DAG.getMachineFunction();
4994   MachineFrameInfo &MFI = MF.getFrameInfo();
4995   MFI.setReturnAddressIsTaken(true);
4996 
4997   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4998     return SDValue();
4999 
5000   EVT VT = Op.getValueType();
5001   SDLoc dl(Op);
5002   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5003   if (Depth) {
5004     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
5005     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
5006     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
5007                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
5008                        MachinePointerInfo());
5009   }
5010 
5011   // Return LR, which contains the return address. Mark it an implicit live-in.
5012   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
5013   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
5014 }
5015 
5016 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
5017   const ARMBaseRegisterInfo &ARI =
5018     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
5019   MachineFunction &MF = DAG.getMachineFunction();
5020   MachineFrameInfo &MFI = MF.getFrameInfo();
5021   MFI.setFrameAddressIsTaken(true);
5022 
5023   EVT VT = Op.getValueType();
5024   SDLoc dl(Op);  // FIXME probably not meaningful
5025   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5026   unsigned FrameReg = ARI.getFrameRegister(MF);
5027   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
5028   while (Depth--)
5029     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
5030                             MachinePointerInfo());
5031   return FrameAddr;
5032 }
5033 
5034 // FIXME? Maybe this could be a TableGen attribute on some registers and
5035 // this table could be generated automatically from RegInfo.
5036 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
5037                                               SelectionDAG &DAG) const {
5038   unsigned Reg = StringSwitch<unsigned>(RegName)
5039                        .Case("sp", ARM::SP)
5040                        .Default(0);
5041   if (Reg)
5042     return Reg;
5043   report_fatal_error(Twine("Invalid register name \""
5044                               + StringRef(RegName)  + "\"."));
5045 }
5046 
5047 // Result is 64 bit value so split into two 32 bit values and return as a
5048 // pair of values.
5049 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
5050                                 SelectionDAG &DAG) {
5051   SDLoc DL(N);
5052 
5053   // This function is only supposed to be called for i64 type destination.
5054   assert(N->getValueType(0) == MVT::i64
5055           && "ExpandREAD_REGISTER called for non-i64 type result.");
5056 
5057   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
5058                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
5059                              N->getOperand(0),
5060                              N->getOperand(1));
5061 
5062   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
5063                     Read.getValue(1)));
5064   Results.push_back(Read.getOperand(0));
5065 }
5066 
5067 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
5068 /// When \p DstVT, the destination type of \p BC, is on the vector
5069 /// register bank and the source of bitcast, \p Op, operates on the same bank,
5070 /// it might be possible to combine them, such that everything stays on the
5071 /// vector register bank.
5072 /// \p return The node that would replace \p BT, if the combine
5073 /// is possible.
5074 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
5075                                                 SelectionDAG &DAG) {
5076   SDValue Op = BC->getOperand(0);
5077   EVT DstVT = BC->getValueType(0);
5078 
5079   // The only vector instruction that can produce a scalar (remember,
5080   // since the bitcast was about to be turned into VMOVDRR, the source
5081   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
5082   // Moreover, we can do this combine only if there is one use.
5083   // Finally, if the destination type is not a vector, there is not
5084   // much point on forcing everything on the vector bank.
5085   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5086       !Op.hasOneUse())
5087     return SDValue();
5088 
5089   // If the index is not constant, we will introduce an additional
5090   // multiply that will stick.
5091   // Give up in that case.
5092   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
5093   if (!Index)
5094     return SDValue();
5095   unsigned DstNumElt = DstVT.getVectorNumElements();
5096 
5097   // Compute the new index.
5098   const APInt &APIntIndex = Index->getAPIntValue();
5099   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
5100   NewIndex *= APIntIndex;
5101   // Check if the new constant index fits into i32.
5102   if (NewIndex.getBitWidth() > 32)
5103     return SDValue();
5104 
5105   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5106   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5107   SDLoc dl(Op);
5108   SDValue ExtractSrc = Op.getOperand(0);
5109   EVT VecVT = EVT::getVectorVT(
5110       *DAG.getContext(), DstVT.getScalarType(),
5111       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5112   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5113   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5114                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5115 }
5116 
5117 /// ExpandBITCAST - If the target supports VFP, this function is called to
5118 /// expand a bit convert where either the source or destination type is i64 to
5119 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5120 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5121 /// vectors), since the legalizer won't know what to do with that.
5122 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG,
5123                              const ARMSubtarget *Subtarget) {
5124   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5125   SDLoc dl(N);
5126   SDValue Op = N->getOperand(0);
5127 
5128   // This function is only supposed to be called for i64 types, either as the
5129   // source or destination of the bit convert.
5130   EVT SrcVT = Op.getValueType();
5131   EVT DstVT = N->getValueType(0);
5132   const bool HasFullFP16 = Subtarget->hasFullFP16();
5133 
5134   if (SrcVT == MVT::f32 && DstVT == MVT::i32) {
5135      // FullFP16: half values are passed in S-registers, and we don't
5136      // need any of the bitcast and moves:
5137      //
5138      // t2: f32,ch = CopyFromReg t0, Register:f32 %0
5139      //   t5: i32 = bitcast t2
5140      // t18: f16 = ARMISD::VMOVhr t5
5141      if (Op.getOpcode() != ISD::CopyFromReg ||
5142          Op.getValueType() != MVT::f32)
5143        return SDValue();
5144 
5145      auto Move = N->use_begin();
5146      if (Move->getOpcode() != ARMISD::VMOVhr)
5147        return SDValue();
5148 
5149      SDValue Ops[] = { Op.getOperand(0), Op.getOperand(1) };
5150      SDValue Copy = DAG.getNode(ISD::CopyFromReg, SDLoc(Op), MVT::f16, Ops);
5151      DAG.ReplaceAllUsesWith(*Move, &Copy);
5152      return Copy;
5153   }
5154 
5155   if (SrcVT == MVT::i16 && DstVT == MVT::f16) {
5156     if (!HasFullFP16)
5157       return SDValue();
5158     // SoftFP: read half-precision arguments:
5159     //
5160     // t2: i32,ch = ...
5161     //        t7: i16 = truncate t2 <~~~~ Op
5162     //      t8: f16 = bitcast t7    <~~~~ N
5163     //
5164     if (Op.getOperand(0).getValueType() == MVT::i32)
5165       return DAG.getNode(ARMISD::VMOVhr, SDLoc(Op),
5166                          MVT::f16, Op.getOperand(0));
5167 
5168     return SDValue();
5169   }
5170 
5171   // Half-precision return values
5172   if (SrcVT == MVT::f16 && DstVT == MVT::i16) {
5173     if (!HasFullFP16)
5174       return SDValue();
5175     //
5176     //          t11: f16 = fadd t8, t10
5177     //        t12: i16 = bitcast t11       <~~~ SDNode N
5178     //      t13: i32 = zero_extend t12
5179     //    t16: ch,glue = CopyToReg t0, Register:i32 %r0, t13
5180     //  t17: ch = ARMISD::RET_FLAG t16, Register:i32 %r0, t16:1
5181     //
5182     // transform this into:
5183     //
5184     //    t20: i32 = ARMISD::VMOVrh t11
5185     //  t16: ch,glue = CopyToReg t0, Register:i32 %r0, t20
5186     //
5187     auto ZeroExtend = N->use_begin();
5188     if (N->use_size() != 1 || ZeroExtend->getOpcode() != ISD::ZERO_EXTEND ||
5189         ZeroExtend->getValueType(0) != MVT::i32)
5190       return SDValue();
5191 
5192     auto Copy = ZeroExtend->use_begin();
5193     if (Copy->getOpcode() == ISD::CopyToReg &&
5194         Copy->use_begin()->getOpcode() == ARMISD::RET_FLAG) {
5195       SDValue Cvt = DAG.getNode(ARMISD::VMOVrh, SDLoc(Op), MVT::i32, Op);
5196       DAG.ReplaceAllUsesWith(*ZeroExtend, &Cvt);
5197       return Cvt;
5198     }
5199     return SDValue();
5200   }
5201 
5202   if (!(SrcVT == MVT::i64 || DstVT == MVT::i64))
5203     return SDValue();
5204 
5205   // Turn i64->f64 into VMOVDRR.
5206   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5207     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5208     // if we can combine the bitcast with its source.
5209     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5210       return Val;
5211 
5212     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5213                              DAG.getConstant(0, dl, MVT::i32));
5214     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5215                              DAG.getConstant(1, dl, MVT::i32));
5216     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5217                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5218   }
5219 
5220   // Turn f64->i64 into VMOVRRD.
5221   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5222     SDValue Cvt;
5223     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5224         SrcVT.getVectorNumElements() > 1)
5225       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5226                         DAG.getVTList(MVT::i32, MVT::i32),
5227                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5228     else
5229       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5230                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5231     // Merge the pieces into a single i64 value.
5232     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5233   }
5234 
5235   return SDValue();
5236 }
5237 
5238 /// getZeroVector - Returns a vector of specified type with all zero elements.
5239 /// Zero vectors are used to represent vector negation and in those cases
5240 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
5241 /// not support i64 elements, so sometimes the zero vectors will need to be
5242 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
5243 /// zero vector.
5244 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5245   assert(VT.isVector() && "Expected a vector type");
5246   // The canonical modified immediate encoding of a zero vector is....0!
5247   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5248   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5249   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5250   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5251 }
5252 
5253 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5254 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5255 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5256                                                 SelectionDAG &DAG) const {
5257   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5258   EVT VT = Op.getValueType();
5259   unsigned VTBits = VT.getSizeInBits();
5260   SDLoc dl(Op);
5261   SDValue ShOpLo = Op.getOperand(0);
5262   SDValue ShOpHi = Op.getOperand(1);
5263   SDValue ShAmt  = Op.getOperand(2);
5264   SDValue ARMcc;
5265   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5266   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5267 
5268   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5269 
5270   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5271                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5272   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5273   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5274                                    DAG.getConstant(VTBits, dl, MVT::i32));
5275   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5276   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5277   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5278   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5279                             ISD::SETGE, ARMcc, DAG, dl);
5280   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5281                            ARMcc, CCR, CmpLo);
5282 
5283   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5284   SDValue HiBigShift = Opc == ISD::SRA
5285                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5286                                          DAG.getConstant(VTBits - 1, dl, VT))
5287                            : DAG.getConstant(0, dl, VT);
5288   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5289                             ISD::SETGE, ARMcc, DAG, dl);
5290   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5291                            ARMcc, CCR, CmpHi);
5292 
5293   SDValue Ops[2] = { Lo, Hi };
5294   return DAG.getMergeValues(Ops, dl);
5295 }
5296 
5297 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5298 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5299 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5300                                                SelectionDAG &DAG) const {
5301   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5302   EVT VT = Op.getValueType();
5303   unsigned VTBits = VT.getSizeInBits();
5304   SDLoc dl(Op);
5305   SDValue ShOpLo = Op.getOperand(0);
5306   SDValue ShOpHi = Op.getOperand(1);
5307   SDValue ShAmt  = Op.getOperand(2);
5308   SDValue ARMcc;
5309   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5310 
5311   assert(Op.getOpcode() == ISD::SHL_PARTS);
5312   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5313                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5314   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5315   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5316   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5317 
5318   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5319                                    DAG.getConstant(VTBits, dl, MVT::i32));
5320   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5321   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5322                             ISD::SETGE, ARMcc, DAG, dl);
5323   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5324                            ARMcc, CCR, CmpHi);
5325 
5326   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5327                           ISD::SETGE, ARMcc, DAG, dl);
5328   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5329   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5330                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5331 
5332   SDValue Ops[2] = { Lo, Hi };
5333   return DAG.getMergeValues(Ops, dl);
5334 }
5335 
5336 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5337                                             SelectionDAG &DAG) const {
5338   // The rounding mode is in bits 23:22 of the FPSCR.
5339   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5340   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5341   // so that the shift + and get folded into a bitfield extract.
5342   SDLoc dl(Op);
5343   SDValue Ops[] = { DAG.getEntryNode(),
5344                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5345 
5346   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5347   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5348                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5349   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5350                               DAG.getConstant(22, dl, MVT::i32));
5351   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5352                      DAG.getConstant(3, dl, MVT::i32));
5353 }
5354 
5355 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5356                          const ARMSubtarget *ST) {
5357   SDLoc dl(N);
5358   EVT VT = N->getValueType(0);
5359   if (VT.isVector()) {
5360     assert(ST->hasNEON());
5361 
5362     // Compute the least significant set bit: LSB = X & -X
5363     SDValue X = N->getOperand(0);
5364     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5365     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5366 
5367     EVT ElemTy = VT.getVectorElementType();
5368 
5369     if (ElemTy == MVT::i8) {
5370       // Compute with: cttz(x) = ctpop(lsb - 1)
5371       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5372                                 DAG.getTargetConstant(1, dl, ElemTy));
5373       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5374       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5375     }
5376 
5377     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5378         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5379       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5380       unsigned NumBits = ElemTy.getSizeInBits();
5381       SDValue WidthMinus1 =
5382           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5383                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5384       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5385       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5386     }
5387 
5388     // Compute with: cttz(x) = ctpop(lsb - 1)
5389 
5390     // Since we can only compute the number of bits in a byte with vcnt.8, we
5391     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
5392     // and i64.
5393 
5394     // Compute LSB - 1.
5395     SDValue Bits;
5396     if (ElemTy == MVT::i64) {
5397       // Load constant 0xffff'ffff'ffff'ffff to register.
5398       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5399                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5400       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5401     } else {
5402       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5403                                 DAG.getTargetConstant(1, dl, ElemTy));
5404       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5405     }
5406 
5407     // Count #bits with vcnt.8.
5408     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5409     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5410     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5411 
5412     // Gather the #bits with vpaddl (pairwise add.)
5413     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5414     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5415         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5416         Cnt8);
5417     if (ElemTy == MVT::i16)
5418       return Cnt16;
5419 
5420     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5421     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5422         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5423         Cnt16);
5424     if (ElemTy == MVT::i32)
5425       return Cnt32;
5426 
5427     assert(ElemTy == MVT::i64);
5428     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5429         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5430         Cnt32);
5431     return Cnt64;
5432   }
5433 
5434   if (!ST->hasV6T2Ops())
5435     return SDValue();
5436 
5437   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5438   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5439 }
5440 
5441 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5442 /// for each 16-bit element from operand, repeated.  The basic idea is to
5443 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5444 ///
5445 /// Trace for v4i16:
5446 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
5447 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5448 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5449 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5450 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
5451 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
5452 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5453 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
5454 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5455   EVT VT = N->getValueType(0);
5456   SDLoc DL(N);
5457 
5458   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5459   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5460   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5461   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5462   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5463   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5464 }
5465 
5466 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5467 /// bit-count for each 16-bit element from the operand.  We need slightly
5468 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5469 /// 64/128-bit registers.
5470 ///
5471 /// Trace for v4i16:
5472 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
5473 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5474 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
5475 /// v4i16:Extracted = [k0    k1    k2    k3    ]
5476 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5477   EVT VT = N->getValueType(0);
5478   SDLoc DL(N);
5479 
5480   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5481   if (VT.is64BitVector()) {
5482     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5483     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5484                        DAG.getIntPtrConstant(0, DL));
5485   } else {
5486     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5487                                     BitCounts, DAG.getIntPtrConstant(0, DL));
5488     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5489   }
5490 }
5491 
5492 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5493 /// bit-count for each 32-bit element from the operand.  The idea here is
5494 /// to split the vector into 16-bit elements, leverage the 16-bit count
5495 /// routine, and then combine the results.
5496 ///
5497 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5498 /// input    = [v0    v1    ] (vi: 32-bit elements)
5499 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5500 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5501 /// vrev: N0 = [k1 k0 k3 k2 ]
5502 ///            [k0 k1 k2 k3 ]
5503 ///       N1 =+[k1 k0 k3 k2 ]
5504 ///            [k0 k2 k1 k3 ]
5505 ///       N2 =+[k1 k3 k0 k2 ]
5506 ///            [k0    k2    k1    k3    ]
5507 /// Extended =+[k1    k3    k0    k2    ]
5508 ///            [k0    k2    ]
5509 /// Extracted=+[k1    k3    ]
5510 ///
5511 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5512   EVT VT = N->getValueType(0);
5513   SDLoc DL(N);
5514 
5515   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5516 
5517   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5518   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5519   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5520   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5521   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5522 
5523   if (VT.is64BitVector()) {
5524     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5525     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5526                        DAG.getIntPtrConstant(0, DL));
5527   } else {
5528     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5529                                     DAG.getIntPtrConstant(0, DL));
5530     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5531   }
5532 }
5533 
5534 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5535                           const ARMSubtarget *ST) {
5536   EVT VT = N->getValueType(0);
5537 
5538   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5539   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5540           VT == MVT::v4i16 || VT == MVT::v8i16) &&
5541          "Unexpected type for custom ctpop lowering");
5542 
5543   if (VT.getVectorElementType() == MVT::i32)
5544     return lowerCTPOP32BitElements(N, DAG);
5545   else
5546     return lowerCTPOP16BitElements(N, DAG);
5547 }
5548 
5549 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5550                           const ARMSubtarget *ST) {
5551   EVT VT = N->getValueType(0);
5552   SDLoc dl(N);
5553 
5554   if (!VT.isVector())
5555     return SDValue();
5556 
5557   // Lower vector shifts on NEON to use VSHL.
5558   assert(ST->hasNEON() && "unexpected vector shift");
5559 
5560   // Left shifts translate directly to the vshiftu intrinsic.
5561   if (N->getOpcode() == ISD::SHL)
5562     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5563                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5564                                        MVT::i32),
5565                        N->getOperand(0), N->getOperand(1));
5566 
5567   assert((N->getOpcode() == ISD::SRA ||
5568           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5569 
5570   // NEON uses the same intrinsics for both left and right shifts.  For
5571   // right shifts, the shift amounts are negative, so negate the vector of
5572   // shift amounts.
5573   EVT ShiftVT = N->getOperand(1).getValueType();
5574   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5575                                      getZeroVector(ShiftVT, DAG, dl),
5576                                      N->getOperand(1));
5577   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5578                              Intrinsic::arm_neon_vshifts :
5579                              Intrinsic::arm_neon_vshiftu);
5580   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5581                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5582                      N->getOperand(0), NegatedCount);
5583 }
5584 
5585 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5586                                 const ARMSubtarget *ST) {
5587   EVT VT = N->getValueType(0);
5588   SDLoc dl(N);
5589 
5590   // We can get here for a node like i32 = ISD::SHL i32, i64
5591   if (VT != MVT::i64)
5592     return SDValue();
5593 
5594   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5595          "Unknown shift to lower!");
5596 
5597   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5598   if (!isOneConstant(N->getOperand(1)))
5599     return SDValue();
5600 
5601   // If we are in thumb mode, we don't have RRX.
5602   if (ST->isThumb1Only()) return SDValue();
5603 
5604   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5605   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5606                            DAG.getConstant(0, dl, MVT::i32));
5607   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5608                            DAG.getConstant(1, dl, MVT::i32));
5609 
5610   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5611   // captures the result into a carry flag.
5612   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5613   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5614 
5615   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5616   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5617 
5618   // Merge the pieces into a single i64 value.
5619  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5620 }
5621 
5622 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5623   SDValue TmpOp0, TmpOp1;
5624   bool Invert = false;
5625   bool Swap = false;
5626   unsigned Opc = 0;
5627 
5628   SDValue Op0 = Op.getOperand(0);
5629   SDValue Op1 = Op.getOperand(1);
5630   SDValue CC = Op.getOperand(2);
5631   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5632   EVT VT = Op.getValueType();
5633   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5634   SDLoc dl(Op);
5635 
5636   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5637       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5638     // Special-case integer 64-bit equality comparisons. They aren't legal,
5639     // but they can be lowered with a few vector instructions.
5640     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5641     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5642     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5643     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5644     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5645                               DAG.getCondCode(ISD::SETEQ));
5646     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5647     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5648     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5649     if (SetCCOpcode == ISD::SETNE)
5650       Merged = DAG.getNOT(dl, Merged, CmpVT);
5651     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5652     return Merged;
5653   }
5654 
5655   if (CmpVT.getVectorElementType() == MVT::i64)
5656     // 64-bit comparisons are not legal in general.
5657     return SDValue();
5658 
5659   if (Op1.getValueType().isFloatingPoint()) {
5660     switch (SetCCOpcode) {
5661     default: llvm_unreachable("Illegal FP comparison");
5662     case ISD::SETUNE:
5663     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5664     case ISD::SETOEQ:
5665     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5666     case ISD::SETOLT:
5667     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5668     case ISD::SETOGT:
5669     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5670     case ISD::SETOLE:
5671     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5672     case ISD::SETOGE:
5673     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5674     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5675     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5676     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5677     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5678     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5679     case ISD::SETONE:
5680       // Expand this to (OLT | OGT).
5681       TmpOp0 = Op0;
5682       TmpOp1 = Op1;
5683       Opc = ISD::OR;
5684       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5685       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5686       break;
5687     case ISD::SETUO:
5688       Invert = true;
5689       LLVM_FALLTHROUGH;
5690     case ISD::SETO:
5691       // Expand this to (OLT | OGE).
5692       TmpOp0 = Op0;
5693       TmpOp1 = Op1;
5694       Opc = ISD::OR;
5695       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5696       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5697       break;
5698     }
5699   } else {
5700     // Integer comparisons.
5701     switch (SetCCOpcode) {
5702     default: llvm_unreachable("Illegal integer comparison");
5703     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5704     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5705     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
5706     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5707     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5708     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5709     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5710     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5711     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5712     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5713     }
5714 
5715     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5716     if (Opc == ARMISD::VCEQ) {
5717       SDValue AndOp;
5718       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5719         AndOp = Op0;
5720       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5721         AndOp = Op1;
5722 
5723       // Ignore bitconvert.
5724       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5725         AndOp = AndOp.getOperand(0);
5726 
5727       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5728         Opc = ARMISD::VTST;
5729         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5730         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5731         Invert = !Invert;
5732       }
5733     }
5734   }
5735 
5736   if (Swap)
5737     std::swap(Op0, Op1);
5738 
5739   // If one of the operands is a constant vector zero, attempt to fold the
5740   // comparison to a specialized compare-against-zero form.
5741   SDValue SingleOp;
5742   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5743     SingleOp = Op0;
5744   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5745     if (Opc == ARMISD::VCGE)
5746       Opc = ARMISD::VCLEZ;
5747     else if (Opc == ARMISD::VCGT)
5748       Opc = ARMISD::VCLTZ;
5749     SingleOp = Op1;
5750   }
5751 
5752   SDValue Result;
5753   if (SingleOp.getNode()) {
5754     switch (Opc) {
5755     case ARMISD::VCEQ:
5756       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5757     case ARMISD::VCGE:
5758       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5759     case ARMISD::VCLEZ:
5760       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5761     case ARMISD::VCGT:
5762       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5763     case ARMISD::VCLTZ:
5764       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5765     default:
5766       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5767     }
5768   } else {
5769      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5770   }
5771 
5772   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5773 
5774   if (Invert)
5775     Result = DAG.getNOT(dl, Result, VT);
5776 
5777   return Result;
5778 }
5779 
5780 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5781   SDValue LHS = Op.getOperand(0);
5782   SDValue RHS = Op.getOperand(1);
5783   SDValue Carry = Op.getOperand(2);
5784   SDValue Cond = Op.getOperand(3);
5785   SDLoc DL(Op);
5786 
5787   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5788 
5789   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5790   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5791   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5792 
5793   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5794   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5795   SDValue ARMcc = DAG.getConstant(
5796       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5797   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5798   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5799                                    Cmp.getValue(1), SDValue());
5800   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5801                      CCR, Chain.getValue(1));
5802 }
5803 
5804 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5805 /// valid vector constant for a NEON instruction with a "modified immediate"
5806 /// operand (e.g., VMOV).  If so, return the encoded value.
5807 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5808                                  unsigned SplatBitSize, SelectionDAG &DAG,
5809                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5810                                  NEONModImmType type) {
5811   unsigned OpCmode, Imm;
5812 
5813   // SplatBitSize is set to the smallest size that splats the vector, so a
5814   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5815   // immediate instructions others than VMOV do not support the 8-bit encoding
5816   // of a zero vector, and the default encoding of zero is supposed to be the
5817   // 32-bit version.
5818   if (SplatBits == 0)
5819     SplatBitSize = 32;
5820 
5821   switch (SplatBitSize) {
5822   case 8:
5823     if (type != VMOVModImm)
5824       return SDValue();
5825     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5826     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5827     OpCmode = 0xe;
5828     Imm = SplatBits;
5829     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5830     break;
5831 
5832   case 16:
5833     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5834     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5835     if ((SplatBits & ~0xff) == 0) {
5836       // Value = 0x00nn: Op=x, Cmode=100x.
5837       OpCmode = 0x8;
5838       Imm = SplatBits;
5839       break;
5840     }
5841     if ((SplatBits & ~0xff00) == 0) {
5842       // Value = 0xnn00: Op=x, Cmode=101x.
5843       OpCmode = 0xa;
5844       Imm = SplatBits >> 8;
5845       break;
5846     }
5847     return SDValue();
5848 
5849   case 32:
5850     // NEON's 32-bit VMOV supports splat values where:
5851     // * only one byte is nonzero, or
5852     // * the least significant byte is 0xff and the second byte is nonzero, or
5853     // * the least significant 2 bytes are 0xff and the third is nonzero.
5854     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5855     if ((SplatBits & ~0xff) == 0) {
5856       // Value = 0x000000nn: Op=x, Cmode=000x.
5857       OpCmode = 0;
5858       Imm = SplatBits;
5859       break;
5860     }
5861     if ((SplatBits & ~0xff00) == 0) {
5862       // Value = 0x0000nn00: Op=x, Cmode=001x.
5863       OpCmode = 0x2;
5864       Imm = SplatBits >> 8;
5865       break;
5866     }
5867     if ((SplatBits & ~0xff0000) == 0) {
5868       // Value = 0x00nn0000: Op=x, Cmode=010x.
5869       OpCmode = 0x4;
5870       Imm = SplatBits >> 16;
5871       break;
5872     }
5873     if ((SplatBits & ~0xff000000) == 0) {
5874       // Value = 0xnn000000: Op=x, Cmode=011x.
5875       OpCmode = 0x6;
5876       Imm = SplatBits >> 24;
5877       break;
5878     }
5879 
5880     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5881     if (type == OtherModImm) return SDValue();
5882 
5883     if ((SplatBits & ~0xffff) == 0 &&
5884         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5885       // Value = 0x0000nnff: Op=x, Cmode=1100.
5886       OpCmode = 0xc;
5887       Imm = SplatBits >> 8;
5888       break;
5889     }
5890 
5891     if ((SplatBits & ~0xffffff) == 0 &&
5892         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5893       // Value = 0x00nnffff: Op=x, Cmode=1101.
5894       OpCmode = 0xd;
5895       Imm = SplatBits >> 16;
5896       break;
5897     }
5898 
5899     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5900     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5901     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5902     // and fall through here to test for a valid 64-bit splat.  But, then the
5903     // caller would also need to check and handle the change in size.
5904     return SDValue();
5905 
5906   case 64: {
5907     if (type != VMOVModImm)
5908       return SDValue();
5909     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5910     uint64_t BitMask = 0xff;
5911     uint64_t Val = 0;
5912     unsigned ImmMask = 1;
5913     Imm = 0;
5914     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5915       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5916         Val |= BitMask;
5917         Imm |= ImmMask;
5918       } else if ((SplatBits & BitMask) != 0) {
5919         return SDValue();
5920       }
5921       BitMask <<= 8;
5922       ImmMask <<= 1;
5923     }
5924 
5925     if (DAG.getDataLayout().isBigEndian())
5926       // swap higher and lower 32 bit word
5927       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5928 
5929     // Op=1, Cmode=1110.
5930     OpCmode = 0x1e;
5931     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5932     break;
5933   }
5934 
5935   default:
5936     llvm_unreachable("unexpected size for isNEONModifiedImm");
5937   }
5938 
5939   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5940   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5941 }
5942 
5943 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5944                                            const ARMSubtarget *ST) const {
5945   bool IsDouble = Op.getValueType() == MVT::f64;
5946   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5947   const APFloat &FPVal = CFP->getValueAPF();
5948 
5949   // Prevent floating-point constants from using literal loads
5950   // when execute-only is enabled.
5951   if (ST->genExecuteOnly()) {
5952     APInt INTVal = FPVal.bitcastToAPInt();
5953     SDLoc DL(CFP);
5954     if (IsDouble) {
5955       SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5956       SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5957       if (!ST->isLittle())
5958         std::swap(Lo, Hi);
5959       return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5960     } else {
5961       return DAG.getConstant(INTVal, DL, MVT::i32);
5962     }
5963   }
5964 
5965   if (!ST->hasVFP3())
5966     return SDValue();
5967 
5968   // Use the default (constant pool) lowering for double constants when we have
5969   // an SP-only FPU
5970   if (IsDouble && Subtarget->isFPOnlySP())
5971     return SDValue();
5972 
5973   // Try splatting with a VMOV.f32...
5974   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5975 
5976   if (ImmVal != -1) {
5977     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5978       // We have code in place to select a valid ConstantFP already, no need to
5979       // do any mangling.
5980       return Op;
5981     }
5982 
5983     // It's a float and we are trying to use NEON operations where
5984     // possible. Lower it to a splat followed by an extract.
5985     SDLoc DL(Op);
5986     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5987     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5988                                       NewVal);
5989     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5990                        DAG.getConstant(0, DL, MVT::i32));
5991   }
5992 
5993   // The rest of our options are NEON only, make sure that's allowed before
5994   // proceeding..
5995   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5996     return SDValue();
5997 
5998   EVT VMovVT;
5999   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
6000 
6001   // It wouldn't really be worth bothering for doubles except for one very
6002   // important value, which does happen to match: 0.0. So make sure we don't do
6003   // anything stupid.
6004   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
6005     return SDValue();
6006 
6007   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
6008   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
6009                                      VMovVT, false, VMOVModImm);
6010   if (NewVal != SDValue()) {
6011     SDLoc DL(Op);
6012     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
6013                                       NewVal);
6014     if (IsDouble)
6015       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6016 
6017     // It's a float: cast and extract a vector element.
6018     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6019                                        VecConstant);
6020     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6021                        DAG.getConstant(0, DL, MVT::i32));
6022   }
6023 
6024   // Finally, try a VMVN.i32
6025   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
6026                              false, VMVNModImm);
6027   if (NewVal != SDValue()) {
6028     SDLoc DL(Op);
6029     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
6030 
6031     if (IsDouble)
6032       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
6033 
6034     // It's a float: cast and extract a vector element.
6035     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
6036                                        VecConstant);
6037     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
6038                        DAG.getConstant(0, DL, MVT::i32));
6039   }
6040 
6041   return SDValue();
6042 }
6043 
6044 // check if an VEXT instruction can handle the shuffle mask when the
6045 // vector sources of the shuffle are the same.
6046 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
6047   unsigned NumElts = VT.getVectorNumElements();
6048 
6049   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6050   if (M[0] < 0)
6051     return false;
6052 
6053   Imm = M[0];
6054 
6055   // If this is a VEXT shuffle, the immediate value is the index of the first
6056   // element.  The other shuffle indices must be the successive elements after
6057   // the first one.
6058   unsigned ExpectedElt = Imm;
6059   for (unsigned i = 1; i < NumElts; ++i) {
6060     // Increment the expected index.  If it wraps around, just follow it
6061     // back to index zero and keep going.
6062     ++ExpectedElt;
6063     if (ExpectedElt == NumElts)
6064       ExpectedElt = 0;
6065 
6066     if (M[i] < 0) continue; // ignore UNDEF indices
6067     if (ExpectedElt != static_cast<unsigned>(M[i]))
6068       return false;
6069   }
6070 
6071   return true;
6072 }
6073 
6074 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
6075                        bool &ReverseVEXT, unsigned &Imm) {
6076   unsigned NumElts = VT.getVectorNumElements();
6077   ReverseVEXT = false;
6078 
6079   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
6080   if (M[0] < 0)
6081     return false;
6082 
6083   Imm = M[0];
6084 
6085   // If this is a VEXT shuffle, the immediate value is the index of the first
6086   // element.  The other shuffle indices must be the successive elements after
6087   // the first one.
6088   unsigned ExpectedElt = Imm;
6089   for (unsigned i = 1; i < NumElts; ++i) {
6090     // Increment the expected index.  If it wraps around, it may still be
6091     // a VEXT but the source vectors must be swapped.
6092     ExpectedElt += 1;
6093     if (ExpectedElt == NumElts * 2) {
6094       ExpectedElt = 0;
6095       ReverseVEXT = true;
6096     }
6097 
6098     if (M[i] < 0) continue; // ignore UNDEF indices
6099     if (ExpectedElt != static_cast<unsigned>(M[i]))
6100       return false;
6101   }
6102 
6103   // Adjust the index value if the source operands will be swapped.
6104   if (ReverseVEXT)
6105     Imm -= NumElts;
6106 
6107   return true;
6108 }
6109 
6110 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
6111 /// instruction with the specified blocksize.  (The order of the elements
6112 /// within each block of the vector is reversed.)
6113 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
6114   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
6115          "Only possible block sizes for VREV are: 16, 32, 64");
6116 
6117   unsigned EltSz = VT.getScalarSizeInBits();
6118   if (EltSz == 64)
6119     return false;
6120 
6121   unsigned NumElts = VT.getVectorNumElements();
6122   unsigned BlockElts = M[0] + 1;
6123   // If the first shuffle index is UNDEF, be optimistic.
6124   if (M[0] < 0)
6125     BlockElts = BlockSize / EltSz;
6126 
6127   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
6128     return false;
6129 
6130   for (unsigned i = 0; i < NumElts; ++i) {
6131     if (M[i] < 0) continue; // ignore UNDEF indices
6132     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
6133       return false;
6134   }
6135 
6136   return true;
6137 }
6138 
6139 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
6140   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
6141   // range, then 0 is placed into the resulting vector. So pretty much any mask
6142   // of 8 elements can work here.
6143   return VT == MVT::v8i8 && M.size() == 8;
6144 }
6145 
6146 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
6147                                unsigned Index) {
6148   if (Mask.size() == Elements * 2)
6149     return Index / Elements;
6150   return Mask[Index] == 0 ? 0 : 1;
6151 }
6152 
6153 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
6154 // checking that pairs of elements in the shuffle mask represent the same index
6155 // in each vector, incrementing the expected index by 2 at each step.
6156 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
6157 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
6158 //  v2={e,f,g,h}
6159 // WhichResult gives the offset for each element in the mask based on which
6160 // of the two results it belongs to.
6161 //
6162 // The transpose can be represented either as:
6163 // result1 = shufflevector v1, v2, result1_shuffle_mask
6164 // result2 = shufflevector v1, v2, result2_shuffle_mask
6165 // where v1/v2 and the shuffle masks have the same number of elements
6166 // (here WhichResult (see below) indicates which result is being checked)
6167 //
6168 // or as:
6169 // results = shufflevector v1, v2, shuffle_mask
6170 // where both results are returned in one vector and the shuffle mask has twice
6171 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
6172 // want to check the low half and high half of the shuffle mask as if it were
6173 // the other case
6174 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6175   unsigned EltSz = VT.getScalarSizeInBits();
6176   if (EltSz == 64)
6177     return false;
6178 
6179   unsigned NumElts = VT.getVectorNumElements();
6180   if (M.size() != NumElts && M.size() != NumElts*2)
6181     return false;
6182 
6183   // If the mask is twice as long as the input vector then we need to check the
6184   // upper and lower parts of the mask with a matching value for WhichResult
6185   // FIXME: A mask with only even values will be rejected in case the first
6186   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6187   // M[0] is used to determine WhichResult
6188   for (unsigned i = 0; i < M.size(); i += NumElts) {
6189     WhichResult = SelectPairHalf(NumElts, M, i);
6190     for (unsigned j = 0; j < NumElts; j += 2) {
6191       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6192           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6193         return false;
6194     }
6195   }
6196 
6197   if (M.size() == NumElts*2)
6198     WhichResult = 0;
6199 
6200   return true;
6201 }
6202 
6203 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6204 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6205 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6206 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6207   unsigned EltSz = VT.getScalarSizeInBits();
6208   if (EltSz == 64)
6209     return false;
6210 
6211   unsigned NumElts = VT.getVectorNumElements();
6212   if (M.size() != NumElts && M.size() != NumElts*2)
6213     return false;
6214 
6215   for (unsigned i = 0; i < M.size(); i += NumElts) {
6216     WhichResult = SelectPairHalf(NumElts, M, i);
6217     for (unsigned j = 0; j < NumElts; j += 2) {
6218       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6219           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6220         return false;
6221     }
6222   }
6223 
6224   if (M.size() == NumElts*2)
6225     WhichResult = 0;
6226 
6227   return true;
6228 }
6229 
6230 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6231 // that the mask elements are either all even and in steps of size 2 or all odd
6232 // and in steps of size 2.
6233 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6234 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6235 //  v2={e,f,g,h}
6236 // Requires similar checks to that of isVTRNMask with
6237 // respect the how results are returned.
6238 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6239   unsigned EltSz = VT.getScalarSizeInBits();
6240   if (EltSz == 64)
6241     return false;
6242 
6243   unsigned NumElts = VT.getVectorNumElements();
6244   if (M.size() != NumElts && M.size() != NumElts*2)
6245     return false;
6246 
6247   for (unsigned i = 0; i < M.size(); i += NumElts) {
6248     WhichResult = SelectPairHalf(NumElts, M, i);
6249     for (unsigned j = 0; j < NumElts; ++j) {
6250       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6251         return false;
6252     }
6253   }
6254 
6255   if (M.size() == NumElts*2)
6256     WhichResult = 0;
6257 
6258   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6259   if (VT.is64BitVector() && EltSz == 32)
6260     return false;
6261 
6262   return true;
6263 }
6264 
6265 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6266 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6267 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6268 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6269   unsigned EltSz = VT.getScalarSizeInBits();
6270   if (EltSz == 64)
6271     return false;
6272 
6273   unsigned NumElts = VT.getVectorNumElements();
6274   if (M.size() != NumElts && M.size() != NumElts*2)
6275     return false;
6276 
6277   unsigned Half = NumElts / 2;
6278   for (unsigned i = 0; i < M.size(); i += NumElts) {
6279     WhichResult = SelectPairHalf(NumElts, M, i);
6280     for (unsigned j = 0; j < NumElts; j += Half) {
6281       unsigned Idx = WhichResult;
6282       for (unsigned k = 0; k < Half; ++k) {
6283         int MIdx = M[i + j + k];
6284         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6285           return false;
6286         Idx += 2;
6287       }
6288     }
6289   }
6290 
6291   if (M.size() == NumElts*2)
6292     WhichResult = 0;
6293 
6294   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6295   if (VT.is64BitVector() && EltSz == 32)
6296     return false;
6297 
6298   return true;
6299 }
6300 
6301 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6302 // that pairs of elements of the shufflemask represent the same index in each
6303 // vector incrementing sequentially through the vectors.
6304 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6305 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6306 //  v2={e,f,g,h}
6307 // Requires similar checks to that of isVTRNMask with respect the how results
6308 // are returned.
6309 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6310   unsigned EltSz = VT.getScalarSizeInBits();
6311   if (EltSz == 64)
6312     return false;
6313 
6314   unsigned NumElts = VT.getVectorNumElements();
6315   if (M.size() != NumElts && M.size() != NumElts*2)
6316     return false;
6317 
6318   for (unsigned i = 0; i < M.size(); i += NumElts) {
6319     WhichResult = SelectPairHalf(NumElts, M, i);
6320     unsigned Idx = WhichResult * NumElts / 2;
6321     for (unsigned j = 0; j < NumElts; j += 2) {
6322       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6323           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6324         return false;
6325       Idx += 1;
6326     }
6327   }
6328 
6329   if (M.size() == NumElts*2)
6330     WhichResult = 0;
6331 
6332   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6333   if (VT.is64BitVector() && EltSz == 32)
6334     return false;
6335 
6336   return true;
6337 }
6338 
6339 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6340 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6341 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6342 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6343   unsigned EltSz = VT.getScalarSizeInBits();
6344   if (EltSz == 64)
6345     return false;
6346 
6347   unsigned NumElts = VT.getVectorNumElements();
6348   if (M.size() != NumElts && M.size() != NumElts*2)
6349     return false;
6350 
6351   for (unsigned i = 0; i < M.size(); i += NumElts) {
6352     WhichResult = SelectPairHalf(NumElts, M, i);
6353     unsigned Idx = WhichResult * NumElts / 2;
6354     for (unsigned j = 0; j < NumElts; j += 2) {
6355       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6356           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6357         return false;
6358       Idx += 1;
6359     }
6360   }
6361 
6362   if (M.size() == NumElts*2)
6363     WhichResult = 0;
6364 
6365   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6366   if (VT.is64BitVector() && EltSz == 32)
6367     return false;
6368 
6369   return true;
6370 }
6371 
6372 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6373 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6374 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6375                                            unsigned &WhichResult,
6376                                            bool &isV_UNDEF) {
6377   isV_UNDEF = false;
6378   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6379     return ARMISD::VTRN;
6380   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6381     return ARMISD::VUZP;
6382   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6383     return ARMISD::VZIP;
6384 
6385   isV_UNDEF = true;
6386   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6387     return ARMISD::VTRN;
6388   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6389     return ARMISD::VUZP;
6390   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6391     return ARMISD::VZIP;
6392 
6393   return 0;
6394 }
6395 
6396 /// \return true if this is a reverse operation on an vector.
6397 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6398   unsigned NumElts = VT.getVectorNumElements();
6399   // Make sure the mask has the right size.
6400   if (NumElts != M.size())
6401       return false;
6402 
6403   // Look for <15, ..., 3, -1, 1, 0>.
6404   for (unsigned i = 0; i != NumElts; ++i)
6405     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6406       return false;
6407 
6408   return true;
6409 }
6410 
6411 // If N is an integer constant that can be moved into a register in one
6412 // instruction, return an SDValue of such a constant (will become a MOV
6413 // instruction).  Otherwise return null.
6414 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6415                                      const ARMSubtarget *ST, const SDLoc &dl) {
6416   uint64_t Val;
6417   if (!isa<ConstantSDNode>(N))
6418     return SDValue();
6419   Val = cast<ConstantSDNode>(N)->getZExtValue();
6420 
6421   if (ST->isThumb1Only()) {
6422     if (Val <= 255 || ~Val <= 255)
6423       return DAG.getConstant(Val, dl, MVT::i32);
6424   } else {
6425     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6426       return DAG.getConstant(Val, dl, MVT::i32);
6427   }
6428   return SDValue();
6429 }
6430 
6431 // If this is a case we can't handle, return null and let the default
6432 // expansion code take care of it.
6433 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6434                                              const ARMSubtarget *ST) const {
6435   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6436   SDLoc dl(Op);
6437   EVT VT = Op.getValueType();
6438 
6439   APInt SplatBits, SplatUndef;
6440   unsigned SplatBitSize;
6441   bool HasAnyUndefs;
6442   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6443     if (SplatUndef.isAllOnesValue())
6444       return DAG.getUNDEF(VT);
6445 
6446     if (SplatBitSize <= 64) {
6447       // Check if an immediate VMOV works.
6448       EVT VmovVT;
6449       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6450                                       SplatUndef.getZExtValue(), SplatBitSize,
6451                                       DAG, dl, VmovVT, VT.is128BitVector(),
6452                                       VMOVModImm);
6453       if (Val.getNode()) {
6454         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6455         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6456       }
6457 
6458       // Try an immediate VMVN.
6459       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6460       Val = isNEONModifiedImm(NegatedImm,
6461                                       SplatUndef.getZExtValue(), SplatBitSize,
6462                                       DAG, dl, VmovVT, VT.is128BitVector(),
6463                                       VMVNModImm);
6464       if (Val.getNode()) {
6465         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6466         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6467       }
6468 
6469       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6470       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6471         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6472         if (ImmVal != -1) {
6473           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6474           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6475         }
6476       }
6477     }
6478   }
6479 
6480   // Scan through the operands to see if only one value is used.
6481   //
6482   // As an optimisation, even if more than one value is used it may be more
6483   // profitable to splat with one value then change some lanes.
6484   //
6485   // Heuristically we decide to do this if the vector has a "dominant" value,
6486   // defined as splatted to more than half of the lanes.
6487   unsigned NumElts = VT.getVectorNumElements();
6488   bool isOnlyLowElement = true;
6489   bool usesOnlyOneValue = true;
6490   bool hasDominantValue = false;
6491   bool isConstant = true;
6492 
6493   // Map of the number of times a particular SDValue appears in the
6494   // element list.
6495   DenseMap<SDValue, unsigned> ValueCounts;
6496   SDValue Value;
6497   for (unsigned i = 0; i < NumElts; ++i) {
6498     SDValue V = Op.getOperand(i);
6499     if (V.isUndef())
6500       continue;
6501     if (i > 0)
6502       isOnlyLowElement = false;
6503     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6504       isConstant = false;
6505 
6506     ValueCounts.insert(std::make_pair(V, 0));
6507     unsigned &Count = ValueCounts[V];
6508 
6509     // Is this value dominant? (takes up more than half of the lanes)
6510     if (++Count > (NumElts / 2)) {
6511       hasDominantValue = true;
6512       Value = V;
6513     }
6514   }
6515   if (ValueCounts.size() != 1)
6516     usesOnlyOneValue = false;
6517   if (!Value.getNode() && !ValueCounts.empty())
6518     Value = ValueCounts.begin()->first;
6519 
6520   if (ValueCounts.empty())
6521     return DAG.getUNDEF(VT);
6522 
6523   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6524   // Keep going if we are hitting this case.
6525   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6526     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6527 
6528   unsigned EltSize = VT.getScalarSizeInBits();
6529 
6530   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6531   // i32 and try again.
6532   if (hasDominantValue && EltSize <= 32) {
6533     if (!isConstant) {
6534       SDValue N;
6535 
6536       // If we are VDUPing a value that comes directly from a vector, that will
6537       // cause an unnecessary move to and from a GPR, where instead we could
6538       // just use VDUPLANE. We can only do this if the lane being extracted
6539       // is at a constant index, as the VDUP from lane instructions only have
6540       // constant-index forms.
6541       ConstantSDNode *constIndex;
6542       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6543           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6544         // We need to create a new undef vector to use for the VDUPLANE if the
6545         // size of the vector from which we get the value is different than the
6546         // size of the vector that we need to create. We will insert the element
6547         // such that the register coalescer will remove unnecessary copies.
6548         if (VT != Value->getOperand(0).getValueType()) {
6549           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6550                              VT.getVectorNumElements();
6551           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6552                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6553                         Value, DAG.getConstant(index, dl, MVT::i32)),
6554                            DAG.getConstant(index, dl, MVT::i32));
6555         } else
6556           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6557                         Value->getOperand(0), Value->getOperand(1));
6558       } else
6559         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6560 
6561       if (!usesOnlyOneValue) {
6562         // The dominant value was splatted as 'N', but we now have to insert
6563         // all differing elements.
6564         for (unsigned I = 0; I < NumElts; ++I) {
6565           if (Op.getOperand(I) == Value)
6566             continue;
6567           SmallVector<SDValue, 3> Ops;
6568           Ops.push_back(N);
6569           Ops.push_back(Op.getOperand(I));
6570           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6571           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6572         }
6573       }
6574       return N;
6575     }
6576     if (VT.getVectorElementType().isFloatingPoint()) {
6577       SmallVector<SDValue, 8> Ops;
6578       for (unsigned i = 0; i < NumElts; ++i)
6579         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6580                                   Op.getOperand(i)));
6581       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6582       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6583       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6584       if (Val.getNode())
6585         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6586     }
6587     if (usesOnlyOneValue) {
6588       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6589       if (isConstant && Val.getNode())
6590         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6591     }
6592   }
6593 
6594   // If all elements are constants and the case above didn't get hit, fall back
6595   // to the default expansion, which will generate a load from the constant
6596   // pool.
6597   if (isConstant)
6598     return SDValue();
6599 
6600   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6601   if (NumElts >= 4) {
6602     SDValue shuffle = ReconstructShuffle(Op, DAG);
6603     if (shuffle != SDValue())
6604       return shuffle;
6605   }
6606 
6607   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6608     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6609     // into two 64-bit vectors; we might discover a better way to lower it.
6610     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6611     EVT ExtVT = VT.getVectorElementType();
6612     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6613     SDValue Lower =
6614         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6615     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6616       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6617     SDValue Upper = DAG.getBuildVector(
6618         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6619     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6620       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6621     if (Lower && Upper)
6622       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6623   }
6624 
6625   // Vectors with 32- or 64-bit elements can be built by directly assigning
6626   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6627   // will be legalized.
6628   if (EltSize >= 32) {
6629     // Do the expansion with floating-point types, since that is what the VFP
6630     // registers are defined to use, and since i64 is not legal.
6631     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6632     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6633     SmallVector<SDValue, 8> Ops;
6634     for (unsigned i = 0; i < NumElts; ++i)
6635       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6636     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6637     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6638   }
6639 
6640   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6641   // know the default expansion would otherwise fall back on something even
6642   // worse. For a vector with one or two non-undef values, that's
6643   // scalar_to_vector for the elements followed by a shuffle (provided the
6644   // shuffle is valid for the target) and materialization element by element
6645   // on the stack followed by a load for everything else.
6646   if (!isConstant && !usesOnlyOneValue) {
6647     SDValue Vec = DAG.getUNDEF(VT);
6648     for (unsigned i = 0 ; i < NumElts; ++i) {
6649       SDValue V = Op.getOperand(i);
6650       if (V.isUndef())
6651         continue;
6652       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6653       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6654     }
6655     return Vec;
6656   }
6657 
6658   return SDValue();
6659 }
6660 
6661 // Gather data to see if the operation can be modelled as a
6662 // shuffle in combination with VEXTs.
6663 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6664                                               SelectionDAG &DAG) const {
6665   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6666   SDLoc dl(Op);
6667   EVT VT = Op.getValueType();
6668   unsigned NumElts = VT.getVectorNumElements();
6669 
6670   struct ShuffleSourceInfo {
6671     SDValue Vec;
6672     unsigned MinElt = std::numeric_limits<unsigned>::max();
6673     unsigned MaxElt = 0;
6674 
6675     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6676     // be compatible with the shuffle we intend to construct. As a result
6677     // ShuffleVec will be some sliding window into the original Vec.
6678     SDValue ShuffleVec;
6679 
6680     // Code should guarantee that element i in Vec starts at element "WindowBase
6681     // + i * WindowScale in ShuffleVec".
6682     int WindowBase = 0;
6683     int WindowScale = 1;
6684 
6685     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6686 
6687     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6688   };
6689 
6690   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6691   // node.
6692   SmallVector<ShuffleSourceInfo, 2> Sources;
6693   for (unsigned i = 0; i < NumElts; ++i) {
6694     SDValue V = Op.getOperand(i);
6695     if (V.isUndef())
6696       continue;
6697     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6698       // A shuffle can only come from building a vector from various
6699       // elements of other vectors.
6700       return SDValue();
6701     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6702       // Furthermore, shuffles require a constant mask, whereas extractelts
6703       // accept variable indices.
6704       return SDValue();
6705     }
6706 
6707     // Add this element source to the list if it's not already there.
6708     SDValue SourceVec = V.getOperand(0);
6709     auto Source = llvm::find(Sources, SourceVec);
6710     if (Source == Sources.end())
6711       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6712 
6713     // Update the minimum and maximum lane number seen.
6714     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6715     Source->MinElt = std::min(Source->MinElt, EltNo);
6716     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6717   }
6718 
6719   // Currently only do something sane when at most two source vectors
6720   // are involved.
6721   if (Sources.size() > 2)
6722     return SDValue();
6723 
6724   // Find out the smallest element size among result and two sources, and use
6725   // it as element size to build the shuffle_vector.
6726   EVT SmallestEltTy = VT.getVectorElementType();
6727   for (auto &Source : Sources) {
6728     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6729     if (SrcEltTy.bitsLT(SmallestEltTy))
6730       SmallestEltTy = SrcEltTy;
6731   }
6732   unsigned ResMultiplier =
6733       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6734   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6735   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6736 
6737   // If the source vector is too wide or too narrow, we may nevertheless be able
6738   // to construct a compatible shuffle either by concatenating it with UNDEF or
6739   // extracting a suitable range of elements.
6740   for (auto &Src : Sources) {
6741     EVT SrcVT = Src.ShuffleVec.getValueType();
6742 
6743     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6744       continue;
6745 
6746     // This stage of the search produces a source with the same element type as
6747     // the original, but with a total width matching the BUILD_VECTOR output.
6748     EVT EltVT = SrcVT.getVectorElementType();
6749     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6750     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6751 
6752     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6753       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6754         return SDValue();
6755       // We can pad out the smaller vector for free, so if it's part of a
6756       // shuffle...
6757       Src.ShuffleVec =
6758           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6759                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6760       continue;
6761     }
6762 
6763     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6764       return SDValue();
6765 
6766     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6767       // Span too large for a VEXT to cope
6768       return SDValue();
6769     }
6770 
6771     if (Src.MinElt >= NumSrcElts) {
6772       // The extraction can just take the second half
6773       Src.ShuffleVec =
6774           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6775                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6776       Src.WindowBase = -NumSrcElts;
6777     } else if (Src.MaxElt < NumSrcElts) {
6778       // The extraction can just take the first half
6779       Src.ShuffleVec =
6780           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6781                       DAG.getConstant(0, dl, MVT::i32));
6782     } else {
6783       // An actual VEXT is needed
6784       SDValue VEXTSrc1 =
6785           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6786                       DAG.getConstant(0, dl, MVT::i32));
6787       SDValue VEXTSrc2 =
6788           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6789                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6790 
6791       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6792                                    VEXTSrc2,
6793                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6794       Src.WindowBase = -Src.MinElt;
6795     }
6796   }
6797 
6798   // Another possible incompatibility occurs from the vector element types. We
6799   // can fix this by bitcasting the source vectors to the same type we intend
6800   // for the shuffle.
6801   for (auto &Src : Sources) {
6802     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6803     if (SrcEltTy == SmallestEltTy)
6804       continue;
6805     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6806     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6807     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6808     Src.WindowBase *= Src.WindowScale;
6809   }
6810 
6811   // Final sanity check before we try to actually produce a shuffle.
6812   DEBUG(
6813     for (auto Src : Sources)
6814       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6815   );
6816 
6817   // The stars all align, our next step is to produce the mask for the shuffle.
6818   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6819   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6820   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6821     SDValue Entry = Op.getOperand(i);
6822     if (Entry.isUndef())
6823       continue;
6824 
6825     auto Src = llvm::find(Sources, Entry.getOperand(0));
6826     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6827 
6828     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6829     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6830     // segment.
6831     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6832     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6833                                VT.getScalarSizeInBits());
6834     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6835 
6836     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6837     // starting at the appropriate offset.
6838     int *LaneMask = &Mask[i * ResMultiplier];
6839 
6840     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6841     ExtractBase += NumElts * (Src - Sources.begin());
6842     for (int j = 0; j < LanesDefined; ++j)
6843       LaneMask[j] = ExtractBase + j;
6844   }
6845 
6846   // Final check before we try to produce nonsense...
6847   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6848     return SDValue();
6849 
6850   // We can't handle more than two sources. This should have already
6851   // been checked before this point.
6852   assert(Sources.size() <= 2 && "Too many sources!");
6853 
6854   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6855   for (unsigned i = 0; i < Sources.size(); ++i)
6856     ShuffleOps[i] = Sources[i].ShuffleVec;
6857 
6858   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6859                                          ShuffleOps[1], Mask);
6860   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6861 }
6862 
6863 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6864 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6865 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6866 /// are assumed to be legal.
6867 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
6868   if (VT.getVectorNumElements() == 4 &&
6869       (VT.is128BitVector() || VT.is64BitVector())) {
6870     unsigned PFIndexes[4];
6871     for (unsigned i = 0; i != 4; ++i) {
6872       if (M[i] < 0)
6873         PFIndexes[i] = 8;
6874       else
6875         PFIndexes[i] = M[i];
6876     }
6877 
6878     // Compute the index in the perfect shuffle table.
6879     unsigned PFTableIndex =
6880       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6881     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6882     unsigned Cost = (PFEntry >> 30);
6883 
6884     if (Cost <= 4)
6885       return true;
6886   }
6887 
6888   bool ReverseVEXT, isV_UNDEF;
6889   unsigned Imm, WhichResult;
6890 
6891   unsigned EltSize = VT.getScalarSizeInBits();
6892   return (EltSize >= 32 ||
6893           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6894           isVREVMask(M, VT, 64) ||
6895           isVREVMask(M, VT, 32) ||
6896           isVREVMask(M, VT, 16) ||
6897           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6898           isVTBLMask(M, VT) ||
6899           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6900           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6901 }
6902 
6903 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6904 /// the specified operations to build the shuffle.
6905 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6906                                       SDValue RHS, SelectionDAG &DAG,
6907                                       const SDLoc &dl) {
6908   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6909   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6910   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6911 
6912   enum {
6913     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6914     OP_VREV,
6915     OP_VDUP0,
6916     OP_VDUP1,
6917     OP_VDUP2,
6918     OP_VDUP3,
6919     OP_VEXT1,
6920     OP_VEXT2,
6921     OP_VEXT3,
6922     OP_VUZPL, // VUZP, left result
6923     OP_VUZPR, // VUZP, right result
6924     OP_VZIPL, // VZIP, left result
6925     OP_VZIPR, // VZIP, right result
6926     OP_VTRNL, // VTRN, left result
6927     OP_VTRNR  // VTRN, right result
6928   };
6929 
6930   if (OpNum == OP_COPY) {
6931     if (LHSID == (1*9+2)*9+3) return LHS;
6932     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6933     return RHS;
6934   }
6935 
6936   SDValue OpLHS, OpRHS;
6937   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6938   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6939   EVT VT = OpLHS.getValueType();
6940 
6941   switch (OpNum) {
6942   default: llvm_unreachable("Unknown shuffle opcode!");
6943   case OP_VREV:
6944     // VREV divides the vector in half and swaps within the half.
6945     if (VT.getVectorElementType() == MVT::i32 ||
6946         VT.getVectorElementType() == MVT::f32)
6947       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6948     // vrev <4 x i16> -> VREV32
6949     if (VT.getVectorElementType() == MVT::i16)
6950       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6951     // vrev <4 x i8> -> VREV16
6952     assert(VT.getVectorElementType() == MVT::i8);
6953     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6954   case OP_VDUP0:
6955   case OP_VDUP1:
6956   case OP_VDUP2:
6957   case OP_VDUP3:
6958     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6959                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6960   case OP_VEXT1:
6961   case OP_VEXT2:
6962   case OP_VEXT3:
6963     return DAG.getNode(ARMISD::VEXT, dl, VT,
6964                        OpLHS, OpRHS,
6965                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6966   case OP_VUZPL:
6967   case OP_VUZPR:
6968     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6969                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6970   case OP_VZIPL:
6971   case OP_VZIPR:
6972     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6973                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6974   case OP_VTRNL:
6975   case OP_VTRNR:
6976     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6977                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6978   }
6979 }
6980 
6981 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6982                                        ArrayRef<int> ShuffleMask,
6983                                        SelectionDAG &DAG) {
6984   // Check to see if we can use the VTBL instruction.
6985   SDValue V1 = Op.getOperand(0);
6986   SDValue V2 = Op.getOperand(1);
6987   SDLoc DL(Op);
6988 
6989   SmallVector<SDValue, 8> VTBLMask;
6990   for (ArrayRef<int>::iterator
6991          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6992     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6993 
6994   if (V2.getNode()->isUndef())
6995     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6996                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6997 
6998   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6999                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
7000 }
7001 
7002 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
7003                                                       SelectionDAG &DAG) {
7004   SDLoc DL(Op);
7005   SDValue OpLHS = Op.getOperand(0);
7006   EVT VT = OpLHS.getValueType();
7007 
7008   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
7009          "Expect an v8i16/v16i8 type");
7010   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
7011   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
7012   // extract the first 8 bytes into the top double word and the last 8 bytes
7013   // into the bottom double word. The v8i16 case is similar.
7014   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
7015   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
7016                      DAG.getConstant(ExtractNum, DL, MVT::i32));
7017 }
7018 
7019 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
7020   SDValue V1 = Op.getOperand(0);
7021   SDValue V2 = Op.getOperand(1);
7022   SDLoc dl(Op);
7023   EVT VT = Op.getValueType();
7024   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
7025 
7026   // Convert shuffles that are directly supported on NEON to target-specific
7027   // DAG nodes, instead of keeping them as shuffles and matching them again
7028   // during code selection.  This is more efficient and avoids the possibility
7029   // of inconsistencies between legalization and selection.
7030   // FIXME: floating-point vectors should be canonicalized to integer vectors
7031   // of the same time so that they get CSEd properly.
7032   ArrayRef<int> ShuffleMask = SVN->getMask();
7033 
7034   unsigned EltSize = VT.getScalarSizeInBits();
7035   if (EltSize <= 32) {
7036     if (SVN->isSplat()) {
7037       int Lane = SVN->getSplatIndex();
7038       // If this is undef splat, generate it via "just" vdup, if possible.
7039       if (Lane == -1) Lane = 0;
7040 
7041       // Test if V1 is a SCALAR_TO_VECTOR.
7042       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
7043         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7044       }
7045       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
7046       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
7047       // reaches it).
7048       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
7049           !isa<ConstantSDNode>(V1.getOperand(0))) {
7050         bool IsScalarToVector = true;
7051         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
7052           if (!V1.getOperand(i).isUndef()) {
7053             IsScalarToVector = false;
7054             break;
7055           }
7056         if (IsScalarToVector)
7057           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
7058       }
7059       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
7060                          DAG.getConstant(Lane, dl, MVT::i32));
7061     }
7062 
7063     bool ReverseVEXT;
7064     unsigned Imm;
7065     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
7066       if (ReverseVEXT)
7067         std::swap(V1, V2);
7068       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
7069                          DAG.getConstant(Imm, dl, MVT::i32));
7070     }
7071 
7072     if (isVREVMask(ShuffleMask, VT, 64))
7073       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
7074     if (isVREVMask(ShuffleMask, VT, 32))
7075       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
7076     if (isVREVMask(ShuffleMask, VT, 16))
7077       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
7078 
7079     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
7080       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
7081                          DAG.getConstant(Imm, dl, MVT::i32));
7082     }
7083 
7084     // Check for Neon shuffles that modify both input vectors in place.
7085     // If both results are used, i.e., if there are two shuffles with the same
7086     // source operands and with masks corresponding to both results of one of
7087     // these operations, DAG memoization will ensure that a single node is
7088     // used for both shuffles.
7089     unsigned WhichResult;
7090     bool isV_UNDEF;
7091     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7092             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
7093       if (isV_UNDEF)
7094         V2 = V1;
7095       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
7096           .getValue(WhichResult);
7097     }
7098 
7099     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
7100     // shuffles that produce a result larger than their operands with:
7101     //   shuffle(concat(v1, undef), concat(v2, undef))
7102     // ->
7103     //   shuffle(concat(v1, v2), undef)
7104     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
7105     //
7106     // This is useful in the general case, but there are special cases where
7107     // native shuffles produce larger results: the two-result ops.
7108     //
7109     // Look through the concat when lowering them:
7110     //   shuffle(concat(v1, v2), undef)
7111     // ->
7112     //   concat(VZIP(v1, v2):0, :1)
7113     //
7114     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
7115       SDValue SubV1 = V1->getOperand(0);
7116       SDValue SubV2 = V1->getOperand(1);
7117       EVT SubVT = SubV1.getValueType();
7118 
7119       // We expect these to have been canonicalized to -1.
7120       assert(llvm::all_of(ShuffleMask, [&](int i) {
7121         return i < (int)VT.getVectorNumElements();
7122       }) && "Unexpected shuffle index into UNDEF operand!");
7123 
7124       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
7125               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
7126         if (isV_UNDEF)
7127           SubV2 = SubV1;
7128         assert((WhichResult == 0) &&
7129                "In-place shuffle of concat can only have one result!");
7130         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
7131                                   SubV1, SubV2);
7132         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
7133                            Res.getValue(1));
7134       }
7135     }
7136   }
7137 
7138   // If the shuffle is not directly supported and it has 4 elements, use
7139   // the PerfectShuffle-generated table to synthesize it from other shuffles.
7140   unsigned NumElts = VT.getVectorNumElements();
7141   if (NumElts == 4) {
7142     unsigned PFIndexes[4];
7143     for (unsigned i = 0; i != 4; ++i) {
7144       if (ShuffleMask[i] < 0)
7145         PFIndexes[i] = 8;
7146       else
7147         PFIndexes[i] = ShuffleMask[i];
7148     }
7149 
7150     // Compute the index in the perfect shuffle table.
7151     unsigned PFTableIndex =
7152       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
7153     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
7154     unsigned Cost = (PFEntry >> 30);
7155 
7156     if (Cost <= 4)
7157       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
7158   }
7159 
7160   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
7161   if (EltSize >= 32) {
7162     // Do the expansion with floating-point types, since that is what the VFP
7163     // registers are defined to use, and since i64 is not legal.
7164     EVT EltVT = EVT::getFloatingPointVT(EltSize);
7165     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
7166     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
7167     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
7168     SmallVector<SDValue, 8> Ops;
7169     for (unsigned i = 0; i < NumElts; ++i) {
7170       if (ShuffleMask[i] < 0)
7171         Ops.push_back(DAG.getUNDEF(EltVT));
7172       else
7173         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7174                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
7175                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7176                                                   dl, MVT::i32)));
7177     }
7178     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7179     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7180   }
7181 
7182   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7183     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7184 
7185   if (VT == MVT::v8i8)
7186     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7187       return NewOp;
7188 
7189   return SDValue();
7190 }
7191 
7192 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7193   // INSERT_VECTOR_ELT is legal only for immediate indexes.
7194   SDValue Lane = Op.getOperand(2);
7195   if (!isa<ConstantSDNode>(Lane))
7196     return SDValue();
7197 
7198   return Op;
7199 }
7200 
7201 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7202   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7203   SDValue Lane = Op.getOperand(1);
7204   if (!isa<ConstantSDNode>(Lane))
7205     return SDValue();
7206 
7207   SDValue Vec = Op.getOperand(0);
7208   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7209     SDLoc dl(Op);
7210     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7211   }
7212 
7213   return Op;
7214 }
7215 
7216 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7217   // The only time a CONCAT_VECTORS operation can have legal types is when
7218   // two 64-bit vectors are concatenated to a 128-bit vector.
7219   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
7220          "unexpected CONCAT_VECTORS");
7221   SDLoc dl(Op);
7222   SDValue Val = DAG.getUNDEF(MVT::v2f64);
7223   SDValue Op0 = Op.getOperand(0);
7224   SDValue Op1 = Op.getOperand(1);
7225   if (!Op0.isUndef())
7226     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7227                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
7228                       DAG.getIntPtrConstant(0, dl));
7229   if (!Op1.isUndef())
7230     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7231                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
7232                       DAG.getIntPtrConstant(1, dl));
7233   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
7234 }
7235 
7236 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
7237 /// element has been zero/sign-extended, depending on the isSigned parameter,
7238 /// from an integer type half its size.
7239 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
7240                                    bool isSigned) {
7241   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
7242   EVT VT = N->getValueType(0);
7243   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
7244     SDNode *BVN = N->getOperand(0).getNode();
7245     if (BVN->getValueType(0) != MVT::v4i32 ||
7246         BVN->getOpcode() != ISD::BUILD_VECTOR)
7247       return false;
7248     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7249     unsigned HiElt = 1 - LoElt;
7250     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
7251     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
7252     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
7253     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
7254     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
7255       return false;
7256     if (isSigned) {
7257       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
7258           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
7259         return true;
7260     } else {
7261       if (Hi0->isNullValue() && Hi1->isNullValue())
7262         return true;
7263     }
7264     return false;
7265   }
7266 
7267   if (N->getOpcode() != ISD::BUILD_VECTOR)
7268     return false;
7269 
7270   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
7271     SDNode *Elt = N->getOperand(i).getNode();
7272     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
7273       unsigned EltSize = VT.getScalarSizeInBits();
7274       unsigned HalfSize = EltSize / 2;
7275       if (isSigned) {
7276         if (!isIntN(HalfSize, C->getSExtValue()))
7277           return false;
7278       } else {
7279         if (!isUIntN(HalfSize, C->getZExtValue()))
7280           return false;
7281       }
7282       continue;
7283     }
7284     return false;
7285   }
7286 
7287   return true;
7288 }
7289 
7290 /// isSignExtended - Check if a node is a vector value that is sign-extended
7291 /// or a constant BUILD_VECTOR with sign-extended elements.
7292 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7293   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7294     return true;
7295   if (isExtendedBUILD_VECTOR(N, DAG, true))
7296     return true;
7297   return false;
7298 }
7299 
7300 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7301 /// or a constant BUILD_VECTOR with zero-extended elements.
7302 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7303   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7304     return true;
7305   if (isExtendedBUILD_VECTOR(N, DAG, false))
7306     return true;
7307   return false;
7308 }
7309 
7310 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7311   if (OrigVT.getSizeInBits() >= 64)
7312     return OrigVT;
7313 
7314   assert(OrigVT.isSimple() && "Expecting a simple value type");
7315 
7316   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7317   switch (OrigSimpleTy) {
7318   default: llvm_unreachable("Unexpected Vector Type");
7319   case MVT::v2i8:
7320   case MVT::v2i16:
7321      return MVT::v2i32;
7322   case MVT::v4i8:
7323     return  MVT::v4i16;
7324   }
7325 }
7326 
7327 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7328 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7329 /// We insert the required extension here to get the vector to fill a D register.
7330 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7331                                             const EVT &OrigTy,
7332                                             const EVT &ExtTy,
7333                                             unsigned ExtOpcode) {
7334   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7335   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7336   // 64-bits we need to insert a new extension so that it will be 64-bits.
7337   assert(ExtTy.is128BitVector() && "Unexpected extension size");
7338   if (OrigTy.getSizeInBits() >= 64)
7339     return N;
7340 
7341   // Must extend size to at least 64 bits to be used as an operand for VMULL.
7342   EVT NewVT = getExtensionTo64Bits(OrigTy);
7343 
7344   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7345 }
7346 
7347 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7348 /// does not do any sign/zero extension. If the original vector is less
7349 /// than 64 bits, an appropriate extension will be added after the load to
7350 /// reach a total size of 64 bits. We have to add the extension separately
7351 /// because ARM does not have a sign/zero extending load for vectors.
7352 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7353   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7354 
7355   // The load already has the right type.
7356   if (ExtendedTy == LD->getMemoryVT())
7357     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7358                        LD->getBasePtr(), LD->getPointerInfo(),
7359                        LD->getAlignment(), LD->getMemOperand()->getFlags());
7360 
7361   // We need to create a zextload/sextload. We cannot just create a load
7362   // followed by a zext/zext node because LowerMUL is also run during normal
7363   // operation legalization where we can't create illegal types.
7364   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7365                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7366                         LD->getMemoryVT(), LD->getAlignment(),
7367                         LD->getMemOperand()->getFlags());
7368 }
7369 
7370 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7371 /// extending load, or BUILD_VECTOR with extended elements, return the
7372 /// unextended value. The unextended vector should be 64 bits so that it can
7373 /// be used as an operand to a VMULL instruction. If the original vector size
7374 /// before extension is less than 64 bits we add a an extension to resize
7375 /// the vector to 64 bits.
7376 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7377   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7378     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7379                                         N->getOperand(0)->getValueType(0),
7380                                         N->getValueType(0),
7381                                         N->getOpcode());
7382 
7383   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7384     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7385            "Expected extending load");
7386 
7387     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7388     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7389     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7390     SDValue extLoad =
7391         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7392     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7393 
7394     return newLoad;
7395   }
7396 
7397   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7398   // have been legalized as a BITCAST from v4i32.
7399   if (N->getOpcode() == ISD::BITCAST) {
7400     SDNode *BVN = N->getOperand(0).getNode();
7401     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7402            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7403     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7404     return DAG.getBuildVector(
7405         MVT::v2i32, SDLoc(N),
7406         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7407   }
7408   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7409   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7410   EVT VT = N->getValueType(0);
7411   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7412   unsigned NumElts = VT.getVectorNumElements();
7413   MVT TruncVT = MVT::getIntegerVT(EltSize);
7414   SmallVector<SDValue, 8> Ops;
7415   SDLoc dl(N);
7416   for (unsigned i = 0; i != NumElts; ++i) {
7417     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7418     const APInt &CInt = C->getAPIntValue();
7419     // Element types smaller than 32 bits are not legal, so use i32 elements.
7420     // The values are implicitly truncated so sext vs. zext doesn't matter.
7421     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7422   }
7423   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7424 }
7425 
7426 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7427   unsigned Opcode = N->getOpcode();
7428   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7429     SDNode *N0 = N->getOperand(0).getNode();
7430     SDNode *N1 = N->getOperand(1).getNode();
7431     return N0->hasOneUse() && N1->hasOneUse() &&
7432       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7433   }
7434   return false;
7435 }
7436 
7437 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7438   unsigned Opcode = N->getOpcode();
7439   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7440     SDNode *N0 = N->getOperand(0).getNode();
7441     SDNode *N1 = N->getOperand(1).getNode();
7442     return N0->hasOneUse() && N1->hasOneUse() &&
7443       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7444   }
7445   return false;
7446 }
7447 
7448 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7449   // Multiplications are only custom-lowered for 128-bit vectors so that
7450   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7451   EVT VT = Op.getValueType();
7452   assert(VT.is128BitVector() && VT.isInteger() &&
7453          "unexpected type for custom-lowering ISD::MUL");
7454   SDNode *N0 = Op.getOperand(0).getNode();
7455   SDNode *N1 = Op.getOperand(1).getNode();
7456   unsigned NewOpc = 0;
7457   bool isMLA = false;
7458   bool isN0SExt = isSignExtended(N0, DAG);
7459   bool isN1SExt = isSignExtended(N1, DAG);
7460   if (isN0SExt && isN1SExt)
7461     NewOpc = ARMISD::VMULLs;
7462   else {
7463     bool isN0ZExt = isZeroExtended(N0, DAG);
7464     bool isN1ZExt = isZeroExtended(N1, DAG);
7465     if (isN0ZExt && isN1ZExt)
7466       NewOpc = ARMISD::VMULLu;
7467     else if (isN1SExt || isN1ZExt) {
7468       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7469       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7470       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7471         NewOpc = ARMISD::VMULLs;
7472         isMLA = true;
7473       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7474         NewOpc = ARMISD::VMULLu;
7475         isMLA = true;
7476       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7477         std::swap(N0, N1);
7478         NewOpc = ARMISD::VMULLu;
7479         isMLA = true;
7480       }
7481     }
7482 
7483     if (!NewOpc) {
7484       if (VT == MVT::v2i64)
7485         // Fall through to expand this.  It is not legal.
7486         return SDValue();
7487       else
7488         // Other vector multiplications are legal.
7489         return Op;
7490     }
7491   }
7492 
7493   // Legalize to a VMULL instruction.
7494   SDLoc DL(Op);
7495   SDValue Op0;
7496   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7497   if (!isMLA) {
7498     Op0 = SkipExtensionForVMULL(N0, DAG);
7499     assert(Op0.getValueType().is64BitVector() &&
7500            Op1.getValueType().is64BitVector() &&
7501            "unexpected types for extended operands to VMULL");
7502     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7503   }
7504 
7505   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7506   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7507   //   vmull q0, d4, d6
7508   //   vmlal q0, d5, d6
7509   // is faster than
7510   //   vaddl q0, d4, d5
7511   //   vmovl q1, d6
7512   //   vmul  q0, q0, q1
7513   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7514   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7515   EVT Op1VT = Op1.getValueType();
7516   return DAG.getNode(N0->getOpcode(), DL, VT,
7517                      DAG.getNode(NewOpc, DL, VT,
7518                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7519                      DAG.getNode(NewOpc, DL, VT,
7520                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7521 }
7522 
7523 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7524                               SelectionDAG &DAG) {
7525   // TODO: Should this propagate fast-math-flags?
7526 
7527   // Convert to float
7528   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7529   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7530   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7531   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7532   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7533   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7534   // Get reciprocal estimate.
7535   // float4 recip = vrecpeq_f32(yf);
7536   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7537                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7538                    Y);
7539   // Because char has a smaller range than uchar, we can actually get away
7540   // without any newton steps.  This requires that we use a weird bias
7541   // of 0xb000, however (again, this has been exhaustively tested).
7542   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7543   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7544   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7545   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7546   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7547   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7548   // Convert back to short.
7549   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7550   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7551   return X;
7552 }
7553 
7554 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7555                                SelectionDAG &DAG) {
7556   // TODO: Should this propagate fast-math-flags?
7557 
7558   SDValue N2;
7559   // Convert to float.
7560   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7561   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7562   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7563   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7564   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7565   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7566 
7567   // Use reciprocal estimate and one refinement step.
7568   // float4 recip = vrecpeq_f32(yf);
7569   // recip *= vrecpsq_f32(yf, recip);
7570   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7571                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7572                    N1);
7573   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7574                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7575                    N1, N2);
7576   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7577   // Because short has a smaller range than ushort, we can actually get away
7578   // with only a single newton step.  This requires that we use a weird bias
7579   // of 89, however (again, this has been exhaustively tested).
7580   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7581   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7582   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7583   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7584   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7585   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7586   // Convert back to integer and return.
7587   // return vmovn_s32(vcvt_s32_f32(result));
7588   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7589   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7590   return N0;
7591 }
7592 
7593 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7594   EVT VT = Op.getValueType();
7595   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7596          "unexpected type for custom-lowering ISD::SDIV");
7597 
7598   SDLoc dl(Op);
7599   SDValue N0 = Op.getOperand(0);
7600   SDValue N1 = Op.getOperand(1);
7601   SDValue N2, N3;
7602 
7603   if (VT == MVT::v8i8) {
7604     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7605     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7606 
7607     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7608                      DAG.getIntPtrConstant(4, dl));
7609     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7610                      DAG.getIntPtrConstant(4, dl));
7611     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7612                      DAG.getIntPtrConstant(0, dl));
7613     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7614                      DAG.getIntPtrConstant(0, dl));
7615 
7616     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7617     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7618 
7619     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7620     N0 = LowerCONCAT_VECTORS(N0, DAG);
7621 
7622     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7623     return N0;
7624   }
7625   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7626 }
7627 
7628 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7629   // TODO: Should this propagate fast-math-flags?
7630   EVT VT = Op.getValueType();
7631   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7632          "unexpected type for custom-lowering ISD::UDIV");
7633 
7634   SDLoc dl(Op);
7635   SDValue N0 = Op.getOperand(0);
7636   SDValue N1 = Op.getOperand(1);
7637   SDValue N2, N3;
7638 
7639   if (VT == MVT::v8i8) {
7640     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7641     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7642 
7643     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7644                      DAG.getIntPtrConstant(4, dl));
7645     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7646                      DAG.getIntPtrConstant(4, dl));
7647     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7648                      DAG.getIntPtrConstant(0, dl));
7649     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7650                      DAG.getIntPtrConstant(0, dl));
7651 
7652     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7653     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7654 
7655     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7656     N0 = LowerCONCAT_VECTORS(N0, DAG);
7657 
7658     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7659                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7660                                      MVT::i32),
7661                      N0);
7662     return N0;
7663   }
7664 
7665   // v4i16 sdiv ... Convert to float.
7666   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7667   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7668   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7669   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7670   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7671   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7672 
7673   // Use reciprocal estimate and two refinement steps.
7674   // float4 recip = vrecpeq_f32(yf);
7675   // recip *= vrecpsq_f32(yf, recip);
7676   // recip *= vrecpsq_f32(yf, recip);
7677   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7678                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7679                    BN1);
7680   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7681                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7682                    BN1, N2);
7683   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7684   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7685                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7686                    BN1, N2);
7687   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7688   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7689   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7690   // and that it will never cause us to return an answer too large).
7691   // float4 result = as_float4(as_int4(xf*recip) + 2);
7692   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7693   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7694   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7695   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7696   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7697   // Convert back to integer and return.
7698   // return vmovn_u32(vcvt_s32_f32(result));
7699   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7700   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7701   return N0;
7702 }
7703 
7704 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7705   EVT VT = Op.getNode()->getValueType(0);
7706   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7707 
7708   unsigned Opc;
7709   bool ExtraOp = false;
7710   switch (Op.getOpcode()) {
7711   default: llvm_unreachable("Invalid code");
7712   case ISD::ADDC: Opc = ARMISD::ADDC; break;
7713   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7714   case ISD::SUBC: Opc = ARMISD::SUBC; break;
7715   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7716   }
7717 
7718   if (!ExtraOp)
7719     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7720                        Op.getOperand(1));
7721   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7722                      Op.getOperand(1), Op.getOperand(2));
7723 }
7724 
7725 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
7726   SDNode *N = Op.getNode();
7727   EVT VT = N->getValueType(0);
7728   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7729 
7730   SDValue Carry = Op.getOperand(2);
7731 
7732   SDLoc DL(Op);
7733 
7734   SDValue Result;
7735   if (Op.getOpcode() == ISD::ADDCARRY) {
7736     // This converts the boolean value carry into the carry flag.
7737     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7738 
7739     // Do the addition proper using the carry flag we wanted.
7740     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
7741                          Op.getOperand(1), Carry.getValue(1));
7742 
7743     // Now convert the carry flag into a boolean value.
7744     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7745   } else {
7746     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
7747     // have to invert the carry first.
7748     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7749                         DAG.getConstant(1, DL, MVT::i32), Carry);
7750     // This converts the boolean value carry into the carry flag.
7751     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7752 
7753     // Do the subtraction proper using the carry flag we wanted.
7754     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
7755                          Op.getOperand(1), Carry.getValue(1));
7756 
7757     // Now convert the carry flag into a boolean value.
7758     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7759     // But the carry returned by ARMISD::SUBE is not a borrow as expected
7760     // by ISD::SUBCARRY, so compute 1 - C.
7761     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7762                         DAG.getConstant(1, DL, MVT::i32), Carry);
7763   }
7764 
7765   // Return both values.
7766   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
7767 }
7768 
7769 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7770   assert(Subtarget->isTargetDarwin());
7771 
7772   // For iOS, we want to call an alternative entry point: __sincos_stret,
7773   // return values are passed via sret.
7774   SDLoc dl(Op);
7775   SDValue Arg = Op.getOperand(0);
7776   EVT ArgVT = Arg.getValueType();
7777   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7778   auto PtrVT = getPointerTy(DAG.getDataLayout());
7779 
7780   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7781   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7782 
7783   // Pair of floats / doubles used to pass the result.
7784   Type *RetTy = StructType::get(ArgTy, ArgTy);
7785   auto &DL = DAG.getDataLayout();
7786 
7787   ArgListTy Args;
7788   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7789   SDValue SRet;
7790   if (ShouldUseSRet) {
7791     // Create stack object for sret.
7792     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7793     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7794     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7795     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7796 
7797     ArgListEntry Entry;
7798     Entry.Node = SRet;
7799     Entry.Ty = RetTy->getPointerTo();
7800     Entry.IsSExt = false;
7801     Entry.IsZExt = false;
7802     Entry.IsSRet = true;
7803     Args.push_back(Entry);
7804     RetTy = Type::getVoidTy(*DAG.getContext());
7805   }
7806 
7807   ArgListEntry Entry;
7808   Entry.Node = Arg;
7809   Entry.Ty = ArgTy;
7810   Entry.IsSExt = false;
7811   Entry.IsZExt = false;
7812   Args.push_back(Entry);
7813 
7814   RTLIB::Libcall LC =
7815       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
7816   const char *LibcallName = getLibcallName(LC);
7817   CallingConv::ID CC = getLibcallCallingConv(LC);
7818   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7819 
7820   TargetLowering::CallLoweringInfo CLI(DAG);
7821   CLI.setDebugLoc(dl)
7822       .setChain(DAG.getEntryNode())
7823       .setCallee(CC, RetTy, Callee, std::move(Args))
7824       .setDiscardResult(ShouldUseSRet);
7825   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7826 
7827   if (!ShouldUseSRet)
7828     return CallResult.first;
7829 
7830   SDValue LoadSin =
7831       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7832 
7833   // Address of cos field.
7834   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7835                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7836   SDValue LoadCos =
7837       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7838 
7839   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7840   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7841                      LoadSin.getValue(0), LoadCos.getValue(0));
7842 }
7843 
7844 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7845                                                   bool Signed,
7846                                                   SDValue &Chain) const {
7847   EVT VT = Op.getValueType();
7848   assert((VT == MVT::i32 || VT == MVT::i64) &&
7849          "unexpected type for custom lowering DIV");
7850   SDLoc dl(Op);
7851 
7852   const auto &DL = DAG.getDataLayout();
7853   const auto &TLI = DAG.getTargetLoweringInfo();
7854 
7855   const char *Name = nullptr;
7856   if (Signed)
7857     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7858   else
7859     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7860 
7861   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7862 
7863   ARMTargetLowering::ArgListTy Args;
7864 
7865   for (auto AI : {1, 0}) {
7866     ArgListEntry Arg;
7867     Arg.Node = Op.getOperand(AI);
7868     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7869     Args.push_back(Arg);
7870   }
7871 
7872   CallLoweringInfo CLI(DAG);
7873   CLI.setDebugLoc(dl)
7874     .setChain(Chain)
7875     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7876                ES, std::move(Args));
7877 
7878   return LowerCallTo(CLI).first;
7879 }
7880 
7881 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7882                                             bool Signed) const {
7883   assert(Op.getValueType() == MVT::i32 &&
7884          "unexpected type for custom lowering DIV");
7885   SDLoc dl(Op);
7886 
7887   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7888                                DAG.getEntryNode(), Op.getOperand(1));
7889 
7890   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7891 }
7892 
7893 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7894   SDLoc DL(N);
7895   SDValue Op = N->getOperand(1);
7896   if (N->getValueType(0) == MVT::i32)
7897     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7898   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7899                            DAG.getConstant(0, DL, MVT::i32));
7900   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7901                            DAG.getConstant(1, DL, MVT::i32));
7902   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7903                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7904 }
7905 
7906 void ARMTargetLowering::ExpandDIV_Windows(
7907     SDValue Op, SelectionDAG &DAG, bool Signed,
7908     SmallVectorImpl<SDValue> &Results) const {
7909   const auto &DL = DAG.getDataLayout();
7910   const auto &TLI = DAG.getTargetLoweringInfo();
7911 
7912   assert(Op.getValueType() == MVT::i64 &&
7913          "unexpected type for custom lowering DIV");
7914   SDLoc dl(Op);
7915 
7916   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7917 
7918   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7919 
7920   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7921   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7922                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7923   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7924 
7925   Results.push_back(Lower);
7926   Results.push_back(Upper);
7927 }
7928 
7929 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7930   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7931     // Acquire/Release load/store is not legal for targets without a dmb or
7932     // equivalent available.
7933     return SDValue();
7934 
7935   // Monotonic load/store is legal for all targets.
7936   return Op;
7937 }
7938 
7939 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7940                                     SmallVectorImpl<SDValue> &Results,
7941                                     SelectionDAG &DAG,
7942                                     const ARMSubtarget *Subtarget) {
7943   SDLoc DL(N);
7944   // Under Power Management extensions, the cycle-count is:
7945   //    mrc p15, #0, <Rt>, c9, c13, #0
7946   SDValue Ops[] = { N->getOperand(0), // Chain
7947                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7948                     DAG.getConstant(15, DL, MVT::i32),
7949                     DAG.getConstant(0, DL, MVT::i32),
7950                     DAG.getConstant(9, DL, MVT::i32),
7951                     DAG.getConstant(13, DL, MVT::i32),
7952                     DAG.getConstant(0, DL, MVT::i32)
7953   };
7954 
7955   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7956                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7957   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7958                                 DAG.getConstant(0, DL, MVT::i32)));
7959   Results.push_back(Cycles32.getValue(1));
7960 }
7961 
7962 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7963   SDLoc dl(V.getNode());
7964   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7965   SDValue VHi = DAG.getAnyExtOrTrunc(
7966       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7967       dl, MVT::i32);
7968   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7969   if (isBigEndian)
7970     std::swap (VLo, VHi);
7971   SDValue RegClass =
7972       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7973   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7974   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7975   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7976   return SDValue(
7977       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7978 }
7979 
7980 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7981                                        SmallVectorImpl<SDValue> & Results,
7982                                        SelectionDAG &DAG) {
7983   assert(N->getValueType(0) == MVT::i64 &&
7984          "AtomicCmpSwap on types less than 64 should be legal");
7985   SDValue Ops[] = {N->getOperand(1),
7986                    createGPRPairNode(DAG, N->getOperand(2)),
7987                    createGPRPairNode(DAG, N->getOperand(3)),
7988                    N->getOperand(0)};
7989   SDNode *CmpSwap = DAG.getMachineNode(
7990       ARM::CMP_SWAP_64, SDLoc(N),
7991       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7992 
7993   MachineFunction &MF = DAG.getMachineFunction();
7994   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7995   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7996   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7997 
7998   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7999 
8000   Results.push_back(
8001       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
8002                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8003   Results.push_back(
8004       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
8005                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
8006   Results.push_back(SDValue(CmpSwap, 2));
8007 }
8008 
8009 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
8010                           SelectionDAG &DAG) {
8011   const auto &TLI = DAG.getTargetLoweringInfo();
8012 
8013   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
8014          "Custom lowering is MSVCRT specific!");
8015 
8016   SDLoc dl(Op);
8017   SDValue Val = Op.getOperand(0);
8018   MVT Ty = Val->getSimpleValueType(0);
8019   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
8020   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
8021                                          TLI.getPointerTy(DAG.getDataLayout()));
8022 
8023   TargetLowering::ArgListTy Args;
8024   TargetLowering::ArgListEntry Entry;
8025 
8026   Entry.Node = Val;
8027   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
8028   Entry.IsZExt = true;
8029   Args.push_back(Entry);
8030 
8031   Entry.Node = Exponent;
8032   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
8033   Entry.IsZExt = true;
8034   Args.push_back(Entry);
8035 
8036   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
8037 
8038   // In the in-chain to the call is the entry node  If we are emitting a
8039   // tailcall, the chain will be mutated if the node has a non-entry input
8040   // chain.
8041   SDValue InChain = DAG.getEntryNode();
8042   SDValue TCChain = InChain;
8043 
8044   const Function &F = DAG.getMachineFunction().getFunction();
8045   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
8046               F.getReturnType() == LCRTy;
8047   if (IsTC)
8048     InChain = TCChain;
8049 
8050   TargetLowering::CallLoweringInfo CLI(DAG);
8051   CLI.setDebugLoc(dl)
8052       .setChain(InChain)
8053       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
8054       .setTailCall(IsTC);
8055   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
8056 
8057   // Return the chain (the DAG root) if it is a tail call
8058   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
8059 }
8060 
8061 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
8062   DEBUG(dbgs() << "Lowering node: "; Op.dump());
8063   switch (Op.getOpcode()) {
8064   default: llvm_unreachable("Don't know how to custom lower this!");
8065   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
8066   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
8067   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
8068   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
8069   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
8070   case ISD::SELECT:        return LowerSELECT(Op, DAG);
8071   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
8072   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
8073   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
8074   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
8075   case ISD::VASTART:       return LowerVASTART(Op, DAG);
8076   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
8077   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
8078   case ISD::SINT_TO_FP:
8079   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
8080   case ISD::FP_TO_SINT:
8081   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
8082   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
8083   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
8084   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
8085   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
8086   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
8087   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
8088   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
8089                                                                Subtarget);
8090   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG, Subtarget);
8091   case ISD::SHL:
8092   case ISD::SRL:
8093   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
8094   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
8095   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
8096   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
8097   case ISD::SRL_PARTS:
8098   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
8099   case ISD::CTTZ:
8100   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
8101   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
8102   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
8103   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
8104   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
8105   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
8106   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
8107   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
8108   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
8109   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
8110   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
8111   case ISD::MUL:           return LowerMUL(Op, DAG);
8112   case ISD::SDIV:
8113     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8114       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
8115     return LowerSDIV(Op, DAG);
8116   case ISD::UDIV:
8117     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
8118       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
8119     return LowerUDIV(Op, DAG);
8120   case ISD::ADDC:
8121   case ISD::ADDE:
8122   case ISD::SUBC:
8123   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
8124   case ISD::ADDCARRY:
8125   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
8126   case ISD::SADDO:
8127   case ISD::SSUBO:
8128     return LowerSignedALUO(Op, DAG);
8129   case ISD::UADDO:
8130   case ISD::USUBO:
8131     return LowerUnsignedALUO(Op, DAG);
8132   case ISD::ATOMIC_LOAD:
8133   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
8134   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
8135   case ISD::SDIVREM:
8136   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
8137   case ISD::DYNAMIC_STACKALLOC:
8138     if (Subtarget->isTargetWindows())
8139       return LowerDYNAMIC_STACKALLOC(Op, DAG);
8140     llvm_unreachable("Don't know how to custom lower this!");
8141   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
8142   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
8143   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
8144   case ARMISD::WIN__DBZCHK: return SDValue();
8145   }
8146 }
8147 
8148 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
8149                                  SelectionDAG &DAG) {
8150   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
8151   unsigned Opc = 0;
8152   if (IntNo == Intrinsic::arm_smlald)
8153     Opc = ARMISD::SMLALD;
8154   else if (IntNo == Intrinsic::arm_smlaldx)
8155     Opc = ARMISD::SMLALDX;
8156   else if (IntNo == Intrinsic::arm_smlsld)
8157     Opc = ARMISD::SMLSLD;
8158   else if (IntNo == Intrinsic::arm_smlsldx)
8159     Opc = ARMISD::SMLSLDX;
8160   else
8161     return;
8162 
8163   SDLoc dl(N);
8164   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8165                            N->getOperand(3),
8166                            DAG.getConstant(0, dl, MVT::i32));
8167   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
8168                            N->getOperand(3),
8169                            DAG.getConstant(1, dl, MVT::i32));
8170 
8171   SDValue LongMul = DAG.getNode(Opc, dl,
8172                                 DAG.getVTList(MVT::i32, MVT::i32),
8173                                 N->getOperand(1), N->getOperand(2),
8174                                 Lo, Hi);
8175   Results.push_back(LongMul.getValue(0));
8176   Results.push_back(LongMul.getValue(1));
8177 }
8178 
8179 /// ReplaceNodeResults - Replace the results of node with an illegal result
8180 /// type with new values built out of custom code.
8181 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
8182                                            SmallVectorImpl<SDValue> &Results,
8183                                            SelectionDAG &DAG) const {
8184   SDValue Res;
8185   switch (N->getOpcode()) {
8186   default:
8187     llvm_unreachable("Don't know how to custom expand this!");
8188   case ISD::READ_REGISTER:
8189     ExpandREAD_REGISTER(N, Results, DAG);
8190     break;
8191   case ISD::BITCAST:
8192     Res = ExpandBITCAST(N, DAG, Subtarget);
8193     break;
8194   case ISD::SRL:
8195   case ISD::SRA:
8196     Res = Expand64BitShift(N, DAG, Subtarget);
8197     break;
8198   case ISD::SREM:
8199   case ISD::UREM:
8200     Res = LowerREM(N, DAG);
8201     break;
8202   case ISD::SDIVREM:
8203   case ISD::UDIVREM:
8204     Res = LowerDivRem(SDValue(N, 0), DAG);
8205     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
8206     Results.push_back(Res.getValue(0));
8207     Results.push_back(Res.getValue(1));
8208     return;
8209   case ISD::READCYCLECOUNTER:
8210     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
8211     return;
8212   case ISD::UDIV:
8213   case ISD::SDIV:
8214     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
8215     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
8216                              Results);
8217   case ISD::ATOMIC_CMP_SWAP:
8218     ReplaceCMP_SWAP_64Results(N, Results, DAG);
8219     return;
8220   case ISD::INTRINSIC_WO_CHAIN:
8221     return ReplaceLongIntrinsic(N, Results, DAG);
8222   }
8223   if (Res.getNode())
8224     Results.push_back(Res);
8225 }
8226 
8227 //===----------------------------------------------------------------------===//
8228 //                           ARM Scheduler Hooks
8229 //===----------------------------------------------------------------------===//
8230 
8231 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
8232 /// registers the function context.
8233 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
8234                                                MachineBasicBlock *MBB,
8235                                                MachineBasicBlock *DispatchBB,
8236                                                int FI) const {
8237   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
8238          "ROPI/RWPI not currently supported with SjLj");
8239   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8240   DebugLoc dl = MI.getDebugLoc();
8241   MachineFunction *MF = MBB->getParent();
8242   MachineRegisterInfo *MRI = &MF->getRegInfo();
8243   MachineConstantPool *MCP = MF->getConstantPool();
8244   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
8245   const Function &F = MF->getFunction();
8246 
8247   bool isThumb = Subtarget->isThumb();
8248   bool isThumb2 = Subtarget->isThumb2();
8249 
8250   unsigned PCLabelId = AFI->createPICLabelUId();
8251   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
8252   ARMConstantPoolValue *CPV =
8253     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
8254   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
8255 
8256   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
8257                                            : &ARM::GPRRegClass;
8258 
8259   // Grab constant pool and fixed stack memory operands.
8260   MachineMemOperand *CPMMO =
8261       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
8262                                MachineMemOperand::MOLoad, 4, 4);
8263 
8264   MachineMemOperand *FIMMOSt =
8265       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
8266                                MachineMemOperand::MOStore, 4, 4);
8267 
8268   // Load the address of the dispatch MBB into the jump buffer.
8269   if (isThumb2) {
8270     // Incoming value: jbuf
8271     //   ldr.n  r5, LCPI1_1
8272     //   orr    r5, r5, #1
8273     //   add    r5, pc
8274     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
8275     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8276     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
8277         .addConstantPoolIndex(CPI)
8278         .addMemOperand(CPMMO)
8279         .add(predOps(ARMCC::AL));
8280     // Set the low bit because of thumb mode.
8281     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8282     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8283         .addReg(NewVReg1, RegState::Kill)
8284         .addImm(0x01)
8285         .add(predOps(ARMCC::AL))
8286         .add(condCodeOp());
8287     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8288     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8289       .addReg(NewVReg2, RegState::Kill)
8290       .addImm(PCLabelId);
8291     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8292         .addReg(NewVReg3, RegState::Kill)
8293         .addFrameIndex(FI)
8294         .addImm(36) // &jbuf[1] :: pc
8295         .addMemOperand(FIMMOSt)
8296         .add(predOps(ARMCC::AL));
8297   } else if (isThumb) {
8298     // Incoming value: jbuf
8299     //   ldr.n  r1, LCPI1_4
8300     //   add    r1, pc
8301     //   mov    r2, #1
8302     //   orrs   r1, r2
8303     //   add    r2, $jbuf, #+4 ; &jbuf[1]
8304     //   str    r1, [r2]
8305     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8306     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8307         .addConstantPoolIndex(CPI)
8308         .addMemOperand(CPMMO)
8309         .add(predOps(ARMCC::AL));
8310     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8311     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8312       .addReg(NewVReg1, RegState::Kill)
8313       .addImm(PCLabelId);
8314     // Set the low bit because of thumb mode.
8315     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8316     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8317         .addReg(ARM::CPSR, RegState::Define)
8318         .addImm(1)
8319         .add(predOps(ARMCC::AL));
8320     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8321     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8322         .addReg(ARM::CPSR, RegState::Define)
8323         .addReg(NewVReg2, RegState::Kill)
8324         .addReg(NewVReg3, RegState::Kill)
8325         .add(predOps(ARMCC::AL));
8326     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8327     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8328             .addFrameIndex(FI)
8329             .addImm(36); // &jbuf[1] :: pc
8330     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8331         .addReg(NewVReg4, RegState::Kill)
8332         .addReg(NewVReg5, RegState::Kill)
8333         .addImm(0)
8334         .addMemOperand(FIMMOSt)
8335         .add(predOps(ARMCC::AL));
8336   } else {
8337     // Incoming value: jbuf
8338     //   ldr  r1, LCPI1_1
8339     //   add  r1, pc, r1
8340     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
8341     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8342     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
8343         .addConstantPoolIndex(CPI)
8344         .addImm(0)
8345         .addMemOperand(CPMMO)
8346         .add(predOps(ARMCC::AL));
8347     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8348     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
8349         .addReg(NewVReg1, RegState::Kill)
8350         .addImm(PCLabelId)
8351         .add(predOps(ARMCC::AL));
8352     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
8353         .addReg(NewVReg2, RegState::Kill)
8354         .addFrameIndex(FI)
8355         .addImm(36) // &jbuf[1] :: pc
8356         .addMemOperand(FIMMOSt)
8357         .add(predOps(ARMCC::AL));
8358   }
8359 }
8360 
8361 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
8362                                               MachineBasicBlock *MBB) const {
8363   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8364   DebugLoc dl = MI.getDebugLoc();
8365   MachineFunction *MF = MBB->getParent();
8366   MachineRegisterInfo *MRI = &MF->getRegInfo();
8367   MachineFrameInfo &MFI = MF->getFrameInfo();
8368   int FI = MFI.getFunctionContextIndex();
8369 
8370   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
8371                                                         : &ARM::GPRnopcRegClass;
8372 
8373   // Get a mapping of the call site numbers to all of the landing pads they're
8374   // associated with.
8375   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
8376   unsigned MaxCSNum = 0;
8377   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8378        ++BB) {
8379     if (!BB->isEHPad()) continue;
8380 
8381     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8382     // pad.
8383     for (MachineBasicBlock::iterator
8384            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8385       if (!II->isEHLabel()) continue;
8386 
8387       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8388       if (!MF->hasCallSiteLandingPad(Sym)) continue;
8389 
8390       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8391       for (SmallVectorImpl<unsigned>::iterator
8392              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8393            CSI != CSE; ++CSI) {
8394         CallSiteNumToLPad[*CSI].push_back(&*BB);
8395         MaxCSNum = std::max(MaxCSNum, *CSI);
8396       }
8397       break;
8398     }
8399   }
8400 
8401   // Get an ordered list of the machine basic blocks for the jump table.
8402   std::vector<MachineBasicBlock*> LPadList;
8403   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8404   LPadList.reserve(CallSiteNumToLPad.size());
8405   for (unsigned I = 1; I <= MaxCSNum; ++I) {
8406     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8407     for (SmallVectorImpl<MachineBasicBlock*>::iterator
8408            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8409       LPadList.push_back(*II);
8410       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8411     }
8412   }
8413 
8414   assert(!LPadList.empty() &&
8415          "No landing pad destinations for the dispatch jump table!");
8416 
8417   // Create the jump table and associated information.
8418   MachineJumpTableInfo *JTI =
8419     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8420   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8421 
8422   // Create the MBBs for the dispatch code.
8423 
8424   // Shove the dispatch's address into the return slot in the function context.
8425   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8426   DispatchBB->setIsEHPad();
8427 
8428   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8429   unsigned trap_opcode;
8430   if (Subtarget->isThumb())
8431     trap_opcode = ARM::tTRAP;
8432   else
8433     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8434 
8435   BuildMI(TrapBB, dl, TII->get(trap_opcode));
8436   DispatchBB->addSuccessor(TrapBB);
8437 
8438   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8439   DispatchBB->addSuccessor(DispContBB);
8440 
8441   // Insert and MBBs.
8442   MF->insert(MF->end(), DispatchBB);
8443   MF->insert(MF->end(), DispContBB);
8444   MF->insert(MF->end(), TrapBB);
8445 
8446   // Insert code into the entry block that creates and registers the function
8447   // context.
8448   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8449 
8450   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8451       MachinePointerInfo::getFixedStack(*MF, FI),
8452       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8453 
8454   MachineInstrBuilder MIB;
8455   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8456 
8457   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8458   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8459 
8460   // Add a register mask with no preserved registers.  This results in all
8461   // registers being marked as clobbered. This can't work if the dispatch block
8462   // is in a Thumb1 function and is linked with ARM code which uses the FP
8463   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8464   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8465 
8466   bool IsPositionIndependent = isPositionIndependent();
8467   unsigned NumLPads = LPadList.size();
8468   if (Subtarget->isThumb2()) {
8469     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8470     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8471         .addFrameIndex(FI)
8472         .addImm(4)
8473         .addMemOperand(FIMMOLd)
8474         .add(predOps(ARMCC::AL));
8475 
8476     if (NumLPads < 256) {
8477       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8478           .addReg(NewVReg1)
8479           .addImm(LPadList.size())
8480           .add(predOps(ARMCC::AL));
8481     } else {
8482       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8483       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8484           .addImm(NumLPads & 0xFFFF)
8485           .add(predOps(ARMCC::AL));
8486 
8487       unsigned VReg2 = VReg1;
8488       if ((NumLPads & 0xFFFF0000) != 0) {
8489         VReg2 = MRI->createVirtualRegister(TRC);
8490         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8491             .addReg(VReg1)
8492             .addImm(NumLPads >> 16)
8493             .add(predOps(ARMCC::AL));
8494       }
8495 
8496       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8497           .addReg(NewVReg1)
8498           .addReg(VReg2)
8499           .add(predOps(ARMCC::AL));
8500     }
8501 
8502     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8503       .addMBB(TrapBB)
8504       .addImm(ARMCC::HI)
8505       .addReg(ARM::CPSR);
8506 
8507     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8508     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8509         .addJumpTableIndex(MJTI)
8510         .add(predOps(ARMCC::AL));
8511 
8512     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8513     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8514         .addReg(NewVReg3, RegState::Kill)
8515         .addReg(NewVReg1)
8516         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8517         .add(predOps(ARMCC::AL))
8518         .add(condCodeOp());
8519 
8520     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8521       .addReg(NewVReg4, RegState::Kill)
8522       .addReg(NewVReg1)
8523       .addJumpTableIndex(MJTI);
8524   } else if (Subtarget->isThumb()) {
8525     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8526     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8527         .addFrameIndex(FI)
8528         .addImm(1)
8529         .addMemOperand(FIMMOLd)
8530         .add(predOps(ARMCC::AL));
8531 
8532     if (NumLPads < 256) {
8533       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8534           .addReg(NewVReg1)
8535           .addImm(NumLPads)
8536           .add(predOps(ARMCC::AL));
8537     } else {
8538       MachineConstantPool *ConstantPool = MF->getConstantPool();
8539       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8540       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8541 
8542       // MachineConstantPool wants an explicit alignment.
8543       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8544       if (Align == 0)
8545         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8546       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8547 
8548       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8549       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8550           .addReg(VReg1, RegState::Define)
8551           .addConstantPoolIndex(Idx)
8552           .add(predOps(ARMCC::AL));
8553       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8554           .addReg(NewVReg1)
8555           .addReg(VReg1)
8556           .add(predOps(ARMCC::AL));
8557     }
8558 
8559     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8560       .addMBB(TrapBB)
8561       .addImm(ARMCC::HI)
8562       .addReg(ARM::CPSR);
8563 
8564     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8565     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8566         .addReg(ARM::CPSR, RegState::Define)
8567         .addReg(NewVReg1)
8568         .addImm(2)
8569         .add(predOps(ARMCC::AL));
8570 
8571     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8572     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8573         .addJumpTableIndex(MJTI)
8574         .add(predOps(ARMCC::AL));
8575 
8576     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8577     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8578         .addReg(ARM::CPSR, RegState::Define)
8579         .addReg(NewVReg2, RegState::Kill)
8580         .addReg(NewVReg3)
8581         .add(predOps(ARMCC::AL));
8582 
8583     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8584         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8585 
8586     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8587     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8588         .addReg(NewVReg4, RegState::Kill)
8589         .addImm(0)
8590         .addMemOperand(JTMMOLd)
8591         .add(predOps(ARMCC::AL));
8592 
8593     unsigned NewVReg6 = NewVReg5;
8594     if (IsPositionIndependent) {
8595       NewVReg6 = MRI->createVirtualRegister(TRC);
8596       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8597           .addReg(ARM::CPSR, RegState::Define)
8598           .addReg(NewVReg5, RegState::Kill)
8599           .addReg(NewVReg3)
8600           .add(predOps(ARMCC::AL));
8601     }
8602 
8603     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8604       .addReg(NewVReg6, RegState::Kill)
8605       .addJumpTableIndex(MJTI);
8606   } else {
8607     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8608     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8609         .addFrameIndex(FI)
8610         .addImm(4)
8611         .addMemOperand(FIMMOLd)
8612         .add(predOps(ARMCC::AL));
8613 
8614     if (NumLPads < 256) {
8615       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8616           .addReg(NewVReg1)
8617           .addImm(NumLPads)
8618           .add(predOps(ARMCC::AL));
8619     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8620       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8621       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8622           .addImm(NumLPads & 0xFFFF)
8623           .add(predOps(ARMCC::AL));
8624 
8625       unsigned VReg2 = VReg1;
8626       if ((NumLPads & 0xFFFF0000) != 0) {
8627         VReg2 = MRI->createVirtualRegister(TRC);
8628         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8629             .addReg(VReg1)
8630             .addImm(NumLPads >> 16)
8631             .add(predOps(ARMCC::AL));
8632       }
8633 
8634       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8635           .addReg(NewVReg1)
8636           .addReg(VReg2)
8637           .add(predOps(ARMCC::AL));
8638     } else {
8639       MachineConstantPool *ConstantPool = MF->getConstantPool();
8640       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8641       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8642 
8643       // MachineConstantPool wants an explicit alignment.
8644       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8645       if (Align == 0)
8646         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8647       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8648 
8649       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8650       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8651           .addReg(VReg1, RegState::Define)
8652           .addConstantPoolIndex(Idx)
8653           .addImm(0)
8654           .add(predOps(ARMCC::AL));
8655       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8656           .addReg(NewVReg1)
8657           .addReg(VReg1, RegState::Kill)
8658           .add(predOps(ARMCC::AL));
8659     }
8660 
8661     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8662       .addMBB(TrapBB)
8663       .addImm(ARMCC::HI)
8664       .addReg(ARM::CPSR);
8665 
8666     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8667     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8668         .addReg(NewVReg1)
8669         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8670         .add(predOps(ARMCC::AL))
8671         .add(condCodeOp());
8672     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8673     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8674         .addJumpTableIndex(MJTI)
8675         .add(predOps(ARMCC::AL));
8676 
8677     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8678         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8679     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8680     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8681         .addReg(NewVReg3, RegState::Kill)
8682         .addReg(NewVReg4)
8683         .addImm(0)
8684         .addMemOperand(JTMMOLd)
8685         .add(predOps(ARMCC::AL));
8686 
8687     if (IsPositionIndependent) {
8688       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8689         .addReg(NewVReg5, RegState::Kill)
8690         .addReg(NewVReg4)
8691         .addJumpTableIndex(MJTI);
8692     } else {
8693       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8694         .addReg(NewVReg5, RegState::Kill)
8695         .addJumpTableIndex(MJTI);
8696     }
8697   }
8698 
8699   // Add the jump table entries as successors to the MBB.
8700   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8701   for (std::vector<MachineBasicBlock*>::iterator
8702          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8703     MachineBasicBlock *CurMBB = *I;
8704     if (SeenMBBs.insert(CurMBB).second)
8705       DispContBB->addSuccessor(CurMBB);
8706   }
8707 
8708   // N.B. the order the invoke BBs are processed in doesn't matter here.
8709   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8710   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8711   for (MachineBasicBlock *BB : InvokeBBs) {
8712 
8713     // Remove the landing pad successor from the invoke block and replace it
8714     // with the new dispatch block.
8715     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8716                                                   BB->succ_end());
8717     while (!Successors.empty()) {
8718       MachineBasicBlock *SMBB = Successors.pop_back_val();
8719       if (SMBB->isEHPad()) {
8720         BB->removeSuccessor(SMBB);
8721         MBBLPads.push_back(SMBB);
8722       }
8723     }
8724 
8725     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8726     BB->normalizeSuccProbs();
8727 
8728     // Find the invoke call and mark all of the callee-saved registers as
8729     // 'implicit defined' so that they're spilled. This prevents code from
8730     // moving instructions to before the EH block, where they will never be
8731     // executed.
8732     for (MachineBasicBlock::reverse_iterator
8733            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8734       if (!II->isCall()) continue;
8735 
8736       DenseMap<unsigned, bool> DefRegs;
8737       for (MachineInstr::mop_iterator
8738              OI = II->operands_begin(), OE = II->operands_end();
8739            OI != OE; ++OI) {
8740         if (!OI->isReg()) continue;
8741         DefRegs[OI->getReg()] = true;
8742       }
8743 
8744       MachineInstrBuilder MIB(*MF, &*II);
8745 
8746       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8747         unsigned Reg = SavedRegs[i];
8748         if (Subtarget->isThumb2() &&
8749             !ARM::tGPRRegClass.contains(Reg) &&
8750             !ARM::hGPRRegClass.contains(Reg))
8751           continue;
8752         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8753           continue;
8754         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8755           continue;
8756         if (!DefRegs[Reg])
8757           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8758       }
8759 
8760       break;
8761     }
8762   }
8763 
8764   // Mark all former landing pads as non-landing pads. The dispatch is the only
8765   // landing pad now.
8766   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8767          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8768     (*I)->setIsEHPad(false);
8769 
8770   // The instruction is gone now.
8771   MI.eraseFromParent();
8772 }
8773 
8774 static
8775 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8776   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8777        E = MBB->succ_end(); I != E; ++I)
8778     if (*I != Succ)
8779       return *I;
8780   llvm_unreachable("Expecting a BB with two successors!");
8781 }
8782 
8783 /// Return the load opcode for a given load size. If load size >= 8,
8784 /// neon opcode will be returned.
8785 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8786   if (LdSize >= 8)
8787     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8788                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8789   if (IsThumb1)
8790     return LdSize == 4 ? ARM::tLDRi
8791                        : LdSize == 2 ? ARM::tLDRHi
8792                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8793   if (IsThumb2)
8794     return LdSize == 4 ? ARM::t2LDR_POST
8795                        : LdSize == 2 ? ARM::t2LDRH_POST
8796                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8797   return LdSize == 4 ? ARM::LDR_POST_IMM
8798                      : LdSize == 2 ? ARM::LDRH_POST
8799                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8800 }
8801 
8802 /// Return the store opcode for a given store size. If store size >= 8,
8803 /// neon opcode will be returned.
8804 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8805   if (StSize >= 8)
8806     return StSize == 16 ? ARM::VST1q32wb_fixed
8807                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8808   if (IsThumb1)
8809     return StSize == 4 ? ARM::tSTRi
8810                        : StSize == 2 ? ARM::tSTRHi
8811                                      : StSize == 1 ? ARM::tSTRBi : 0;
8812   if (IsThumb2)
8813     return StSize == 4 ? ARM::t2STR_POST
8814                        : StSize == 2 ? ARM::t2STRH_POST
8815                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8816   return StSize == 4 ? ARM::STR_POST_IMM
8817                      : StSize == 2 ? ARM::STRH_POST
8818                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8819 }
8820 
8821 /// Emit a post-increment load operation with given size. The instructions
8822 /// will be added to BB at Pos.
8823 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8824                        const TargetInstrInfo *TII, const DebugLoc &dl,
8825                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8826                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8827   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8828   assert(LdOpc != 0 && "Should have a load opcode");
8829   if (LdSize >= 8) {
8830     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8831         .addReg(AddrOut, RegState::Define)
8832         .addReg(AddrIn)
8833         .addImm(0)
8834         .add(predOps(ARMCC::AL));
8835   } else if (IsThumb1) {
8836     // load + update AddrIn
8837     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8838         .addReg(AddrIn)
8839         .addImm(0)
8840         .add(predOps(ARMCC::AL));
8841     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8842         .add(t1CondCodeOp())
8843         .addReg(AddrIn)
8844         .addImm(LdSize)
8845         .add(predOps(ARMCC::AL));
8846   } else if (IsThumb2) {
8847     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8848         .addReg(AddrOut, RegState::Define)
8849         .addReg(AddrIn)
8850         .addImm(LdSize)
8851         .add(predOps(ARMCC::AL));
8852   } else { // arm
8853     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8854         .addReg(AddrOut, RegState::Define)
8855         .addReg(AddrIn)
8856         .addReg(0)
8857         .addImm(LdSize)
8858         .add(predOps(ARMCC::AL));
8859   }
8860 }
8861 
8862 /// Emit a post-increment store operation with given size. The instructions
8863 /// will be added to BB at Pos.
8864 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8865                        const TargetInstrInfo *TII, const DebugLoc &dl,
8866                        unsigned StSize, unsigned Data, unsigned AddrIn,
8867                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8868   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8869   assert(StOpc != 0 && "Should have a store opcode");
8870   if (StSize >= 8) {
8871     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8872         .addReg(AddrIn)
8873         .addImm(0)
8874         .addReg(Data)
8875         .add(predOps(ARMCC::AL));
8876   } else if (IsThumb1) {
8877     // store + update AddrIn
8878     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8879         .addReg(Data)
8880         .addReg(AddrIn)
8881         .addImm(0)
8882         .add(predOps(ARMCC::AL));
8883     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8884         .add(t1CondCodeOp())
8885         .addReg(AddrIn)
8886         .addImm(StSize)
8887         .add(predOps(ARMCC::AL));
8888   } else if (IsThumb2) {
8889     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8890         .addReg(Data)
8891         .addReg(AddrIn)
8892         .addImm(StSize)
8893         .add(predOps(ARMCC::AL));
8894   } else { // arm
8895     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8896         .addReg(Data)
8897         .addReg(AddrIn)
8898         .addReg(0)
8899         .addImm(StSize)
8900         .add(predOps(ARMCC::AL));
8901   }
8902 }
8903 
8904 MachineBasicBlock *
8905 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8906                                    MachineBasicBlock *BB) const {
8907   // This pseudo instruction has 3 operands: dst, src, size
8908   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8909   // Otherwise, we will generate unrolled scalar copies.
8910   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8911   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8912   MachineFunction::iterator It = ++BB->getIterator();
8913 
8914   unsigned dest = MI.getOperand(0).getReg();
8915   unsigned src = MI.getOperand(1).getReg();
8916   unsigned SizeVal = MI.getOperand(2).getImm();
8917   unsigned Align = MI.getOperand(3).getImm();
8918   DebugLoc dl = MI.getDebugLoc();
8919 
8920   MachineFunction *MF = BB->getParent();
8921   MachineRegisterInfo &MRI = MF->getRegInfo();
8922   unsigned UnitSize = 0;
8923   const TargetRegisterClass *TRC = nullptr;
8924   const TargetRegisterClass *VecTRC = nullptr;
8925 
8926   bool IsThumb1 = Subtarget->isThumb1Only();
8927   bool IsThumb2 = Subtarget->isThumb2();
8928   bool IsThumb = Subtarget->isThumb();
8929 
8930   if (Align & 1) {
8931     UnitSize = 1;
8932   } else if (Align & 2) {
8933     UnitSize = 2;
8934   } else {
8935     // Check whether we can use NEON instructions.
8936     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
8937         Subtarget->hasNEON()) {
8938       if ((Align % 16 == 0) && SizeVal >= 16)
8939         UnitSize = 16;
8940       else if ((Align % 8 == 0) && SizeVal >= 8)
8941         UnitSize = 8;
8942     }
8943     // Can't use NEON instructions.
8944     if (UnitSize == 0)
8945       UnitSize = 4;
8946   }
8947 
8948   // Select the correct opcode and register class for unit size load/store
8949   bool IsNeon = UnitSize >= 8;
8950   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8951   if (IsNeon)
8952     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8953                             : UnitSize == 8 ? &ARM::DPRRegClass
8954                                             : nullptr;
8955 
8956   unsigned BytesLeft = SizeVal % UnitSize;
8957   unsigned LoopSize = SizeVal - BytesLeft;
8958 
8959   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8960     // Use LDR and STR to copy.
8961     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8962     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8963     unsigned srcIn = src;
8964     unsigned destIn = dest;
8965     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8966       unsigned srcOut = MRI.createVirtualRegister(TRC);
8967       unsigned destOut = MRI.createVirtualRegister(TRC);
8968       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8969       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8970                  IsThumb1, IsThumb2);
8971       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8972                  IsThumb1, IsThumb2);
8973       srcIn = srcOut;
8974       destIn = destOut;
8975     }
8976 
8977     // Handle the leftover bytes with LDRB and STRB.
8978     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8979     // [destOut] = STRB_POST(scratch, destIn, 1)
8980     for (unsigned i = 0; i < BytesLeft; i++) {
8981       unsigned srcOut = MRI.createVirtualRegister(TRC);
8982       unsigned destOut = MRI.createVirtualRegister(TRC);
8983       unsigned scratch = MRI.createVirtualRegister(TRC);
8984       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8985                  IsThumb1, IsThumb2);
8986       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8987                  IsThumb1, IsThumb2);
8988       srcIn = srcOut;
8989       destIn = destOut;
8990     }
8991     MI.eraseFromParent(); // The instruction is gone now.
8992     return BB;
8993   }
8994 
8995   // Expand the pseudo op to a loop.
8996   // thisMBB:
8997   //   ...
8998   //   movw varEnd, # --> with thumb2
8999   //   movt varEnd, #
9000   //   ldrcp varEnd, idx --> without thumb2
9001   //   fallthrough --> loopMBB
9002   // loopMBB:
9003   //   PHI varPhi, varEnd, varLoop
9004   //   PHI srcPhi, src, srcLoop
9005   //   PHI destPhi, dst, destLoop
9006   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9007   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
9008   //   subs varLoop, varPhi, #UnitSize
9009   //   bne loopMBB
9010   //   fallthrough --> exitMBB
9011   // exitMBB:
9012   //   epilogue to handle left-over bytes
9013   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9014   //   [destOut] = STRB_POST(scratch, destLoop, 1)
9015   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9016   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
9017   MF->insert(It, loopMBB);
9018   MF->insert(It, exitMBB);
9019 
9020   // Transfer the remainder of BB and its successor edges to exitMBB.
9021   exitMBB->splice(exitMBB->begin(), BB,
9022                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
9023   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
9024 
9025   // Load an immediate to varEnd.
9026   unsigned varEnd = MRI.createVirtualRegister(TRC);
9027   if (Subtarget->useMovt(*MF)) {
9028     unsigned Vtmp = varEnd;
9029     if ((LoopSize & 0xFFFF0000) != 0)
9030       Vtmp = MRI.createVirtualRegister(TRC);
9031     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
9032         .addImm(LoopSize & 0xFFFF)
9033         .add(predOps(ARMCC::AL));
9034 
9035     if ((LoopSize & 0xFFFF0000) != 0)
9036       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
9037           .addReg(Vtmp)
9038           .addImm(LoopSize >> 16)
9039           .add(predOps(ARMCC::AL));
9040   } else {
9041     MachineConstantPool *ConstantPool = MF->getConstantPool();
9042     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
9043     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
9044 
9045     // MachineConstantPool wants an explicit alignment.
9046     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
9047     if (Align == 0)
9048       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
9049     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
9050 
9051     if (IsThumb)
9052       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
9053           .addReg(varEnd, RegState::Define)
9054           .addConstantPoolIndex(Idx)
9055           .add(predOps(ARMCC::AL));
9056     else
9057       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
9058           .addReg(varEnd, RegState::Define)
9059           .addConstantPoolIndex(Idx)
9060           .addImm(0)
9061           .add(predOps(ARMCC::AL));
9062   }
9063   BB->addSuccessor(loopMBB);
9064 
9065   // Generate the loop body:
9066   //   varPhi = PHI(varLoop, varEnd)
9067   //   srcPhi = PHI(srcLoop, src)
9068   //   destPhi = PHI(destLoop, dst)
9069   MachineBasicBlock *entryBB = BB;
9070   BB = loopMBB;
9071   unsigned varLoop = MRI.createVirtualRegister(TRC);
9072   unsigned varPhi = MRI.createVirtualRegister(TRC);
9073   unsigned srcLoop = MRI.createVirtualRegister(TRC);
9074   unsigned srcPhi = MRI.createVirtualRegister(TRC);
9075   unsigned destLoop = MRI.createVirtualRegister(TRC);
9076   unsigned destPhi = MRI.createVirtualRegister(TRC);
9077 
9078   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
9079     .addReg(varLoop).addMBB(loopMBB)
9080     .addReg(varEnd).addMBB(entryBB);
9081   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
9082     .addReg(srcLoop).addMBB(loopMBB)
9083     .addReg(src).addMBB(entryBB);
9084   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
9085     .addReg(destLoop).addMBB(loopMBB)
9086     .addReg(dest).addMBB(entryBB);
9087 
9088   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
9089   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
9090   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
9091   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
9092              IsThumb1, IsThumb2);
9093   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
9094              IsThumb1, IsThumb2);
9095 
9096   // Decrement loop variable by UnitSize.
9097   if (IsThumb1) {
9098     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
9099         .add(t1CondCodeOp())
9100         .addReg(varPhi)
9101         .addImm(UnitSize)
9102         .add(predOps(ARMCC::AL));
9103   } else {
9104     MachineInstrBuilder MIB =
9105         BuildMI(*BB, BB->end(), dl,
9106                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
9107     MIB.addReg(varPhi)
9108         .addImm(UnitSize)
9109         .add(predOps(ARMCC::AL))
9110         .add(condCodeOp());
9111     MIB->getOperand(5).setReg(ARM::CPSR);
9112     MIB->getOperand(5).setIsDef(true);
9113   }
9114   BuildMI(*BB, BB->end(), dl,
9115           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
9116       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
9117 
9118   // loopMBB can loop back to loopMBB or fall through to exitMBB.
9119   BB->addSuccessor(loopMBB);
9120   BB->addSuccessor(exitMBB);
9121 
9122   // Add epilogue to handle BytesLeft.
9123   BB = exitMBB;
9124   auto StartOfExit = exitMBB->begin();
9125 
9126   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
9127   //   [destOut] = STRB_POST(scratch, destLoop, 1)
9128   unsigned srcIn = srcLoop;
9129   unsigned destIn = destLoop;
9130   for (unsigned i = 0; i < BytesLeft; i++) {
9131     unsigned srcOut = MRI.createVirtualRegister(TRC);
9132     unsigned destOut = MRI.createVirtualRegister(TRC);
9133     unsigned scratch = MRI.createVirtualRegister(TRC);
9134     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
9135                IsThumb1, IsThumb2);
9136     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
9137                IsThumb1, IsThumb2);
9138     srcIn = srcOut;
9139     destIn = destOut;
9140   }
9141 
9142   MI.eraseFromParent(); // The instruction is gone now.
9143   return BB;
9144 }
9145 
9146 MachineBasicBlock *
9147 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
9148                                        MachineBasicBlock *MBB) const {
9149   const TargetMachine &TM = getTargetMachine();
9150   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
9151   DebugLoc DL = MI.getDebugLoc();
9152 
9153   assert(Subtarget->isTargetWindows() &&
9154          "__chkstk is only supported on Windows");
9155   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
9156 
9157   // __chkstk takes the number of words to allocate on the stack in R4, and
9158   // returns the stack adjustment in number of bytes in R4.  This will not
9159   // clober any other registers (other than the obvious lr).
9160   //
9161   // Although, technically, IP should be considered a register which may be
9162   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
9163   // thumb-2 environment, so there is no interworking required.  As a result, we
9164   // do not expect a veneer to be emitted by the linker, clobbering IP.
9165   //
9166   // Each module receives its own copy of __chkstk, so no import thunk is
9167   // required, again, ensuring that IP is not clobbered.
9168   //
9169   // Finally, although some linkers may theoretically provide a trampoline for
9170   // out of range calls (which is quite common due to a 32M range limitation of
9171   // branches for Thumb), we can generate the long-call version via
9172   // -mcmodel=large, alleviating the need for the trampoline which may clobber
9173   // IP.
9174 
9175   switch (TM.getCodeModel()) {
9176   case CodeModel::Small:
9177   case CodeModel::Medium:
9178   case CodeModel::Kernel:
9179     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
9180         .add(predOps(ARMCC::AL))
9181         .addExternalSymbol("__chkstk")
9182         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9183         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9184         .addReg(ARM::R12,
9185                 RegState::Implicit | RegState::Define | RegState::Dead)
9186         .addReg(ARM::CPSR,
9187                 RegState::Implicit | RegState::Define | RegState::Dead);
9188     break;
9189   case CodeModel::Large: {
9190     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9191     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
9192 
9193     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
9194       .addExternalSymbol("__chkstk");
9195     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
9196         .add(predOps(ARMCC::AL))
9197         .addReg(Reg, RegState::Kill)
9198         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9199         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9200         .addReg(ARM::R12,
9201                 RegState::Implicit | RegState::Define | RegState::Dead)
9202         .addReg(ARM::CPSR,
9203                 RegState::Implicit | RegState::Define | RegState::Dead);
9204     break;
9205   }
9206   }
9207 
9208   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
9209       .addReg(ARM::SP, RegState::Kill)
9210       .addReg(ARM::R4, RegState::Kill)
9211       .setMIFlags(MachineInstr::FrameSetup)
9212       .add(predOps(ARMCC::AL))
9213       .add(condCodeOp());
9214 
9215   MI.eraseFromParent();
9216   return MBB;
9217 }
9218 
9219 MachineBasicBlock *
9220 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
9221                                        MachineBasicBlock *MBB) const {
9222   DebugLoc DL = MI.getDebugLoc();
9223   MachineFunction *MF = MBB->getParent();
9224   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9225 
9226   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
9227   MF->insert(++MBB->getIterator(), ContBB);
9228   ContBB->splice(ContBB->begin(), MBB,
9229                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9230   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
9231   MBB->addSuccessor(ContBB);
9232 
9233   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9234   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
9235   MF->push_back(TrapBB);
9236   MBB->addSuccessor(TrapBB);
9237 
9238   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
9239       .addReg(MI.getOperand(0).getReg())
9240       .addImm(0)
9241       .add(predOps(ARMCC::AL));
9242   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
9243       .addMBB(TrapBB)
9244       .addImm(ARMCC::EQ)
9245       .addReg(ARM::CPSR);
9246 
9247   MI.eraseFromParent();
9248   return ContBB;
9249 }
9250 
9251 MachineBasicBlock *
9252 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9253                                                MachineBasicBlock *BB) const {
9254   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9255   DebugLoc dl = MI.getDebugLoc();
9256   bool isThumb2 = Subtarget->isThumb2();
9257   switch (MI.getOpcode()) {
9258   default: {
9259     MI.print(errs());
9260     llvm_unreachable("Unexpected instr type to insert");
9261   }
9262 
9263   // Thumb1 post-indexed loads are really just single-register LDMs.
9264   case ARM::tLDR_postidx: {
9265     MachineOperand Def(MI.getOperand(1));
9266     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
9267         .add(Def)  // Rn_wb
9268         .add(MI.getOperand(2))  // Rn
9269         .add(MI.getOperand(3))  // PredImm
9270         .add(MI.getOperand(4))  // PredReg
9271         .add(MI.getOperand(0)); // Rt
9272     MI.eraseFromParent();
9273     return BB;
9274   }
9275 
9276   // The Thumb2 pre-indexed stores have the same MI operands, they just
9277   // define them differently in the .td files from the isel patterns, so
9278   // they need pseudos.
9279   case ARM::t2STR_preidx:
9280     MI.setDesc(TII->get(ARM::t2STR_PRE));
9281     return BB;
9282   case ARM::t2STRB_preidx:
9283     MI.setDesc(TII->get(ARM::t2STRB_PRE));
9284     return BB;
9285   case ARM::t2STRH_preidx:
9286     MI.setDesc(TII->get(ARM::t2STRH_PRE));
9287     return BB;
9288 
9289   case ARM::STRi_preidx:
9290   case ARM::STRBi_preidx: {
9291     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9292                                                          : ARM::STRB_PRE_IMM;
9293     // Decode the offset.
9294     unsigned Offset = MI.getOperand(4).getImm();
9295     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
9296     Offset = ARM_AM::getAM2Offset(Offset);
9297     if (isSub)
9298       Offset = -Offset;
9299 
9300     MachineMemOperand *MMO = *MI.memoperands_begin();
9301     BuildMI(*BB, MI, dl, TII->get(NewOpc))
9302         .add(MI.getOperand(0)) // Rn_wb
9303         .add(MI.getOperand(1)) // Rt
9304         .add(MI.getOperand(2)) // Rn
9305         .addImm(Offset)        // offset (skip GPR==zero_reg)
9306         .add(MI.getOperand(5)) // pred
9307         .add(MI.getOperand(6))
9308         .addMemOperand(MMO);
9309     MI.eraseFromParent();
9310     return BB;
9311   }
9312   case ARM::STRr_preidx:
9313   case ARM::STRBr_preidx:
9314   case ARM::STRH_preidx: {
9315     unsigned NewOpc;
9316     switch (MI.getOpcode()) {
9317     default: llvm_unreachable("unexpected opcode!");
9318     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
9319     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
9320     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
9321     }
9322     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
9323     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
9324       MIB.add(MI.getOperand(i));
9325     MI.eraseFromParent();
9326     return BB;
9327   }
9328 
9329   case ARM::tMOVCCr_pseudo: {
9330     // To "insert" a SELECT_CC instruction, we actually have to insert the
9331     // diamond control-flow pattern.  The incoming instruction knows the
9332     // destination vreg to set, the condition code register to branch on, the
9333     // true/false values to select between, and a branch opcode to use.
9334     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9335     MachineFunction::iterator It = ++BB->getIterator();
9336 
9337     //  thisMBB:
9338     //  ...
9339     //   TrueVal = ...
9340     //   cmpTY ccX, r1, r2
9341     //   bCC copy1MBB
9342     //   fallthrough --> copy0MBB
9343     MachineBasicBlock *thisMBB  = BB;
9344     MachineFunction *F = BB->getParent();
9345     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9346     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
9347     F->insert(It, copy0MBB);
9348     F->insert(It, sinkMBB);
9349 
9350     // Transfer the remainder of BB and its successor edges to sinkMBB.
9351     sinkMBB->splice(sinkMBB->begin(), BB,
9352                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9353     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9354 
9355     BB->addSuccessor(copy0MBB);
9356     BB->addSuccessor(sinkMBB);
9357 
9358     BuildMI(BB, dl, TII->get(ARM::tBcc))
9359         .addMBB(sinkMBB)
9360         .addImm(MI.getOperand(3).getImm())
9361         .addReg(MI.getOperand(4).getReg());
9362 
9363     //  copy0MBB:
9364     //   %FalseValue = ...
9365     //   # fallthrough to sinkMBB
9366     BB = copy0MBB;
9367 
9368     // Update machine-CFG edges
9369     BB->addSuccessor(sinkMBB);
9370 
9371     //  sinkMBB:
9372     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9373     //  ...
9374     BB = sinkMBB;
9375     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
9376         .addReg(MI.getOperand(1).getReg())
9377         .addMBB(copy0MBB)
9378         .addReg(MI.getOperand(2).getReg())
9379         .addMBB(thisMBB);
9380 
9381     MI.eraseFromParent(); // The pseudo instruction is gone now.
9382     return BB;
9383   }
9384 
9385   case ARM::BCCi64:
9386   case ARM::BCCZi64: {
9387     // If there is an unconditional branch to the other successor, remove it.
9388     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9389 
9390     // Compare both parts that make up the double comparison separately for
9391     // equality.
9392     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9393 
9394     unsigned LHS1 = MI.getOperand(1).getReg();
9395     unsigned LHS2 = MI.getOperand(2).getReg();
9396     if (RHSisZero) {
9397       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9398           .addReg(LHS1)
9399           .addImm(0)
9400           .add(predOps(ARMCC::AL));
9401       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9402         .addReg(LHS2).addImm(0)
9403         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9404     } else {
9405       unsigned RHS1 = MI.getOperand(3).getReg();
9406       unsigned RHS2 = MI.getOperand(4).getReg();
9407       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9408           .addReg(LHS1)
9409           .addReg(RHS1)
9410           .add(predOps(ARMCC::AL));
9411       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9412         .addReg(LHS2).addReg(RHS2)
9413         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9414     }
9415 
9416     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9417     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9418     if (MI.getOperand(0).getImm() == ARMCC::NE)
9419       std::swap(destMBB, exitMBB);
9420 
9421     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9422       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9423     if (isThumb2)
9424       BuildMI(BB, dl, TII->get(ARM::t2B))
9425           .addMBB(exitMBB)
9426           .add(predOps(ARMCC::AL));
9427     else
9428       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9429 
9430     MI.eraseFromParent(); // The pseudo instruction is gone now.
9431     return BB;
9432   }
9433 
9434   case ARM::Int_eh_sjlj_setjmp:
9435   case ARM::Int_eh_sjlj_setjmp_nofp:
9436   case ARM::tInt_eh_sjlj_setjmp:
9437   case ARM::t2Int_eh_sjlj_setjmp:
9438   case ARM::t2Int_eh_sjlj_setjmp_nofp:
9439     return BB;
9440 
9441   case ARM::Int_eh_sjlj_setup_dispatch:
9442     EmitSjLjDispatchBlock(MI, BB);
9443     return BB;
9444 
9445   case ARM::ABS:
9446   case ARM::t2ABS: {
9447     // To insert an ABS instruction, we have to insert the
9448     // diamond control-flow pattern.  The incoming instruction knows the
9449     // source vreg to test against 0, the destination vreg to set,
9450     // the condition code register to branch on, the
9451     // true/false values to select between, and a branch opcode to use.
9452     // It transforms
9453     //     V1 = ABS V0
9454     // into
9455     //     V2 = MOVS V0
9456     //     BCC                      (branch to SinkBB if V0 >= 0)
9457     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
9458     //     SinkBB: V1 = PHI(V2, V3)
9459     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9460     MachineFunction::iterator BBI = ++BB->getIterator();
9461     MachineFunction *Fn = BB->getParent();
9462     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9463     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
9464     Fn->insert(BBI, RSBBB);
9465     Fn->insert(BBI, SinkBB);
9466 
9467     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9468     unsigned int ABSDstReg = MI.getOperand(0).getReg();
9469     bool ABSSrcKIll = MI.getOperand(1).isKill();
9470     bool isThumb2 = Subtarget->isThumb2();
9471     MachineRegisterInfo &MRI = Fn->getRegInfo();
9472     // In Thumb mode S must not be specified if source register is the SP or
9473     // PC and if destination register is the SP, so restrict register class
9474     unsigned NewRsbDstReg =
9475       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9476 
9477     // Transfer the remainder of BB and its successor edges to sinkMBB.
9478     SinkBB->splice(SinkBB->begin(), BB,
9479                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9480     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9481 
9482     BB->addSuccessor(RSBBB);
9483     BB->addSuccessor(SinkBB);
9484 
9485     // fall through to SinkMBB
9486     RSBBB->addSuccessor(SinkBB);
9487 
9488     // insert a cmp at the end of BB
9489     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9490         .addReg(ABSSrcReg)
9491         .addImm(0)
9492         .add(predOps(ARMCC::AL));
9493 
9494     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9495     BuildMI(BB, dl,
9496       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9497       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9498 
9499     // insert rsbri in RSBBB
9500     // Note: BCC and rsbri will be converted into predicated rsbmi
9501     // by if-conversion pass
9502     BuildMI(*RSBBB, RSBBB->begin(), dl,
9503             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9504         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9505         .addImm(0)
9506         .add(predOps(ARMCC::AL))
9507         .add(condCodeOp());
9508 
9509     // insert PHI in SinkBB,
9510     // reuse ABSDstReg to not change uses of ABS instruction
9511     BuildMI(*SinkBB, SinkBB->begin(), dl,
9512       TII->get(ARM::PHI), ABSDstReg)
9513       .addReg(NewRsbDstReg).addMBB(RSBBB)
9514       .addReg(ABSSrcReg).addMBB(BB);
9515 
9516     // remove ABS instruction
9517     MI.eraseFromParent();
9518 
9519     // return last added BB
9520     return SinkBB;
9521   }
9522   case ARM::COPY_STRUCT_BYVAL_I32:
9523     ++NumLoopByVals;
9524     return EmitStructByval(MI, BB);
9525   case ARM::WIN__CHKSTK:
9526     return EmitLowered__chkstk(MI, BB);
9527   case ARM::WIN__DBZCHK:
9528     return EmitLowered__dbzchk(MI, BB);
9529   }
9530 }
9531 
9532 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
9533 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9534 /// instead of as a custom inserter because we need the use list from the SDNode.
9535 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9536                                     MachineInstr &MI, const SDNode *Node) {
9537   bool isThumb1 = Subtarget->isThumb1Only();
9538 
9539   DebugLoc DL = MI.getDebugLoc();
9540   MachineFunction *MF = MI.getParent()->getParent();
9541   MachineRegisterInfo &MRI = MF->getRegInfo();
9542   MachineInstrBuilder MIB(*MF, MI);
9543 
9544   // If the new dst/src is unused mark it as dead.
9545   if (!Node->hasAnyUseOfValue(0)) {
9546     MI.getOperand(0).setIsDead(true);
9547   }
9548   if (!Node->hasAnyUseOfValue(1)) {
9549     MI.getOperand(1).setIsDead(true);
9550   }
9551 
9552   // The MEMCPY both defines and kills the scratch registers.
9553   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9554     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9555                                                          : &ARM::GPRRegClass);
9556     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9557   }
9558 }
9559 
9560 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9561                                                       SDNode *Node) const {
9562   if (MI.getOpcode() == ARM::MEMCPY) {
9563     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9564     return;
9565   }
9566 
9567   const MCInstrDesc *MCID = &MI.getDesc();
9568   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9569   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9570   // operand is still set to noreg. If needed, set the optional operand's
9571   // register to CPSR, and remove the redundant implicit def.
9572   //
9573   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
9574 
9575   // Rename pseudo opcodes.
9576   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9577   unsigned ccOutIdx;
9578   if (NewOpc) {
9579     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9580     MCID = &TII->get(NewOpc);
9581 
9582     assert(MCID->getNumOperands() ==
9583            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9584         && "converted opcode should be the same except for cc_out"
9585            " (and, on Thumb1, pred)");
9586 
9587     MI.setDesc(*MCID);
9588 
9589     // Add the optional cc_out operand
9590     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9591 
9592     // On Thumb1, move all input operands to the end, then add the predicate
9593     if (Subtarget->isThumb1Only()) {
9594       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9595         MI.addOperand(MI.getOperand(1));
9596         MI.RemoveOperand(1);
9597       }
9598 
9599       // Restore the ties
9600       for (unsigned i = MI.getNumOperands(); i--;) {
9601         const MachineOperand& op = MI.getOperand(i);
9602         if (op.isReg() && op.isUse()) {
9603           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9604           if (DefIdx != -1)
9605             MI.tieOperands(DefIdx, i);
9606         }
9607       }
9608 
9609       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9610       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9611       ccOutIdx = 1;
9612     } else
9613       ccOutIdx = MCID->getNumOperands() - 1;
9614   } else
9615     ccOutIdx = MCID->getNumOperands() - 1;
9616 
9617   // Any ARM instruction that sets the 's' bit should specify an optional
9618   // "cc_out" operand in the last operand position.
9619   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9620     assert(!NewOpc && "Optional cc_out operand required");
9621     return;
9622   }
9623   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9624   // since we already have an optional CPSR def.
9625   bool definesCPSR = false;
9626   bool deadCPSR = false;
9627   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9628        ++i) {
9629     const MachineOperand &MO = MI.getOperand(i);
9630     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9631       definesCPSR = true;
9632       if (MO.isDead())
9633         deadCPSR = true;
9634       MI.RemoveOperand(i);
9635       break;
9636     }
9637   }
9638   if (!definesCPSR) {
9639     assert(!NewOpc && "Optional cc_out operand required");
9640     return;
9641   }
9642   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9643   if (deadCPSR) {
9644     assert(!MI.getOperand(ccOutIdx).getReg() &&
9645            "expect uninitialized optional cc_out operand");
9646     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9647     if (!Subtarget->isThumb1Only())
9648       return;
9649   }
9650 
9651   // If this instruction was defined with an optional CPSR def and its dag node
9652   // had a live implicit CPSR def, then activate the optional CPSR def.
9653   MachineOperand &MO = MI.getOperand(ccOutIdx);
9654   MO.setReg(ARM::CPSR);
9655   MO.setIsDef(true);
9656 }
9657 
9658 //===----------------------------------------------------------------------===//
9659 //                           ARM Optimization Hooks
9660 //===----------------------------------------------------------------------===//
9661 
9662 // Helper function that checks if N is a null or all ones constant.
9663 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9664   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9665 }
9666 
9667 // Return true if N is conditionally 0 or all ones.
9668 // Detects these expressions where cc is an i1 value:
9669 //
9670 //   (select cc 0, y)   [AllOnes=0]
9671 //   (select cc y, 0)   [AllOnes=0]
9672 //   (zext cc)          [AllOnes=0]
9673 //   (sext cc)          [AllOnes=0/1]
9674 //   (select cc -1, y)  [AllOnes=1]
9675 //   (select cc y, -1)  [AllOnes=1]
9676 //
9677 // Invert is set when N is the null/all ones constant when CC is false.
9678 // OtherOp is set to the alternative value of N.
9679 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9680                                        SDValue &CC, bool &Invert,
9681                                        SDValue &OtherOp,
9682                                        SelectionDAG &DAG) {
9683   switch (N->getOpcode()) {
9684   default: return false;
9685   case ISD::SELECT: {
9686     CC = N->getOperand(0);
9687     SDValue N1 = N->getOperand(1);
9688     SDValue N2 = N->getOperand(2);
9689     if (isZeroOrAllOnes(N1, AllOnes)) {
9690       Invert = false;
9691       OtherOp = N2;
9692       return true;
9693     }
9694     if (isZeroOrAllOnes(N2, AllOnes)) {
9695       Invert = true;
9696       OtherOp = N1;
9697       return true;
9698     }
9699     return false;
9700   }
9701   case ISD::ZERO_EXTEND:
9702     // (zext cc) can never be the all ones value.
9703     if (AllOnes)
9704       return false;
9705     LLVM_FALLTHROUGH;
9706   case ISD::SIGN_EXTEND: {
9707     SDLoc dl(N);
9708     EVT VT = N->getValueType(0);
9709     CC = N->getOperand(0);
9710     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9711       return false;
9712     Invert = !AllOnes;
9713     if (AllOnes)
9714       // When looking for an AllOnes constant, N is an sext, and the 'other'
9715       // value is 0.
9716       OtherOp = DAG.getConstant(0, dl, VT);
9717     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9718       // When looking for a 0 constant, N can be zext or sext.
9719       OtherOp = DAG.getConstant(1, dl, VT);
9720     else
9721       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9722                                 VT);
9723     return true;
9724   }
9725   }
9726 }
9727 
9728 // Combine a constant select operand into its use:
9729 //
9730 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9731 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9732 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9733 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9734 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9735 //
9736 // The transform is rejected if the select doesn't have a constant operand that
9737 // is null, or all ones when AllOnes is set.
9738 //
9739 // Also recognize sext/zext from i1:
9740 //
9741 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9742 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9743 //
9744 // These transformations eventually create predicated instructions.
9745 //
9746 // @param N       The node to transform.
9747 // @param Slct    The N operand that is a select.
9748 // @param OtherOp The other N operand (x above).
9749 // @param DCI     Context.
9750 // @param AllOnes Require the select constant to be all ones instead of null.
9751 // @returns The new node, or SDValue() on failure.
9752 static
9753 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9754                             TargetLowering::DAGCombinerInfo &DCI,
9755                             bool AllOnes = false) {
9756   SelectionDAG &DAG = DCI.DAG;
9757   EVT VT = N->getValueType(0);
9758   SDValue NonConstantVal;
9759   SDValue CCOp;
9760   bool SwapSelectOps;
9761   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9762                                   NonConstantVal, DAG))
9763     return SDValue();
9764 
9765   // Slct is now know to be the desired identity constant when CC is true.
9766   SDValue TrueVal = OtherOp;
9767   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9768                                  OtherOp, NonConstantVal);
9769   // Unless SwapSelectOps says CC should be false.
9770   if (SwapSelectOps)
9771     std::swap(TrueVal, FalseVal);
9772 
9773   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9774                      CCOp, TrueVal, FalseVal);
9775 }
9776 
9777 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9778 static
9779 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9780                                        TargetLowering::DAGCombinerInfo &DCI) {
9781   SDValue N0 = N->getOperand(0);
9782   SDValue N1 = N->getOperand(1);
9783   if (N0.getNode()->hasOneUse())
9784     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9785       return Result;
9786   if (N1.getNode()->hasOneUse())
9787     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9788       return Result;
9789   return SDValue();
9790 }
9791 
9792 static bool IsVUZPShuffleNode(SDNode *N) {
9793   // VUZP shuffle node.
9794   if (N->getOpcode() == ARMISD::VUZP)
9795     return true;
9796 
9797   // "VUZP" on i32 is an alias for VTRN.
9798   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9799     return true;
9800 
9801   return false;
9802 }
9803 
9804 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9805                                  TargetLowering::DAGCombinerInfo &DCI,
9806                                  const ARMSubtarget *Subtarget) {
9807   // Look for ADD(VUZP.0, VUZP.1).
9808   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9809       N0 == N1)
9810    return SDValue();
9811 
9812   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9813   if (!N->getValueType(0).is64BitVector())
9814     return SDValue();
9815 
9816   // Generate vpadd.
9817   SelectionDAG &DAG = DCI.DAG;
9818   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9819   SDLoc dl(N);
9820   SDNode *Unzip = N0.getNode();
9821   EVT VT = N->getValueType(0);
9822 
9823   SmallVector<SDValue, 8> Ops;
9824   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9825                                 TLI.getPointerTy(DAG.getDataLayout())));
9826   Ops.push_back(Unzip->getOperand(0));
9827   Ops.push_back(Unzip->getOperand(1));
9828 
9829   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9830 }
9831 
9832 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9833                                       TargetLowering::DAGCombinerInfo &DCI,
9834                                       const ARMSubtarget *Subtarget) {
9835   // Check for two extended operands.
9836   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9837         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9838       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9839         N1.getOpcode() == ISD::ZERO_EXTEND))
9840     return SDValue();
9841 
9842   SDValue N00 = N0.getOperand(0);
9843   SDValue N10 = N1.getOperand(0);
9844 
9845   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9846   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9847       N00 == N10)
9848     return SDValue();
9849 
9850   // We only recognize Q register paddl here; this can't be reached until
9851   // after type legalization.
9852   if (!N00.getValueType().is64BitVector() ||
9853       !N0.getValueType().is128BitVector())
9854     return SDValue();
9855 
9856   // Generate vpaddl.
9857   SelectionDAG &DAG = DCI.DAG;
9858   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9859   SDLoc dl(N);
9860   EVT VT = N->getValueType(0);
9861 
9862   SmallVector<SDValue, 8> Ops;
9863   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9864   unsigned Opcode;
9865   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9866     Opcode = Intrinsic::arm_neon_vpaddls;
9867   else
9868     Opcode = Intrinsic::arm_neon_vpaddlu;
9869   Ops.push_back(DAG.getConstant(Opcode, dl,
9870                                 TLI.getPointerTy(DAG.getDataLayout())));
9871   EVT ElemTy = N00.getValueType().getVectorElementType();
9872   unsigned NumElts = VT.getVectorNumElements();
9873   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9874   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9875                                N00.getOperand(0), N00.getOperand(1));
9876   Ops.push_back(Concat);
9877 
9878   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9879 }
9880 
9881 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9882 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9883 // much easier to match.
9884 static SDValue
9885 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9886                                TargetLowering::DAGCombinerInfo &DCI,
9887                                const ARMSubtarget *Subtarget) {
9888   // Only perform optimization if after legalize, and if NEON is available. We
9889   // also expected both operands to be BUILD_VECTORs.
9890   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9891       || N0.getOpcode() != ISD::BUILD_VECTOR
9892       || N1.getOpcode() != ISD::BUILD_VECTOR)
9893     return SDValue();
9894 
9895   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9896   EVT VT = N->getValueType(0);
9897   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9898     return SDValue();
9899 
9900   // Check that the vector operands are of the right form.
9901   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9902   // operands, where N is the size of the formed vector.
9903   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9904   // index such that we have a pair wise add pattern.
9905 
9906   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9907   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9908     return SDValue();
9909   SDValue Vec = N0->getOperand(0)->getOperand(0);
9910   SDNode *V = Vec.getNode();
9911   unsigned nextIndex = 0;
9912 
9913   // For each operands to the ADD which are BUILD_VECTORs,
9914   // check to see if each of their operands are an EXTRACT_VECTOR with
9915   // the same vector and appropriate index.
9916   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9917     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9918         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9919 
9920       SDValue ExtVec0 = N0->getOperand(i);
9921       SDValue ExtVec1 = N1->getOperand(i);
9922 
9923       // First operand is the vector, verify its the same.
9924       if (V != ExtVec0->getOperand(0).getNode() ||
9925           V != ExtVec1->getOperand(0).getNode())
9926         return SDValue();
9927 
9928       // Second is the constant, verify its correct.
9929       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9930       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9931 
9932       // For the constant, we want to see all the even or all the odd.
9933       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9934           || C1->getZExtValue() != nextIndex+1)
9935         return SDValue();
9936 
9937       // Increment index.
9938       nextIndex+=2;
9939     } else
9940       return SDValue();
9941   }
9942 
9943   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9944   // we're using the entire input vector, otherwise there's a size/legality
9945   // mismatch somewhere.
9946   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9947       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9948     return SDValue();
9949 
9950   // Create VPADDL node.
9951   SelectionDAG &DAG = DCI.DAG;
9952   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9953 
9954   SDLoc dl(N);
9955 
9956   // Build operand list.
9957   SmallVector<SDValue, 8> Ops;
9958   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9959                                 TLI.getPointerTy(DAG.getDataLayout())));
9960 
9961   // Input is the vector.
9962   Ops.push_back(Vec);
9963 
9964   // Get widened type and narrowed type.
9965   MVT widenType;
9966   unsigned numElem = VT.getVectorNumElements();
9967 
9968   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9969   switch (inputLaneType.getSimpleVT().SimpleTy) {
9970     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9971     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9972     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9973     default:
9974       llvm_unreachable("Invalid vector element type for padd optimization.");
9975   }
9976 
9977   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9978   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9979   return DAG.getNode(ExtOp, dl, VT, tmp);
9980 }
9981 
9982 static SDValue findMUL_LOHI(SDValue V) {
9983   if (V->getOpcode() == ISD::UMUL_LOHI ||
9984       V->getOpcode() == ISD::SMUL_LOHI)
9985     return V;
9986   return SDValue();
9987 }
9988 
9989 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9990                                         TargetLowering::DAGCombinerInfo &DCI,
9991                                         const ARMSubtarget *Subtarget) {
9992   if (Subtarget->isThumb()) {
9993     if (!Subtarget->hasDSP())
9994       return SDValue();
9995   } else if (!Subtarget->hasV5TEOps())
9996     return SDValue();
9997 
9998   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
9999   // accumulates the product into a 64-bit value. The 16-bit values will
10000   // be sign extended somehow or SRA'd into 32-bit values
10001   // (addc (adde (mul 16bit, 16bit), lo), hi)
10002   SDValue Mul = AddcNode->getOperand(0);
10003   SDValue Lo = AddcNode->getOperand(1);
10004   if (Mul.getOpcode() != ISD::MUL) {
10005     Lo = AddcNode->getOperand(0);
10006     Mul = AddcNode->getOperand(1);
10007     if (Mul.getOpcode() != ISD::MUL)
10008       return SDValue();
10009   }
10010 
10011   SDValue SRA = AddeNode->getOperand(0);
10012   SDValue Hi = AddeNode->getOperand(1);
10013   if (SRA.getOpcode() != ISD::SRA) {
10014     SRA = AddeNode->getOperand(1);
10015     Hi = AddeNode->getOperand(0);
10016     if (SRA.getOpcode() != ISD::SRA)
10017       return SDValue();
10018   }
10019   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
10020     if (Const->getZExtValue() != 31)
10021       return SDValue();
10022   } else
10023     return SDValue();
10024 
10025   if (SRA.getOperand(0) != Mul)
10026     return SDValue();
10027 
10028   SelectionDAG &DAG = DCI.DAG;
10029   SDLoc dl(AddcNode);
10030   unsigned Opcode = 0;
10031   SDValue Op0;
10032   SDValue Op1;
10033 
10034   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
10035     Opcode = ARMISD::SMLALBB;
10036     Op0 = Mul.getOperand(0);
10037     Op1 = Mul.getOperand(1);
10038   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
10039     Opcode = ARMISD::SMLALBT;
10040     Op0 = Mul.getOperand(0);
10041     Op1 = Mul.getOperand(1).getOperand(0);
10042   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
10043     Opcode = ARMISD::SMLALTB;
10044     Op0 = Mul.getOperand(0).getOperand(0);
10045     Op1 = Mul.getOperand(1);
10046   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
10047     Opcode = ARMISD::SMLALTT;
10048     Op0 = Mul->getOperand(0).getOperand(0);
10049     Op1 = Mul->getOperand(1).getOperand(0);
10050   }
10051 
10052   if (!Op0 || !Op1)
10053     return SDValue();
10054 
10055   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
10056                               Op0, Op1, Lo, Hi);
10057   // Replace the ADDs' nodes uses by the MLA node's values.
10058   SDValue HiMLALResult(SMLAL.getNode(), 1);
10059   SDValue LoMLALResult(SMLAL.getNode(), 0);
10060 
10061   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
10062   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
10063 
10064   // Return original node to notify the driver to stop replacing.
10065   SDValue resNode(AddcNode, 0);
10066   return resNode;
10067 }
10068 
10069 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
10070                                      TargetLowering::DAGCombinerInfo &DCI,
10071                                      const ARMSubtarget *Subtarget) {
10072   // Look for multiply add opportunities.
10073   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
10074   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
10075   // a glue link from the first add to the second add.
10076   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
10077   // a S/UMLAL instruction.
10078   //                  UMUL_LOHI
10079   //                 / :lo    \ :hi
10080   //                V          \          [no multiline comment]
10081   //    loAdd ->  ADDC         |
10082   //                 \ :carry /
10083   //                  V      V
10084   //                    ADDE   <- hiAdd
10085   //
10086   // In the special case where only the higher part of a signed result is used
10087   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
10088   // a constant with the exact value of 0x80000000, we recognize we are dealing
10089   // with a "rounded multiply and add" (or subtract) and transform it into
10090   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
10091 
10092   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
10093           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
10094          "Expect an ADDE or SUBE");
10095 
10096   assert(AddeSubeNode->getNumOperands() == 3 &&
10097          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
10098          "ADDE node has the wrong inputs");
10099 
10100   // Check that we are chained to the right ADDC or SUBC node.
10101   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
10102   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10103        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
10104       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
10105        AddcSubcNode->getOpcode() != ARMISD::SUBC))
10106     return SDValue();
10107 
10108   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
10109   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
10110 
10111   // Check if the two operands are from the same mul_lohi node.
10112   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
10113     return SDValue();
10114 
10115   assert(AddcSubcNode->getNumValues() == 2 &&
10116          AddcSubcNode->getValueType(0) == MVT::i32 &&
10117          "Expect ADDC with two result values. First: i32");
10118 
10119   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
10120   // maybe a SMLAL which multiplies two 16-bit values.
10121   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
10122       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
10123       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
10124       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
10125       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
10126     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
10127 
10128   // Check for the triangle shape.
10129   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
10130   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
10131 
10132   // Make sure that the ADDE/SUBE operands are not coming from the same node.
10133   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
10134     return SDValue();
10135 
10136   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
10137   bool IsLeftOperandMUL = false;
10138   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
10139   if (MULOp == SDValue())
10140     MULOp = findMUL_LOHI(AddeSubeOp1);
10141   else
10142     IsLeftOperandMUL = true;
10143   if (MULOp == SDValue())
10144     return SDValue();
10145 
10146   // Figure out the right opcode.
10147   unsigned Opc = MULOp->getOpcode();
10148   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
10149 
10150   // Figure out the high and low input values to the MLAL node.
10151   SDValue *HiAddSub = nullptr;
10152   SDValue *LoMul = nullptr;
10153   SDValue *LowAddSub = nullptr;
10154 
10155   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
10156   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
10157     return SDValue();
10158 
10159   if (IsLeftOperandMUL)
10160     HiAddSub = &AddeSubeOp1;
10161   else
10162     HiAddSub = &AddeSubeOp0;
10163 
10164   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
10165   // whose low result is fed to the ADDC/SUBC we are checking.
10166 
10167   if (AddcSubcOp0 == MULOp.getValue(0)) {
10168     LoMul = &AddcSubcOp0;
10169     LowAddSub = &AddcSubcOp1;
10170   }
10171   if (AddcSubcOp1 == MULOp.getValue(0)) {
10172     LoMul = &AddcSubcOp1;
10173     LowAddSub = &AddcSubcOp0;
10174   }
10175 
10176   if (!LoMul)
10177     return SDValue();
10178 
10179   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
10180   // the replacement below will create a cycle.
10181   if (AddcSubcNode == HiAddSub->getNode() ||
10182       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
10183     return SDValue();
10184 
10185   // Create the merged node.
10186   SelectionDAG &DAG = DCI.DAG;
10187 
10188   // Start building operand list.
10189   SmallVector<SDValue, 8> Ops;
10190   Ops.push_back(LoMul->getOperand(0));
10191   Ops.push_back(LoMul->getOperand(1));
10192 
10193   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
10194   // the case, we must be doing signed multiplication and only use the higher
10195   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
10196   // addition or subtraction with the value of 0x800000.
10197   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
10198       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
10199       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
10200       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
10201           0x80000000) {
10202     Ops.push_back(*HiAddSub);
10203     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
10204       FinalOpc = ARMISD::SMMLSR;
10205     } else {
10206       FinalOpc = ARMISD::SMMLAR;
10207     }
10208     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
10209     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
10210 
10211     return SDValue(AddeSubeNode, 0);
10212   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
10213     // SMMLS is generated during instruction selection and the rest of this
10214     // function can not handle the case where AddcSubcNode is a SUBC.
10215     return SDValue();
10216 
10217   // Finish building the operand list for {U/S}MLAL
10218   Ops.push_back(*LowAddSub);
10219   Ops.push_back(*HiAddSub);
10220 
10221   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
10222                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10223 
10224   // Replace the ADDs' nodes uses by the MLA node's values.
10225   SDValue HiMLALResult(MLALNode.getNode(), 1);
10226   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
10227 
10228   SDValue LoMLALResult(MLALNode.getNode(), 0);
10229   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
10230 
10231   // Return original node to notify the driver to stop replacing.
10232   return SDValue(AddeSubeNode, 0);
10233 }
10234 
10235 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
10236                                       TargetLowering::DAGCombinerInfo &DCI,
10237                                       const ARMSubtarget *Subtarget) {
10238   // UMAAL is similar to UMLAL except that it adds two unsigned values.
10239   // While trying to combine for the other MLAL nodes, first search for the
10240   // chance to use UMAAL. Check if Addc uses a node which has already
10241   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
10242   // as the addend, and it's handled in PerformUMLALCombine.
10243 
10244   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10245     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10246 
10247   // Check that we have a glued ADDC node.
10248   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
10249   if (AddcNode->getOpcode() != ARMISD::ADDC)
10250     return SDValue();
10251 
10252   // Find the converted UMAAL or quit if it doesn't exist.
10253   SDNode *UmlalNode = nullptr;
10254   SDValue AddHi;
10255   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
10256     UmlalNode = AddcNode->getOperand(0).getNode();
10257     AddHi = AddcNode->getOperand(1);
10258   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
10259     UmlalNode = AddcNode->getOperand(1).getNode();
10260     AddHi = AddcNode->getOperand(0);
10261   } else {
10262     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10263   }
10264 
10265   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
10266   // the ADDC as well as Zero.
10267   if (!isNullConstant(UmlalNode->getOperand(3)))
10268     return SDValue();
10269 
10270   if ((isNullConstant(AddeNode->getOperand(0)) &&
10271        AddeNode->getOperand(1).getNode() == UmlalNode) ||
10272       (AddeNode->getOperand(0).getNode() == UmlalNode &&
10273        isNullConstant(AddeNode->getOperand(1)))) {
10274     SelectionDAG &DAG = DCI.DAG;
10275     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
10276                       UmlalNode->getOperand(2), AddHi };
10277     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
10278                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10279 
10280     // Replace the ADDs' nodes uses by the UMAAL node's values.
10281     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
10282     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
10283 
10284     // Return original node to notify the driver to stop replacing.
10285     return SDValue(AddeNode, 0);
10286   }
10287   return SDValue();
10288 }
10289 
10290 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
10291                                    const ARMSubtarget *Subtarget) {
10292   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10293     return SDValue();
10294 
10295   // Check that we have a pair of ADDC and ADDE as operands.
10296   // Both addends of the ADDE must be zero.
10297   SDNode* AddcNode = N->getOperand(2).getNode();
10298   SDNode* AddeNode = N->getOperand(3).getNode();
10299   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
10300       (AddeNode->getOpcode() == ARMISD::ADDE) &&
10301       isNullConstant(AddeNode->getOperand(0)) &&
10302       isNullConstant(AddeNode->getOperand(1)) &&
10303       (AddeNode->getOperand(2).getNode() == AddcNode))
10304     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
10305                        DAG.getVTList(MVT::i32, MVT::i32),
10306                        {N->getOperand(0), N->getOperand(1),
10307                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
10308   else
10309     return SDValue();
10310 }
10311 
10312 static SDValue PerformAddcSubcCombine(SDNode *N,
10313                                       TargetLowering::DAGCombinerInfo &DCI,
10314                                       const ARMSubtarget *Subtarget) {
10315   SelectionDAG &DAG(DCI.DAG);
10316 
10317   if (N->getOpcode() == ARMISD::SUBC) {
10318     // (SUBC (ADDE 0, 0, C), 1) -> C
10319     SDValue LHS = N->getOperand(0);
10320     SDValue RHS = N->getOperand(1);
10321     if (LHS->getOpcode() == ARMISD::ADDE &&
10322         isNullConstant(LHS->getOperand(0)) &&
10323         isNullConstant(LHS->getOperand(1)) && isOneConstant(RHS)) {
10324       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
10325     }
10326   }
10327 
10328   if (Subtarget->isThumb1Only()) {
10329     SDValue RHS = N->getOperand(1);
10330     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10331       int32_t imm = C->getSExtValue();
10332       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
10333         SDLoc DL(N);
10334         RHS = DAG.getConstant(-imm, DL, MVT::i32);
10335         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
10336                                                            : ARMISD::ADDC;
10337         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
10338       }
10339     }
10340   }
10341   return SDValue();
10342 }
10343 
10344 static SDValue PerformAddeSubeCombine(SDNode *N,
10345                                       TargetLowering::DAGCombinerInfo &DCI,
10346                                       const ARMSubtarget *Subtarget) {
10347   if (Subtarget->isThumb1Only()) {
10348     SelectionDAG &DAG = DCI.DAG;
10349     SDValue RHS = N->getOperand(1);
10350     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10351       int64_t imm = C->getSExtValue();
10352       if (imm < 0) {
10353         SDLoc DL(N);
10354 
10355         // The with-carry-in form matches bitwise not instead of the negation.
10356         // Effectively, the inverse interpretation of the carry flag already
10357         // accounts for part of the negation.
10358         RHS = DAG.getConstant(~imm, DL, MVT::i32);
10359 
10360         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
10361                                                            : ARMISD::ADDE;
10362         return DAG.getNode(Opcode, DL, N->getVTList(),
10363                            N->getOperand(0), RHS, N->getOperand(2));
10364       }
10365     }
10366   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
10367     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
10368   }
10369   return SDValue();
10370 }
10371 
10372 /// PerformADDECombine - Target-specific dag combine transform from
10373 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
10374 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
10375 static SDValue PerformADDECombine(SDNode *N,
10376                                   TargetLowering::DAGCombinerInfo &DCI,
10377                                   const ARMSubtarget *Subtarget) {
10378   // Only ARM and Thumb2 support UMLAL/SMLAL.
10379   if (Subtarget->isThumb1Only())
10380     return PerformAddeSubeCombine(N, DCI, Subtarget);
10381 
10382   // Only perform the checks after legalize when the pattern is available.
10383   if (DCI.isBeforeLegalize()) return SDValue();
10384 
10385   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
10386 }
10387 
10388 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
10389 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
10390 /// called with the default operands, and if that fails, with commuted
10391 /// operands.
10392 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
10393                                           TargetLowering::DAGCombinerInfo &DCI,
10394                                           const ARMSubtarget *Subtarget){
10395   // Attempt to create vpadd for this add.
10396   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
10397     return Result;
10398 
10399   // Attempt to create vpaddl for this add.
10400   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
10401     return Result;
10402   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
10403                                                       Subtarget))
10404     return Result;
10405 
10406   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10407   if (N0.getNode()->hasOneUse())
10408     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
10409       return Result;
10410   return SDValue();
10411 }
10412 
10413 static SDValue PerformSHLSimplify(SDNode *N,
10414                                 TargetLowering::DAGCombinerInfo &DCI,
10415                                 const ARMSubtarget *ST) {
10416   // Allow the generic combiner to identify potential bswaps.
10417   if (DCI.isBeforeLegalize())
10418     return SDValue();
10419 
10420   // DAG combiner will fold:
10421   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
10422   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
10423   // Other code patterns that can be also be modified have the following form:
10424   // b + ((a << 1) | 510)
10425   // b + ((a << 1) & 510)
10426   // b + ((a << 1) ^ 510)
10427   // b + ((a << 1) + 510)
10428 
10429   // Many instructions can  perform the shift for free, but it requires both
10430   // the operands to be registers. If c1 << c2 is too large, a mov immediate
10431   // instruction will needed. So, unfold back to the original pattern if:
10432   // - if c1 and c2 are small enough that they don't require mov imms.
10433   // - the user(s) of the node can perform an shl
10434 
10435   // No shifted operands for 16-bit instructions.
10436   if (ST->isThumb() && ST->isThumb1Only())
10437     return SDValue();
10438 
10439   // Check that all the users could perform the shl themselves.
10440   for (auto U : N->uses()) {
10441     switch(U->getOpcode()) {
10442     default:
10443       return SDValue();
10444     case ISD::SUB:
10445     case ISD::ADD:
10446     case ISD::AND:
10447     case ISD::OR:
10448     case ISD::XOR:
10449     case ISD::SETCC:
10450     case ARMISD::CMP:
10451       // Check that the user isn't already using a constant because there
10452       // aren't any instructions that support an immediate operand and a
10453       // shifted operand.
10454       if (isa<ConstantSDNode>(U->getOperand(0)) ||
10455           isa<ConstantSDNode>(U->getOperand(1)))
10456         return SDValue();
10457 
10458       // Check that it's not already using a shift.
10459       if (U->getOperand(0).getOpcode() == ISD::SHL ||
10460           U->getOperand(1).getOpcode() == ISD::SHL)
10461         return SDValue();
10462       break;
10463     }
10464   }
10465 
10466   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
10467       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
10468     return SDValue();
10469 
10470   if (N->getOperand(0).getOpcode() != ISD::SHL)
10471     return SDValue();
10472 
10473   SDValue SHL = N->getOperand(0);
10474 
10475   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
10476   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
10477   if (!C1ShlC2 || !C2)
10478     return SDValue();
10479 
10480   APInt C2Int = C2->getAPIntValue();
10481   APInt C1Int = C1ShlC2->getAPIntValue();
10482 
10483   // Check that performing a lshr will not lose any information.
10484   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
10485                                      C2Int.getBitWidth() - C2->getZExtValue());
10486   if ((C1Int & Mask) != C1Int)
10487     return SDValue();
10488 
10489   // Shift the first constant.
10490   C1Int.lshrInPlace(C2Int);
10491 
10492   // The immediates are encoded as an 8-bit value that can be rotated.
10493   auto LargeImm = [](const APInt &Imm) {
10494     unsigned Zeros = Imm.countLeadingZeros() + Imm.countTrailingZeros();
10495     return Imm.getBitWidth() - Zeros > 8;
10496   };
10497 
10498   if (LargeImm(C1Int) || LargeImm(C2Int))
10499     return SDValue();
10500 
10501   SelectionDAG &DAG = DCI.DAG;
10502   SDLoc dl(N);
10503   SDValue X = SHL.getOperand(0);
10504   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
10505                               DAG.getConstant(C1Int, dl, MVT::i32));
10506   // Shift left to compensate for the lshr of C1Int.
10507   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
10508 
10509   DEBUG(dbgs() << "Simplify shl use:\n"; SHL.getOperand(0).dump(); SHL.dump();
10510         N->dump());
10511   DEBUG(dbgs() << "Into:\n"; X.dump(); BinOp.dump(); Res.dump());
10512 
10513   DAG.ReplaceAllUsesWith(SDValue(N, 0), Res);
10514   return SDValue(N, 0);
10515 }
10516 
10517 
10518 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
10519 ///
10520 static SDValue PerformADDCombine(SDNode *N,
10521                                  TargetLowering::DAGCombinerInfo &DCI,
10522                                  const ARMSubtarget *Subtarget) {
10523   SDValue N0 = N->getOperand(0);
10524   SDValue N1 = N->getOperand(1);
10525 
10526   // Only works one way, because it needs an immediate operand.
10527   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10528     return Result;
10529 
10530   // First try with the default operand order.
10531   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
10532     return Result;
10533 
10534   // If that didn't work, try again with the operands commuted.
10535   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
10536 }
10537 
10538 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
10539 ///
10540 static SDValue PerformSUBCombine(SDNode *N,
10541                                  TargetLowering::DAGCombinerInfo &DCI) {
10542   SDValue N0 = N->getOperand(0);
10543   SDValue N1 = N->getOperand(1);
10544 
10545   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10546   if (N1.getNode()->hasOneUse())
10547     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10548       return Result;
10549 
10550   return SDValue();
10551 }
10552 
10553 /// PerformVMULCombine
10554 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10555 /// special multiplier accumulator forwarding.
10556 ///   vmul d3, d0, d2
10557 ///   vmla d3, d1, d2
10558 /// is faster than
10559 ///   vadd d3, d0, d1
10560 ///   vmul d3, d3, d2
10561 //  However, for (A + B) * (A + B),
10562 //    vadd d2, d0, d1
10563 //    vmul d3, d0, d2
10564 //    vmla d3, d1, d2
10565 //  is slower than
10566 //    vadd d2, d0, d1
10567 //    vmul d3, d2, d2
10568 static SDValue PerformVMULCombine(SDNode *N,
10569                                   TargetLowering::DAGCombinerInfo &DCI,
10570                                   const ARMSubtarget *Subtarget) {
10571   if (!Subtarget->hasVMLxForwarding())
10572     return SDValue();
10573 
10574   SelectionDAG &DAG = DCI.DAG;
10575   SDValue N0 = N->getOperand(0);
10576   SDValue N1 = N->getOperand(1);
10577   unsigned Opcode = N0.getOpcode();
10578   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10579       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10580     Opcode = N1.getOpcode();
10581     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10582         Opcode != ISD::FADD && Opcode != ISD::FSUB)
10583       return SDValue();
10584     std::swap(N0, N1);
10585   }
10586 
10587   if (N0 == N1)
10588     return SDValue();
10589 
10590   EVT VT = N->getValueType(0);
10591   SDLoc DL(N);
10592   SDValue N00 = N0->getOperand(0);
10593   SDValue N01 = N0->getOperand(1);
10594   return DAG.getNode(Opcode, DL, VT,
10595                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10596                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10597 }
10598 
10599 static SDValue PerformMULCombine(SDNode *N,
10600                                  TargetLowering::DAGCombinerInfo &DCI,
10601                                  const ARMSubtarget *Subtarget) {
10602   SelectionDAG &DAG = DCI.DAG;
10603 
10604   if (Subtarget->isThumb1Only())
10605     return SDValue();
10606 
10607   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10608     return SDValue();
10609 
10610   EVT VT = N->getValueType(0);
10611   if (VT.is64BitVector() || VT.is128BitVector())
10612     return PerformVMULCombine(N, DCI, Subtarget);
10613   if (VT != MVT::i32)
10614     return SDValue();
10615 
10616   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10617   if (!C)
10618     return SDValue();
10619 
10620   int64_t MulAmt = C->getSExtValue();
10621   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10622 
10623   ShiftAmt = ShiftAmt & (32 - 1);
10624   SDValue V = N->getOperand(0);
10625   SDLoc DL(N);
10626 
10627   SDValue Res;
10628   MulAmt >>= ShiftAmt;
10629 
10630   if (MulAmt >= 0) {
10631     if (isPowerOf2_32(MulAmt - 1)) {
10632       // (mul x, 2^N + 1) => (add (shl x, N), x)
10633       Res = DAG.getNode(ISD::ADD, DL, VT,
10634                         V,
10635                         DAG.getNode(ISD::SHL, DL, VT,
10636                                     V,
10637                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
10638                                                     MVT::i32)));
10639     } else if (isPowerOf2_32(MulAmt + 1)) {
10640       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10641       Res = DAG.getNode(ISD::SUB, DL, VT,
10642                         DAG.getNode(ISD::SHL, DL, VT,
10643                                     V,
10644                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10645                                                     MVT::i32)),
10646                         V);
10647     } else
10648       return SDValue();
10649   } else {
10650     uint64_t MulAmtAbs = -MulAmt;
10651     if (isPowerOf2_32(MulAmtAbs + 1)) {
10652       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10653       Res = DAG.getNode(ISD::SUB, DL, VT,
10654                         V,
10655                         DAG.getNode(ISD::SHL, DL, VT,
10656                                     V,
10657                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10658                                                     MVT::i32)));
10659     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10660       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10661       Res = DAG.getNode(ISD::ADD, DL, VT,
10662                         V,
10663                         DAG.getNode(ISD::SHL, DL, VT,
10664                                     V,
10665                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10666                                                     MVT::i32)));
10667       Res = DAG.getNode(ISD::SUB, DL, VT,
10668                         DAG.getConstant(0, DL, MVT::i32), Res);
10669     } else
10670       return SDValue();
10671   }
10672 
10673   if (ShiftAmt != 0)
10674     Res = DAG.getNode(ISD::SHL, DL, VT,
10675                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10676 
10677   // Do not add new nodes to DAG combiner worklist.
10678   DCI.CombineTo(N, Res, false);
10679   return SDValue();
10680 }
10681 
10682 static SDValue PerformANDCombine(SDNode *N,
10683                                  TargetLowering::DAGCombinerInfo &DCI,
10684                                  const ARMSubtarget *Subtarget) {
10685   // Attempt to use immediate-form VBIC
10686   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10687   SDLoc dl(N);
10688   EVT VT = N->getValueType(0);
10689   SelectionDAG &DAG = DCI.DAG;
10690 
10691   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10692     return SDValue();
10693 
10694   APInt SplatBits, SplatUndef;
10695   unsigned SplatBitSize;
10696   bool HasAnyUndefs;
10697   if (BVN &&
10698       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10699     if (SplatBitSize <= 64) {
10700       EVT VbicVT;
10701       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10702                                       SplatUndef.getZExtValue(), SplatBitSize,
10703                                       DAG, dl, VbicVT, VT.is128BitVector(),
10704                                       OtherModImm);
10705       if (Val.getNode()) {
10706         SDValue Input =
10707           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10708         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10709         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10710       }
10711     }
10712   }
10713 
10714   if (!Subtarget->isThumb1Only()) {
10715     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10716     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10717       return Result;
10718 
10719     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10720       return Result;
10721   }
10722 
10723   return SDValue();
10724 }
10725 
10726 // Try combining OR nodes to SMULWB, SMULWT.
10727 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10728                                          TargetLowering::DAGCombinerInfo &DCI,
10729                                          const ARMSubtarget *Subtarget) {
10730   if (!Subtarget->hasV6Ops() ||
10731       (Subtarget->isThumb() &&
10732        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10733     return SDValue();
10734 
10735   SDValue SRL = OR->getOperand(0);
10736   SDValue SHL = OR->getOperand(1);
10737 
10738   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10739     SRL = OR->getOperand(1);
10740     SHL = OR->getOperand(0);
10741   }
10742   if (!isSRL16(SRL) || !isSHL16(SHL))
10743     return SDValue();
10744 
10745   // The first operands to the shifts need to be the two results from the
10746   // same smul_lohi node.
10747   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10748        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10749     return SDValue();
10750 
10751   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10752   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10753       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10754     return SDValue();
10755 
10756   // Now we have:
10757   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10758   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10759   // For SMUWB the 16-bit value will signed extended somehow.
10760   // For SMULWT only the SRA is required.
10761   // Check both sides of SMUL_LOHI
10762   SDValue OpS16 = SMULLOHI->getOperand(0);
10763   SDValue OpS32 = SMULLOHI->getOperand(1);
10764 
10765   SelectionDAG &DAG = DCI.DAG;
10766   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10767     OpS16 = OpS32;
10768     OpS32 = SMULLOHI->getOperand(0);
10769   }
10770 
10771   SDLoc dl(OR);
10772   unsigned Opcode = 0;
10773   if (isS16(OpS16, DAG))
10774     Opcode = ARMISD::SMULWB;
10775   else if (isSRA16(OpS16)) {
10776     Opcode = ARMISD::SMULWT;
10777     OpS16 = OpS16->getOperand(0);
10778   }
10779   else
10780     return SDValue();
10781 
10782   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10783   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10784   return SDValue(OR, 0);
10785 }
10786 
10787 static SDValue PerformORCombineToBFI(SDNode *N,
10788                                      TargetLowering::DAGCombinerInfo &DCI,
10789                                      const ARMSubtarget *Subtarget) {
10790   // BFI is only available on V6T2+
10791   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10792     return SDValue();
10793 
10794   EVT VT = N->getValueType(0);
10795   SDValue N0 = N->getOperand(0);
10796   SDValue N1 = N->getOperand(1);
10797   SelectionDAG &DAG = DCI.DAG;
10798   SDLoc DL(N);
10799   // 1) or (and A, mask), val => ARMbfi A, val, mask
10800   //      iff (val & mask) == val
10801   //
10802   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10803   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10804   //          && mask == ~mask2
10805   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10806   //          && ~mask == mask2
10807   //  (i.e., copy a bitfield value into another bitfield of the same width)
10808 
10809   if (VT != MVT::i32)
10810     return SDValue();
10811 
10812   SDValue N00 = N0.getOperand(0);
10813 
10814   // The value and the mask need to be constants so we can verify this is
10815   // actually a bitfield set. If the mask is 0xffff, we can do better
10816   // via a movt instruction, so don't use BFI in that case.
10817   SDValue MaskOp = N0.getOperand(1);
10818   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10819   if (!MaskC)
10820     return SDValue();
10821   unsigned Mask = MaskC->getZExtValue();
10822   if (Mask == 0xffff)
10823     return SDValue();
10824   SDValue Res;
10825   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10826   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10827   if (N1C) {
10828     unsigned Val = N1C->getZExtValue();
10829     if ((Val & ~Mask) != Val)
10830       return SDValue();
10831 
10832     if (ARM::isBitFieldInvertedMask(Mask)) {
10833       Val >>= countTrailingZeros(~Mask);
10834 
10835       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10836                         DAG.getConstant(Val, DL, MVT::i32),
10837                         DAG.getConstant(Mask, DL, MVT::i32));
10838 
10839       DCI.CombineTo(N, Res, false);
10840       // Return value from the original node to inform the combiner than N is
10841       // now dead.
10842       return SDValue(N, 0);
10843     }
10844   } else if (N1.getOpcode() == ISD::AND) {
10845     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10846     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10847     if (!N11C)
10848       return SDValue();
10849     unsigned Mask2 = N11C->getZExtValue();
10850 
10851     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10852     // as is to match.
10853     if (ARM::isBitFieldInvertedMask(Mask) &&
10854         (Mask == ~Mask2)) {
10855       // The pack halfword instruction works better for masks that fit it,
10856       // so use that when it's available.
10857       if (Subtarget->hasDSP() &&
10858           (Mask == 0xffff || Mask == 0xffff0000))
10859         return SDValue();
10860       // 2a
10861       unsigned amt = countTrailingZeros(Mask2);
10862       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10863                         DAG.getConstant(amt, DL, MVT::i32));
10864       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10865                         DAG.getConstant(Mask, DL, MVT::i32));
10866       DCI.CombineTo(N, Res, false);
10867       // Return value from the original node to inform the combiner than N is
10868       // now dead.
10869       return SDValue(N, 0);
10870     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10871                (~Mask == Mask2)) {
10872       // The pack halfword instruction works better for masks that fit it,
10873       // so use that when it's available.
10874       if (Subtarget->hasDSP() &&
10875           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10876         return SDValue();
10877       // 2b
10878       unsigned lsb = countTrailingZeros(Mask);
10879       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10880                         DAG.getConstant(lsb, DL, MVT::i32));
10881       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10882                         DAG.getConstant(Mask2, DL, MVT::i32));
10883       DCI.CombineTo(N, Res, false);
10884       // Return value from the original node to inform the combiner than N is
10885       // now dead.
10886       return SDValue(N, 0);
10887     }
10888   }
10889 
10890   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10891       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10892       ARM::isBitFieldInvertedMask(~Mask)) {
10893     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10894     // where lsb(mask) == #shamt and masked bits of B are known zero.
10895     SDValue ShAmt = N00.getOperand(1);
10896     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10897     unsigned LSB = countTrailingZeros(Mask);
10898     if (ShAmtC != LSB)
10899       return SDValue();
10900 
10901     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10902                       DAG.getConstant(~Mask, DL, MVT::i32));
10903 
10904     DCI.CombineTo(N, Res, false);
10905     // Return value from the original node to inform the combiner than N is
10906     // now dead.
10907     return SDValue(N, 0);
10908   }
10909 
10910   return SDValue();
10911 }
10912 
10913 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
10914 static SDValue PerformORCombine(SDNode *N,
10915                                 TargetLowering::DAGCombinerInfo &DCI,
10916                                 const ARMSubtarget *Subtarget) {
10917   // Attempt to use immediate-form VORR
10918   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10919   SDLoc dl(N);
10920   EVT VT = N->getValueType(0);
10921   SelectionDAG &DAG = DCI.DAG;
10922 
10923   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10924     return SDValue();
10925 
10926   APInt SplatBits, SplatUndef;
10927   unsigned SplatBitSize;
10928   bool HasAnyUndefs;
10929   if (BVN && Subtarget->hasNEON() &&
10930       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10931     if (SplatBitSize <= 64) {
10932       EVT VorrVT;
10933       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
10934                                       SplatUndef.getZExtValue(), SplatBitSize,
10935                                       DAG, dl, VorrVT, VT.is128BitVector(),
10936                                       OtherModImm);
10937       if (Val.getNode()) {
10938         SDValue Input =
10939           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
10940         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
10941         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
10942       }
10943     }
10944   }
10945 
10946   if (!Subtarget->isThumb1Only()) {
10947     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10948     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10949       return Result;
10950     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
10951       return Result;
10952   }
10953 
10954   SDValue N0 = N->getOperand(0);
10955   SDValue N1 = N->getOperand(1);
10956 
10957   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
10958   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
10959       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10960 
10961     // The code below optimizes (or (and X, Y), Z).
10962     // The AND operand needs to have a single user to make these optimizations
10963     // profitable.
10964     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
10965       return SDValue();
10966 
10967     APInt SplatUndef;
10968     unsigned SplatBitSize;
10969     bool HasAnyUndefs;
10970 
10971     APInt SplatBits0, SplatBits1;
10972     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
10973     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
10974     // Ensure that the second operand of both ands are constants
10975     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
10976                                       HasAnyUndefs) && !HasAnyUndefs) {
10977         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
10978                                           HasAnyUndefs) && !HasAnyUndefs) {
10979             // Ensure that the bit width of the constants are the same and that
10980             // the splat arguments are logical inverses as per the pattern we
10981             // are trying to simplify.
10982             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
10983                 SplatBits0 == ~SplatBits1) {
10984                 // Canonicalize the vector type to make instruction selection
10985                 // simpler.
10986                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
10987                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
10988                                              N0->getOperand(1),
10989                                              N0->getOperand(0),
10990                                              N1->getOperand(0));
10991                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10992             }
10993         }
10994     }
10995   }
10996 
10997   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
10998   // reasonable.
10999   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
11000     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
11001       return Res;
11002   }
11003 
11004   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11005     return Result;
11006 
11007   return SDValue();
11008 }
11009 
11010 static SDValue PerformXORCombine(SDNode *N,
11011                                  TargetLowering::DAGCombinerInfo &DCI,
11012                                  const ARMSubtarget *Subtarget) {
11013   EVT VT = N->getValueType(0);
11014   SelectionDAG &DAG = DCI.DAG;
11015 
11016   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
11017     return SDValue();
11018 
11019   if (!Subtarget->isThumb1Only()) {
11020     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
11021     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
11022       return Result;
11023 
11024     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
11025       return Result;
11026   }
11027 
11028   return SDValue();
11029 }
11030 
11031 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
11032 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
11033 // their position in "to" (Rd).
11034 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
11035   assert(N->getOpcode() == ARMISD::BFI);
11036 
11037   SDValue From = N->getOperand(1);
11038   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
11039   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
11040 
11041   // If the Base came from a SHR #C, we can deduce that it is really testing bit
11042   // #C in the base of the SHR.
11043   if (From->getOpcode() == ISD::SRL &&
11044       isa<ConstantSDNode>(From->getOperand(1))) {
11045     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
11046     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
11047     FromMask <<= Shift.getLimitedValue(31);
11048     From = From->getOperand(0);
11049   }
11050 
11051   return From;
11052 }
11053 
11054 // If A and B contain one contiguous set of bits, does A | B == A . B?
11055 //
11056 // Neither A nor B must be zero.
11057 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
11058   unsigned LastActiveBitInA =  A.countTrailingZeros();
11059   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
11060   return LastActiveBitInA - 1 == FirstActiveBitInB;
11061 }
11062 
11063 static SDValue FindBFIToCombineWith(SDNode *N) {
11064   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
11065   // if one exists.
11066   APInt ToMask, FromMask;
11067   SDValue From = ParseBFI(N, ToMask, FromMask);
11068   SDValue To = N->getOperand(0);
11069 
11070   // Now check for a compatible BFI to merge with. We can pass through BFIs that
11071   // aren't compatible, but not if they set the same bit in their destination as
11072   // we do (or that of any BFI we're going to combine with).
11073   SDValue V = To;
11074   APInt CombinedToMask = ToMask;
11075   while (V.getOpcode() == ARMISD::BFI) {
11076     APInt NewToMask, NewFromMask;
11077     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
11078     if (NewFrom != From) {
11079       // This BFI has a different base. Keep going.
11080       CombinedToMask |= NewToMask;
11081       V = V.getOperand(0);
11082       continue;
11083     }
11084 
11085     // Do the written bits conflict with any we've seen so far?
11086     if ((NewToMask & CombinedToMask).getBoolValue())
11087       // Conflicting bits - bail out because going further is unsafe.
11088       return SDValue();
11089 
11090     // Are the new bits contiguous when combined with the old bits?
11091     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
11092         BitsProperlyConcatenate(FromMask, NewFromMask))
11093       return V;
11094     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
11095         BitsProperlyConcatenate(NewFromMask, FromMask))
11096       return V;
11097 
11098     // We've seen a write to some bits, so track it.
11099     CombinedToMask |= NewToMask;
11100     // Keep going...
11101     V = V.getOperand(0);
11102   }
11103 
11104   return SDValue();
11105 }
11106 
11107 static SDValue PerformBFICombine(SDNode *N,
11108                                  TargetLowering::DAGCombinerInfo &DCI) {
11109   SDValue N1 = N->getOperand(1);
11110   if (N1.getOpcode() == ISD::AND) {
11111     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
11112     // the bits being cleared by the AND are not demanded by the BFI.
11113     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
11114     if (!N11C)
11115       return SDValue();
11116     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
11117     unsigned LSB = countTrailingZeros(~InvMask);
11118     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
11119     assert(Width <
11120                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
11121            "undefined behavior");
11122     unsigned Mask = (1u << Width) - 1;
11123     unsigned Mask2 = N11C->getZExtValue();
11124     if ((Mask & (~Mask2)) == 0)
11125       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
11126                              N->getOperand(0), N1.getOperand(0),
11127                              N->getOperand(2));
11128   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
11129     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
11130     // Keep track of any consecutive bits set that all come from the same base
11131     // value. We can combine these together into a single BFI.
11132     SDValue CombineBFI = FindBFIToCombineWith(N);
11133     if (CombineBFI == SDValue())
11134       return SDValue();
11135 
11136     // We've found a BFI.
11137     APInt ToMask1, FromMask1;
11138     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
11139 
11140     APInt ToMask2, FromMask2;
11141     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
11142     assert(From1 == From2);
11143     (void)From2;
11144 
11145     // First, unlink CombineBFI.
11146     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
11147     // Then create a new BFI, combining the two together.
11148     APInt NewFromMask = FromMask1 | FromMask2;
11149     APInt NewToMask = ToMask1 | ToMask2;
11150 
11151     EVT VT = N->getValueType(0);
11152     SDLoc dl(N);
11153 
11154     if (NewFromMask[0] == 0)
11155       From1 = DCI.DAG.getNode(
11156         ISD::SRL, dl, VT, From1,
11157         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
11158     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
11159                            DCI.DAG.getConstant(~NewToMask, dl, VT));
11160   }
11161   return SDValue();
11162 }
11163 
11164 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
11165 /// ARMISD::VMOVRRD.
11166 static SDValue PerformVMOVRRDCombine(SDNode *N,
11167                                      TargetLowering::DAGCombinerInfo &DCI,
11168                                      const ARMSubtarget *Subtarget) {
11169   // vmovrrd(vmovdrr x, y) -> x,y
11170   SDValue InDouble = N->getOperand(0);
11171   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
11172     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
11173 
11174   // vmovrrd(load f64) -> (load i32), (load i32)
11175   SDNode *InNode = InDouble.getNode();
11176   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
11177       InNode->getValueType(0) == MVT::f64 &&
11178       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
11179       !cast<LoadSDNode>(InNode)->isVolatile()) {
11180     // TODO: Should this be done for non-FrameIndex operands?
11181     LoadSDNode *LD = cast<LoadSDNode>(InNode);
11182 
11183     SelectionDAG &DAG = DCI.DAG;
11184     SDLoc DL(LD);
11185     SDValue BasePtr = LD->getBasePtr();
11186     SDValue NewLD1 =
11187         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
11188                     LD->getAlignment(), LD->getMemOperand()->getFlags());
11189 
11190     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11191                                     DAG.getConstant(4, DL, MVT::i32));
11192     SDValue NewLD2 = DAG.getLoad(
11193         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
11194         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
11195 
11196     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
11197     if (DCI.DAG.getDataLayout().isBigEndian())
11198       std::swap (NewLD1, NewLD2);
11199     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
11200     return Result;
11201   }
11202 
11203   return SDValue();
11204 }
11205 
11206 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
11207 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
11208 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
11209   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
11210   SDValue Op0 = N->getOperand(0);
11211   SDValue Op1 = N->getOperand(1);
11212   if (Op0.getOpcode() == ISD::BITCAST)
11213     Op0 = Op0.getOperand(0);
11214   if (Op1.getOpcode() == ISD::BITCAST)
11215     Op1 = Op1.getOperand(0);
11216   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
11217       Op0.getNode() == Op1.getNode() &&
11218       Op0.getResNo() == 0 && Op1.getResNo() == 1)
11219     return DAG.getNode(ISD::BITCAST, SDLoc(N),
11220                        N->getValueType(0), Op0.getOperand(0));
11221   return SDValue();
11222 }
11223 
11224 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
11225 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
11226 /// i64 vector to have f64 elements, since the value can then be loaded
11227 /// directly into a VFP register.
11228 static bool hasNormalLoadOperand(SDNode *N) {
11229   unsigned NumElts = N->getValueType(0).getVectorNumElements();
11230   for (unsigned i = 0; i < NumElts; ++i) {
11231     SDNode *Elt = N->getOperand(i).getNode();
11232     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
11233       return true;
11234   }
11235   return false;
11236 }
11237 
11238 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
11239 /// ISD::BUILD_VECTOR.
11240 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
11241                                           TargetLowering::DAGCombinerInfo &DCI,
11242                                           const ARMSubtarget *Subtarget) {
11243   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
11244   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
11245   // into a pair of GPRs, which is fine when the value is used as a scalar,
11246   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
11247   SelectionDAG &DAG = DCI.DAG;
11248   if (N->getNumOperands() == 2)
11249     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
11250       return RV;
11251 
11252   // Load i64 elements as f64 values so that type legalization does not split
11253   // them up into i32 values.
11254   EVT VT = N->getValueType(0);
11255   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
11256     return SDValue();
11257   SDLoc dl(N);
11258   SmallVector<SDValue, 8> Ops;
11259   unsigned NumElts = VT.getVectorNumElements();
11260   for (unsigned i = 0; i < NumElts; ++i) {
11261     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
11262     Ops.push_back(V);
11263     // Make the DAGCombiner fold the bitcast.
11264     DCI.AddToWorklist(V.getNode());
11265   }
11266   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
11267   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
11268   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11269 }
11270 
11271 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
11272 static SDValue
11273 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11274   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
11275   // At that time, we may have inserted bitcasts from integer to float.
11276   // If these bitcasts have survived DAGCombine, change the lowering of this
11277   // BUILD_VECTOR in something more vector friendly, i.e., that does not
11278   // force to use floating point types.
11279 
11280   // Make sure we can change the type of the vector.
11281   // This is possible iff:
11282   // 1. The vector is only used in a bitcast to a integer type. I.e.,
11283   //    1.1. Vector is used only once.
11284   //    1.2. Use is a bit convert to an integer type.
11285   // 2. The size of its operands are 32-bits (64-bits are not legal).
11286   EVT VT = N->getValueType(0);
11287   EVT EltVT = VT.getVectorElementType();
11288 
11289   // Check 1.1. and 2.
11290   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
11291     return SDValue();
11292 
11293   // By construction, the input type must be float.
11294   assert(EltVT == MVT::f32 && "Unexpected type!");
11295 
11296   // Check 1.2.
11297   SDNode *Use = *N->use_begin();
11298   if (Use->getOpcode() != ISD::BITCAST ||
11299       Use->getValueType(0).isFloatingPoint())
11300     return SDValue();
11301 
11302   // Check profitability.
11303   // Model is, if more than half of the relevant operands are bitcast from
11304   // i32, turn the build_vector into a sequence of insert_vector_elt.
11305   // Relevant operands are everything that is not statically
11306   // (i.e., at compile time) bitcasted.
11307   unsigned NumOfBitCastedElts = 0;
11308   unsigned NumElts = VT.getVectorNumElements();
11309   unsigned NumOfRelevantElts = NumElts;
11310   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
11311     SDValue Elt = N->getOperand(Idx);
11312     if (Elt->getOpcode() == ISD::BITCAST) {
11313       // Assume only bit cast to i32 will go away.
11314       if (Elt->getOperand(0).getValueType() == MVT::i32)
11315         ++NumOfBitCastedElts;
11316     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
11317       // Constants are statically casted, thus do not count them as
11318       // relevant operands.
11319       --NumOfRelevantElts;
11320   }
11321 
11322   // Check if more than half of the elements require a non-free bitcast.
11323   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
11324     return SDValue();
11325 
11326   SelectionDAG &DAG = DCI.DAG;
11327   // Create the new vector type.
11328   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
11329   // Check if the type is legal.
11330   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11331   if (!TLI.isTypeLegal(VecVT))
11332     return SDValue();
11333 
11334   // Combine:
11335   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
11336   // => BITCAST INSERT_VECTOR_ELT
11337   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
11338   //                      (BITCAST EN), N.
11339   SDValue Vec = DAG.getUNDEF(VecVT);
11340   SDLoc dl(N);
11341   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
11342     SDValue V = N->getOperand(Idx);
11343     if (V.isUndef())
11344       continue;
11345     if (V.getOpcode() == ISD::BITCAST &&
11346         V->getOperand(0).getValueType() == MVT::i32)
11347       // Fold obvious case.
11348       V = V.getOperand(0);
11349     else {
11350       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
11351       // Make the DAGCombiner fold the bitcasts.
11352       DCI.AddToWorklist(V.getNode());
11353     }
11354     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
11355     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
11356   }
11357   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
11358   // Make the DAGCombiner fold the bitcasts.
11359   DCI.AddToWorklist(Vec.getNode());
11360   return Vec;
11361 }
11362 
11363 /// PerformInsertEltCombine - Target-specific dag combine xforms for
11364 /// ISD::INSERT_VECTOR_ELT.
11365 static SDValue PerformInsertEltCombine(SDNode *N,
11366                                        TargetLowering::DAGCombinerInfo &DCI) {
11367   // Bitcast an i64 load inserted into a vector to f64.
11368   // Otherwise, the i64 value will be legalized to a pair of i32 values.
11369   EVT VT = N->getValueType(0);
11370   SDNode *Elt = N->getOperand(1).getNode();
11371   if (VT.getVectorElementType() != MVT::i64 ||
11372       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
11373     return SDValue();
11374 
11375   SelectionDAG &DAG = DCI.DAG;
11376   SDLoc dl(N);
11377   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11378                                  VT.getVectorNumElements());
11379   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
11380   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
11381   // Make the DAGCombiner fold the bitcasts.
11382   DCI.AddToWorklist(Vec.getNode());
11383   DCI.AddToWorklist(V.getNode());
11384   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
11385                                Vec, V, N->getOperand(2));
11386   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
11387 }
11388 
11389 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
11390 /// ISD::VECTOR_SHUFFLE.
11391 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
11392   // The LLVM shufflevector instruction does not require the shuffle mask
11393   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
11394   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
11395   // operands do not match the mask length, they are extended by concatenating
11396   // them with undef vectors.  That is probably the right thing for other
11397   // targets, but for NEON it is better to concatenate two double-register
11398   // size vector operands into a single quad-register size vector.  Do that
11399   // transformation here:
11400   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
11401   //   shuffle(concat(v1, v2), undef)
11402   SDValue Op0 = N->getOperand(0);
11403   SDValue Op1 = N->getOperand(1);
11404   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
11405       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
11406       Op0.getNumOperands() != 2 ||
11407       Op1.getNumOperands() != 2)
11408     return SDValue();
11409   SDValue Concat0Op1 = Op0.getOperand(1);
11410   SDValue Concat1Op1 = Op1.getOperand(1);
11411   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
11412     return SDValue();
11413   // Skip the transformation if any of the types are illegal.
11414   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11415   EVT VT = N->getValueType(0);
11416   if (!TLI.isTypeLegal(VT) ||
11417       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
11418       !TLI.isTypeLegal(Concat1Op1.getValueType()))
11419     return SDValue();
11420 
11421   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11422                                   Op0.getOperand(0), Op1.getOperand(0));
11423   // Translate the shuffle mask.
11424   SmallVector<int, 16> NewMask;
11425   unsigned NumElts = VT.getVectorNumElements();
11426   unsigned HalfElts = NumElts/2;
11427   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11428   for (unsigned n = 0; n < NumElts; ++n) {
11429     int MaskElt = SVN->getMaskElt(n);
11430     int NewElt = -1;
11431     if (MaskElt < (int)HalfElts)
11432       NewElt = MaskElt;
11433     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
11434       NewElt = HalfElts + MaskElt - NumElts;
11435     NewMask.push_back(NewElt);
11436   }
11437   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
11438                               DAG.getUNDEF(VT), NewMask);
11439 }
11440 
11441 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
11442 /// NEON load/store intrinsics, and generic vector load/stores, to merge
11443 /// base address updates.
11444 /// For generic load/stores, the memory type is assumed to be a vector.
11445 /// The caller is assumed to have checked legality.
11446 static SDValue CombineBaseUpdate(SDNode *N,
11447                                  TargetLowering::DAGCombinerInfo &DCI) {
11448   SelectionDAG &DAG = DCI.DAG;
11449   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
11450                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
11451   const bool isStore = N->getOpcode() == ISD::STORE;
11452   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
11453   SDValue Addr = N->getOperand(AddrOpIdx);
11454   MemSDNode *MemN = cast<MemSDNode>(N);
11455   SDLoc dl(N);
11456 
11457   // Search for a use of the address operand that is an increment.
11458   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11459          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11460     SDNode *User = *UI;
11461     if (User->getOpcode() != ISD::ADD ||
11462         UI.getUse().getResNo() != Addr.getResNo())
11463       continue;
11464 
11465     // Check that the add is independent of the load/store.  Otherwise, folding
11466     // it would create a cycle.
11467     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
11468       continue;
11469 
11470     // Find the new opcode for the updating load/store.
11471     bool isLoadOp = true;
11472     bool isLaneOp = false;
11473     unsigned NewOpc = 0;
11474     unsigned NumVecs = 0;
11475     if (isIntrinsic) {
11476       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11477       switch (IntNo) {
11478       default: llvm_unreachable("unexpected intrinsic for Neon base update");
11479       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
11480         NumVecs = 1; break;
11481       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
11482         NumVecs = 2; break;
11483       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
11484         NumVecs = 3; break;
11485       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
11486         NumVecs = 4; break;
11487       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
11488         NumVecs = 2; isLaneOp = true; break;
11489       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
11490         NumVecs = 3; isLaneOp = true; break;
11491       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
11492         NumVecs = 4; isLaneOp = true; break;
11493       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
11494         NumVecs = 1; isLoadOp = false; break;
11495       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
11496         NumVecs = 2; isLoadOp = false; break;
11497       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
11498         NumVecs = 3; isLoadOp = false; break;
11499       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
11500         NumVecs = 4; isLoadOp = false; break;
11501       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
11502         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
11503       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
11504         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
11505       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
11506         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
11507       }
11508     } else {
11509       isLaneOp = true;
11510       switch (N->getOpcode()) {
11511       default: llvm_unreachable("unexpected opcode for Neon base update");
11512       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
11513       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
11514       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
11515       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
11516       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
11517         NumVecs = 1; isLaneOp = false; break;
11518       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
11519         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
11520       }
11521     }
11522 
11523     // Find the size of memory referenced by the load/store.
11524     EVT VecTy;
11525     if (isLoadOp) {
11526       VecTy = N->getValueType(0);
11527     } else if (isIntrinsic) {
11528       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
11529     } else {
11530       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
11531       VecTy = N->getOperand(1).getValueType();
11532     }
11533 
11534     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11535     if (isLaneOp)
11536       NumBytes /= VecTy.getVectorNumElements();
11537 
11538     // If the increment is a constant, it must match the memory ref size.
11539     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11540     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
11541     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
11542       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
11543       // separate instructions that make it harder to use a non-constant update.
11544       continue;
11545     }
11546 
11547     // OK, we found an ADD we can fold into the base update.
11548     // Now, create a _UPD node, taking care of not breaking alignment.
11549 
11550     EVT AlignedVecTy = VecTy;
11551     unsigned Alignment = MemN->getAlignment();
11552 
11553     // If this is a less-than-standard-aligned load/store, change the type to
11554     // match the standard alignment.
11555     // The alignment is overlooked when selecting _UPD variants; and it's
11556     // easier to introduce bitcasts here than fix that.
11557     // There are 3 ways to get to this base-update combine:
11558     // - intrinsics: they are assumed to be properly aligned (to the standard
11559     //   alignment of the memory type), so we don't need to do anything.
11560     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
11561     //   intrinsics, so, likewise, there's nothing to do.
11562     // - generic load/store instructions: the alignment is specified as an
11563     //   explicit operand, rather than implicitly as the standard alignment
11564     //   of the memory type (like the intrisics).  We need to change the
11565     //   memory type to match the explicit alignment.  That way, we don't
11566     //   generate non-standard-aligned ARMISD::VLDx nodes.
11567     if (isa<LSBaseSDNode>(N)) {
11568       if (Alignment == 0)
11569         Alignment = 1;
11570       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
11571         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
11572         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
11573         assert(!isLaneOp && "Unexpected generic load/store lane.");
11574         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
11575         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
11576       }
11577       // Don't set an explicit alignment on regular load/stores that we want
11578       // to transform to VLD/VST 1_UPD nodes.
11579       // This matches the behavior of regular load/stores, which only get an
11580       // explicit alignment if the MMO alignment is larger than the standard
11581       // alignment of the memory type.
11582       // Intrinsics, however, always get an explicit alignment, set to the
11583       // alignment of the MMO.
11584       Alignment = 1;
11585     }
11586 
11587     // Create the new updating load/store node.
11588     // First, create an SDVTList for the new updating node's results.
11589     EVT Tys[6];
11590     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
11591     unsigned n;
11592     for (n = 0; n < NumResultVecs; ++n)
11593       Tys[n] = AlignedVecTy;
11594     Tys[n++] = MVT::i32;
11595     Tys[n] = MVT::Other;
11596     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
11597 
11598     // Then, gather the new node's operands.
11599     SmallVector<SDValue, 8> Ops;
11600     Ops.push_back(N->getOperand(0)); // incoming chain
11601     Ops.push_back(N->getOperand(AddrOpIdx));
11602     Ops.push_back(Inc);
11603 
11604     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
11605       // Try to match the intrinsic's signature
11606       Ops.push_back(StN->getValue());
11607     } else {
11608       // Loads (and of course intrinsics) match the intrinsics' signature,
11609       // so just add all but the alignment operand.
11610       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
11611         Ops.push_back(N->getOperand(i));
11612     }
11613 
11614     // For all node types, the alignment operand is always the last one.
11615     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
11616 
11617     // If this is a non-standard-aligned STORE, the penultimate operand is the
11618     // stored value.  Bitcast it to the aligned type.
11619     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11620       SDValue &StVal = Ops[Ops.size()-2];
11621       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11622     }
11623 
11624     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11625     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11626                                            MemN->getMemOperand());
11627 
11628     // Update the uses.
11629     SmallVector<SDValue, 5> NewResults;
11630     for (unsigned i = 0; i < NumResultVecs; ++i)
11631       NewResults.push_back(SDValue(UpdN.getNode(), i));
11632 
11633     // If this is an non-standard-aligned LOAD, the first result is the loaded
11634     // value.  Bitcast it to the expected result type.
11635     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11636       SDValue &LdVal = NewResults[0];
11637       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11638     }
11639 
11640     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11641     DCI.CombineTo(N, NewResults);
11642     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11643 
11644     break;
11645   }
11646   return SDValue();
11647 }
11648 
11649 static SDValue PerformVLDCombine(SDNode *N,
11650                                  TargetLowering::DAGCombinerInfo &DCI) {
11651   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11652     return SDValue();
11653 
11654   return CombineBaseUpdate(N, DCI);
11655 }
11656 
11657 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11658 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11659 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
11660 /// return true.
11661 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11662   SelectionDAG &DAG = DCI.DAG;
11663   EVT VT = N->getValueType(0);
11664   // vldN-dup instructions only support 64-bit vectors for N > 1.
11665   if (!VT.is64BitVector())
11666     return false;
11667 
11668   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11669   SDNode *VLD = N->getOperand(0).getNode();
11670   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11671     return false;
11672   unsigned NumVecs = 0;
11673   unsigned NewOpc = 0;
11674   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11675   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11676     NumVecs = 2;
11677     NewOpc = ARMISD::VLD2DUP;
11678   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11679     NumVecs = 3;
11680     NewOpc = ARMISD::VLD3DUP;
11681   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11682     NumVecs = 4;
11683     NewOpc = ARMISD::VLD4DUP;
11684   } else {
11685     return false;
11686   }
11687 
11688   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11689   // numbers match the load.
11690   unsigned VLDLaneNo =
11691     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11692   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11693        UI != UE; ++UI) {
11694     // Ignore uses of the chain result.
11695     if (UI.getUse().getResNo() == NumVecs)
11696       continue;
11697     SDNode *User = *UI;
11698     if (User->getOpcode() != ARMISD::VDUPLANE ||
11699         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11700       return false;
11701   }
11702 
11703   // Create the vldN-dup node.
11704   EVT Tys[5];
11705   unsigned n;
11706   for (n = 0; n < NumVecs; ++n)
11707     Tys[n] = VT;
11708   Tys[n] = MVT::Other;
11709   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11710   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11711   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11712   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11713                                            Ops, VLDMemInt->getMemoryVT(),
11714                                            VLDMemInt->getMemOperand());
11715 
11716   // Update the uses.
11717   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11718        UI != UE; ++UI) {
11719     unsigned ResNo = UI.getUse().getResNo();
11720     // Ignore uses of the chain result.
11721     if (ResNo == NumVecs)
11722       continue;
11723     SDNode *User = *UI;
11724     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11725   }
11726 
11727   // Now the vldN-lane intrinsic is dead except for its chain result.
11728   // Update uses of the chain.
11729   std::vector<SDValue> VLDDupResults;
11730   for (unsigned n = 0; n < NumVecs; ++n)
11731     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11732   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11733   DCI.CombineTo(VLD, VLDDupResults);
11734 
11735   return true;
11736 }
11737 
11738 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11739 /// ARMISD::VDUPLANE.
11740 static SDValue PerformVDUPLANECombine(SDNode *N,
11741                                       TargetLowering::DAGCombinerInfo &DCI) {
11742   SDValue Op = N->getOperand(0);
11743 
11744   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11745   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11746   if (CombineVLDDUP(N, DCI))
11747     return SDValue(N, 0);
11748 
11749   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11750   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11751   while (Op.getOpcode() == ISD::BITCAST)
11752     Op = Op.getOperand(0);
11753   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11754     return SDValue();
11755 
11756   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11757   unsigned EltSize = Op.getScalarValueSizeInBits();
11758   // The canonical VMOV for a zero vector uses a 32-bit element size.
11759   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11760   unsigned EltBits;
11761   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11762     EltSize = 8;
11763   EVT VT = N->getValueType(0);
11764   if (EltSize > VT.getScalarSizeInBits())
11765     return SDValue();
11766 
11767   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11768 }
11769 
11770 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11771 static SDValue PerformVDUPCombine(SDNode *N,
11772                                   TargetLowering::DAGCombinerInfo &DCI) {
11773   SelectionDAG &DAG = DCI.DAG;
11774   SDValue Op = N->getOperand(0);
11775 
11776   // Match VDUP(LOAD) -> VLD1DUP.
11777   // We match this pattern here rather than waiting for isel because the
11778   // transform is only legal for unindexed loads.
11779   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11780   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11781       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11782     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11783                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11784     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11785     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11786                                              Ops, LD->getMemoryVT(),
11787                                              LD->getMemOperand());
11788     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11789     return VLDDup;
11790   }
11791 
11792   return SDValue();
11793 }
11794 
11795 static SDValue PerformLOADCombine(SDNode *N,
11796                                   TargetLowering::DAGCombinerInfo &DCI) {
11797   EVT VT = N->getValueType(0);
11798 
11799   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11800   if (ISD::isNormalLoad(N) && VT.isVector() &&
11801       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11802     return CombineBaseUpdate(N, DCI);
11803 
11804   return SDValue();
11805 }
11806 
11807 /// PerformSTORECombine - Target-specific dag combine xforms for
11808 /// ISD::STORE.
11809 static SDValue PerformSTORECombine(SDNode *N,
11810                                    TargetLowering::DAGCombinerInfo &DCI) {
11811   StoreSDNode *St = cast<StoreSDNode>(N);
11812   if (St->isVolatile())
11813     return SDValue();
11814 
11815   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11816   // pack all of the elements in one place.  Next, store to memory in fewer
11817   // chunks.
11818   SDValue StVal = St->getValue();
11819   EVT VT = StVal.getValueType();
11820   if (St->isTruncatingStore() && VT.isVector()) {
11821     SelectionDAG &DAG = DCI.DAG;
11822     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11823     EVT StVT = St->getMemoryVT();
11824     unsigned NumElems = VT.getVectorNumElements();
11825     assert(StVT != VT && "Cannot truncate to the same type");
11826     unsigned FromEltSz = VT.getScalarSizeInBits();
11827     unsigned ToEltSz = StVT.getScalarSizeInBits();
11828 
11829     // From, To sizes and ElemCount must be pow of two
11830     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11831 
11832     // We are going to use the original vector elt for storing.
11833     // Accumulated smaller vector elements must be a multiple of the store size.
11834     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11835 
11836     unsigned SizeRatio  = FromEltSz / ToEltSz;
11837     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11838 
11839     // Create a type on which we perform the shuffle.
11840     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11841                                      NumElems*SizeRatio);
11842     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11843 
11844     SDLoc DL(St);
11845     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11846     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11847     for (unsigned i = 0; i < NumElems; ++i)
11848       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11849                           ? (i + 1) * SizeRatio - 1
11850                           : i * SizeRatio;
11851 
11852     // Can't shuffle using an illegal type.
11853     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11854 
11855     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11856                                 DAG.getUNDEF(WideVec.getValueType()),
11857                                 ShuffleVec);
11858     // At this point all of the data is stored at the bottom of the
11859     // register. We now need to save it to mem.
11860 
11861     // Find the largest store unit
11862     MVT StoreType = MVT::i8;
11863     for (MVT Tp : MVT::integer_valuetypes()) {
11864       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11865         StoreType = Tp;
11866     }
11867     // Didn't find a legal store type.
11868     if (!TLI.isTypeLegal(StoreType))
11869       return SDValue();
11870 
11871     // Bitcast the original vector into a vector of store-size units
11872     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11873             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11874     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11875     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11876     SmallVector<SDValue, 8> Chains;
11877     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11878                                         TLI.getPointerTy(DAG.getDataLayout()));
11879     SDValue BasePtr = St->getBasePtr();
11880 
11881     // Perform one or more big stores into memory.
11882     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11883     for (unsigned I = 0; I < E; I++) {
11884       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11885                                    StoreType, ShuffWide,
11886                                    DAG.getIntPtrConstant(I, DL));
11887       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
11888                                 St->getPointerInfo(), St->getAlignment(),
11889                                 St->getMemOperand()->getFlags());
11890       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
11891                             Increment);
11892       Chains.push_back(Ch);
11893     }
11894     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11895   }
11896 
11897   if (!ISD::isNormalStore(St))
11898     return SDValue();
11899 
11900   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
11901   // ARM stores of arguments in the same cache line.
11902   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
11903       StVal.getNode()->hasOneUse()) {
11904     SelectionDAG  &DAG = DCI.DAG;
11905     bool isBigEndian = DAG.getDataLayout().isBigEndian();
11906     SDLoc DL(St);
11907     SDValue BasePtr = St->getBasePtr();
11908     SDValue NewST1 = DAG.getStore(
11909         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
11910         BasePtr, St->getPointerInfo(), St->getAlignment(),
11911         St->getMemOperand()->getFlags());
11912 
11913     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11914                                     DAG.getConstant(4, DL, MVT::i32));
11915     return DAG.getStore(NewST1.getValue(0), DL,
11916                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
11917                         OffsetPtr, St->getPointerInfo(),
11918                         std::min(4U, St->getAlignment() / 2),
11919                         St->getMemOperand()->getFlags());
11920   }
11921 
11922   if (StVal.getValueType() == MVT::i64 &&
11923       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11924 
11925     // Bitcast an i64 store extracted from a vector to f64.
11926     // Otherwise, the i64 value will be legalized to a pair of i32 values.
11927     SelectionDAG &DAG = DCI.DAG;
11928     SDLoc dl(StVal);
11929     SDValue IntVec = StVal.getOperand(0);
11930     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11931                                    IntVec.getValueType().getVectorNumElements());
11932     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
11933     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11934                                  Vec, StVal.getOperand(1));
11935     dl = SDLoc(N);
11936     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
11937     // Make the DAGCombiner fold the bitcasts.
11938     DCI.AddToWorklist(Vec.getNode());
11939     DCI.AddToWorklist(ExtElt.getNode());
11940     DCI.AddToWorklist(V.getNode());
11941     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
11942                         St->getPointerInfo(), St->getAlignment(),
11943                         St->getMemOperand()->getFlags(), St->getAAInfo());
11944   }
11945 
11946   // If this is a legal vector store, try to combine it into a VST1_UPD.
11947   if (ISD::isNormalStore(N) && VT.isVector() &&
11948       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11949     return CombineBaseUpdate(N, DCI);
11950 
11951   return SDValue();
11952 }
11953 
11954 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11955 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11956 /// when the VMUL has a constant operand that is a power of 2.
11957 ///
11958 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11959 ///  vmul.f32        d16, d17, d16
11960 ///  vcvt.s32.f32    d16, d16
11961 /// becomes:
11962 ///  vcvt.s32.f32    d16, d16, #3
11963 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11964                                   const ARMSubtarget *Subtarget) {
11965   if (!Subtarget->hasNEON())
11966     return SDValue();
11967 
11968   SDValue Op = N->getOperand(0);
11969   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11970       Op.getOpcode() != ISD::FMUL)
11971     return SDValue();
11972 
11973   SDValue ConstVec = Op->getOperand(1);
11974   if (!isa<BuildVectorSDNode>(ConstVec))
11975     return SDValue();
11976 
11977   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11978   uint32_t FloatBits = FloatTy.getSizeInBits();
11979   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11980   uint32_t IntBits = IntTy.getSizeInBits();
11981   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11982   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11983     // These instructions only exist converting from f32 to i32. We can handle
11984     // smaller integers by generating an extra truncate, but larger ones would
11985     // be lossy. We also can't handle more then 4 lanes, since these intructions
11986     // only support v2i32/v4i32 types.
11987     return SDValue();
11988   }
11989 
11990   BitVector UndefElements;
11991   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11992   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11993   if (C == -1 || C == 0 || C > 32)
11994     return SDValue();
11995 
11996   SDLoc dl(N);
11997   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
11998   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
11999     Intrinsic::arm_neon_vcvtfp2fxu;
12000   SDValue FixConv = DAG.getNode(
12001       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12002       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
12003       DAG.getConstant(C, dl, MVT::i32));
12004 
12005   if (IntBits < FloatBits)
12006     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
12007 
12008   return FixConv;
12009 }
12010 
12011 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
12012 /// can replace combinations of VCVT (integer to floating-point) and VDIV
12013 /// when the VDIV has a constant operand that is a power of 2.
12014 ///
12015 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
12016 ///  vcvt.f32.s32    d16, d16
12017 ///  vdiv.f32        d16, d17, d16
12018 /// becomes:
12019 ///  vcvt.f32.s32    d16, d16, #3
12020 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
12021                                   const ARMSubtarget *Subtarget) {
12022   if (!Subtarget->hasNEON())
12023     return SDValue();
12024 
12025   SDValue Op = N->getOperand(0);
12026   unsigned OpOpcode = Op.getNode()->getOpcode();
12027   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
12028       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
12029     return SDValue();
12030 
12031   SDValue ConstVec = N->getOperand(1);
12032   if (!isa<BuildVectorSDNode>(ConstVec))
12033     return SDValue();
12034 
12035   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
12036   uint32_t FloatBits = FloatTy.getSizeInBits();
12037   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
12038   uint32_t IntBits = IntTy.getSizeInBits();
12039   unsigned NumLanes = Op.getValueType().getVectorNumElements();
12040   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
12041     // These instructions only exist converting from i32 to f32. We can handle
12042     // smaller integers by generating an extra extend, but larger ones would
12043     // be lossy. We also can't handle more then 4 lanes, since these intructions
12044     // only support v2i32/v4i32 types.
12045     return SDValue();
12046   }
12047 
12048   BitVector UndefElements;
12049   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
12050   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
12051   if (C == -1 || C == 0 || C > 32)
12052     return SDValue();
12053 
12054   SDLoc dl(N);
12055   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
12056   SDValue ConvInput = Op.getOperand(0);
12057   if (IntBits < FloatBits)
12058     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
12059                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
12060                             ConvInput);
12061 
12062   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
12063     Intrinsic::arm_neon_vcvtfxu2fp;
12064   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
12065                      Op.getValueType(),
12066                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
12067                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
12068 }
12069 
12070 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
12071 /// operand of a vector shift operation, where all the elements of the
12072 /// build_vector must have the same constant integer value.
12073 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
12074   // Ignore bit_converts.
12075   while (Op.getOpcode() == ISD::BITCAST)
12076     Op = Op.getOperand(0);
12077   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
12078   APInt SplatBits, SplatUndef;
12079   unsigned SplatBitSize;
12080   bool HasAnyUndefs;
12081   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
12082                                       HasAnyUndefs, ElementBits) ||
12083       SplatBitSize > ElementBits)
12084     return false;
12085   Cnt = SplatBits.getSExtValue();
12086   return true;
12087 }
12088 
12089 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
12090 /// operand of a vector shift left operation.  That value must be in the range:
12091 ///   0 <= Value < ElementBits for a left shift; or
12092 ///   0 <= Value <= ElementBits for a long left shift.
12093 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
12094   assert(VT.isVector() && "vector shift count is not a vector type");
12095   int64_t ElementBits = VT.getScalarSizeInBits();
12096   if (! getVShiftImm(Op, ElementBits, Cnt))
12097     return false;
12098   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
12099 }
12100 
12101 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
12102 /// operand of a vector shift right operation.  For a shift opcode, the value
12103 /// is positive, but for an intrinsic the value count must be negative. The
12104 /// absolute value must be in the range:
12105 ///   1 <= |Value| <= ElementBits for a right shift; or
12106 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
12107 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
12108                          int64_t &Cnt) {
12109   assert(VT.isVector() && "vector shift count is not a vector type");
12110   int64_t ElementBits = VT.getScalarSizeInBits();
12111   if (! getVShiftImm(Op, ElementBits, Cnt))
12112     return false;
12113   if (!isIntrinsic)
12114     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
12115   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
12116     Cnt = -Cnt;
12117     return true;
12118   }
12119   return false;
12120 }
12121 
12122 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
12123 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
12124   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
12125   switch (IntNo) {
12126   default:
12127     // Don't do anything for most intrinsics.
12128     break;
12129 
12130   // Vector shifts: check for immediate versions and lower them.
12131   // Note: This is done during DAG combining instead of DAG legalizing because
12132   // the build_vectors for 64-bit vector element shift counts are generally
12133   // not legal, and it is hard to see their values after they get legalized to
12134   // loads from a constant pool.
12135   case Intrinsic::arm_neon_vshifts:
12136   case Intrinsic::arm_neon_vshiftu:
12137   case Intrinsic::arm_neon_vrshifts:
12138   case Intrinsic::arm_neon_vrshiftu:
12139   case Intrinsic::arm_neon_vrshiftn:
12140   case Intrinsic::arm_neon_vqshifts:
12141   case Intrinsic::arm_neon_vqshiftu:
12142   case Intrinsic::arm_neon_vqshiftsu:
12143   case Intrinsic::arm_neon_vqshiftns:
12144   case Intrinsic::arm_neon_vqshiftnu:
12145   case Intrinsic::arm_neon_vqshiftnsu:
12146   case Intrinsic::arm_neon_vqrshiftns:
12147   case Intrinsic::arm_neon_vqrshiftnu:
12148   case Intrinsic::arm_neon_vqrshiftnsu: {
12149     EVT VT = N->getOperand(1).getValueType();
12150     int64_t Cnt;
12151     unsigned VShiftOpc = 0;
12152 
12153     switch (IntNo) {
12154     case Intrinsic::arm_neon_vshifts:
12155     case Intrinsic::arm_neon_vshiftu:
12156       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
12157         VShiftOpc = ARMISD::VSHL;
12158         break;
12159       }
12160       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
12161         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
12162                      ARMISD::VSHRs : ARMISD::VSHRu);
12163         break;
12164       }
12165       return SDValue();
12166 
12167     case Intrinsic::arm_neon_vrshifts:
12168     case Intrinsic::arm_neon_vrshiftu:
12169       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
12170         break;
12171       return SDValue();
12172 
12173     case Intrinsic::arm_neon_vqshifts:
12174     case Intrinsic::arm_neon_vqshiftu:
12175       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12176         break;
12177       return SDValue();
12178 
12179     case Intrinsic::arm_neon_vqshiftsu:
12180       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12181         break;
12182       llvm_unreachable("invalid shift count for vqshlu intrinsic");
12183 
12184     case Intrinsic::arm_neon_vrshiftn:
12185     case Intrinsic::arm_neon_vqshiftns:
12186     case Intrinsic::arm_neon_vqshiftnu:
12187     case Intrinsic::arm_neon_vqshiftnsu:
12188     case Intrinsic::arm_neon_vqrshiftns:
12189     case Intrinsic::arm_neon_vqrshiftnu:
12190     case Intrinsic::arm_neon_vqrshiftnsu:
12191       // Narrowing shifts require an immediate right shift.
12192       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
12193         break;
12194       llvm_unreachable("invalid shift count for narrowing vector shift "
12195                        "intrinsic");
12196 
12197     default:
12198       llvm_unreachable("unhandled vector shift");
12199     }
12200 
12201     switch (IntNo) {
12202     case Intrinsic::arm_neon_vshifts:
12203     case Intrinsic::arm_neon_vshiftu:
12204       // Opcode already set above.
12205       break;
12206     case Intrinsic::arm_neon_vrshifts:
12207       VShiftOpc = ARMISD::VRSHRs; break;
12208     case Intrinsic::arm_neon_vrshiftu:
12209       VShiftOpc = ARMISD::VRSHRu; break;
12210     case Intrinsic::arm_neon_vrshiftn:
12211       VShiftOpc = ARMISD::VRSHRN; break;
12212     case Intrinsic::arm_neon_vqshifts:
12213       VShiftOpc = ARMISD::VQSHLs; break;
12214     case Intrinsic::arm_neon_vqshiftu:
12215       VShiftOpc = ARMISD::VQSHLu; break;
12216     case Intrinsic::arm_neon_vqshiftsu:
12217       VShiftOpc = ARMISD::VQSHLsu; break;
12218     case Intrinsic::arm_neon_vqshiftns:
12219       VShiftOpc = ARMISD::VQSHRNs; break;
12220     case Intrinsic::arm_neon_vqshiftnu:
12221       VShiftOpc = ARMISD::VQSHRNu; break;
12222     case Intrinsic::arm_neon_vqshiftnsu:
12223       VShiftOpc = ARMISD::VQSHRNsu; break;
12224     case Intrinsic::arm_neon_vqrshiftns:
12225       VShiftOpc = ARMISD::VQRSHRNs; break;
12226     case Intrinsic::arm_neon_vqrshiftnu:
12227       VShiftOpc = ARMISD::VQRSHRNu; break;
12228     case Intrinsic::arm_neon_vqrshiftnsu:
12229       VShiftOpc = ARMISD::VQRSHRNsu; break;
12230     }
12231 
12232     SDLoc dl(N);
12233     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12234                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
12235   }
12236 
12237   case Intrinsic::arm_neon_vshiftins: {
12238     EVT VT = N->getOperand(1).getValueType();
12239     int64_t Cnt;
12240     unsigned VShiftOpc = 0;
12241 
12242     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
12243       VShiftOpc = ARMISD::VSLI;
12244     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
12245       VShiftOpc = ARMISD::VSRI;
12246     else {
12247       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
12248     }
12249 
12250     SDLoc dl(N);
12251     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12252                        N->getOperand(1), N->getOperand(2),
12253                        DAG.getConstant(Cnt, dl, MVT::i32));
12254   }
12255 
12256   case Intrinsic::arm_neon_vqrshifts:
12257   case Intrinsic::arm_neon_vqrshiftu:
12258     // No immediate versions of these to check for.
12259     break;
12260   }
12261 
12262   return SDValue();
12263 }
12264 
12265 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
12266 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
12267 /// combining instead of DAG legalizing because the build_vectors for 64-bit
12268 /// vector element shift counts are generally not legal, and it is hard to see
12269 /// their values after they get legalized to loads from a constant pool.
12270 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
12271                                    const ARMSubtarget *ST) {
12272   EVT VT = N->getValueType(0);
12273   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
12274     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
12275     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
12276     SDValue N1 = N->getOperand(1);
12277     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
12278       SDValue N0 = N->getOperand(0);
12279       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
12280           DAG.MaskedValueIsZero(N0.getOperand(0),
12281                                 APInt::getHighBitsSet(32, 16)))
12282         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
12283     }
12284   }
12285 
12286   // Nothing to be done for scalar shifts.
12287   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12288   if (!VT.isVector() || !TLI.isTypeLegal(VT))
12289     return SDValue();
12290 
12291   assert(ST->hasNEON() && "unexpected vector shift");
12292   int64_t Cnt;
12293 
12294   switch (N->getOpcode()) {
12295   default: llvm_unreachable("unexpected shift opcode");
12296 
12297   case ISD::SHL:
12298     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
12299       SDLoc dl(N);
12300       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
12301                          DAG.getConstant(Cnt, dl, MVT::i32));
12302     }
12303     break;
12304 
12305   case ISD::SRA:
12306   case ISD::SRL:
12307     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
12308       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
12309                             ARMISD::VSHRs : ARMISD::VSHRu);
12310       SDLoc dl(N);
12311       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
12312                          DAG.getConstant(Cnt, dl, MVT::i32));
12313     }
12314   }
12315   return SDValue();
12316 }
12317 
12318 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
12319 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
12320 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
12321                                     const ARMSubtarget *ST) {
12322   SDValue N0 = N->getOperand(0);
12323 
12324   // Check for sign- and zero-extensions of vector extract operations of 8-
12325   // and 16-bit vector elements.  NEON supports these directly.  They are
12326   // handled during DAG combining because type legalization will promote them
12327   // to 32-bit types and it is messy to recognize the operations after that.
12328   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12329     SDValue Vec = N0.getOperand(0);
12330     SDValue Lane = N0.getOperand(1);
12331     EVT VT = N->getValueType(0);
12332     EVT EltVT = N0.getValueType();
12333     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12334 
12335     if (VT == MVT::i32 &&
12336         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
12337         TLI.isTypeLegal(Vec.getValueType()) &&
12338         isa<ConstantSDNode>(Lane)) {
12339 
12340       unsigned Opc = 0;
12341       switch (N->getOpcode()) {
12342       default: llvm_unreachable("unexpected opcode");
12343       case ISD::SIGN_EXTEND:
12344         Opc = ARMISD::VGETLANEs;
12345         break;
12346       case ISD::ZERO_EXTEND:
12347       case ISD::ANY_EXTEND:
12348         Opc = ARMISD::VGETLANEu;
12349         break;
12350       }
12351       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
12352     }
12353   }
12354 
12355   return SDValue();
12356 }
12357 
12358 static const APInt *isPowerOf2Constant(SDValue V) {
12359   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12360   if (!C)
12361     return nullptr;
12362   const APInt *CV = &C->getAPIntValue();
12363   return CV->isPowerOf2() ? CV : nullptr;
12364 }
12365 
12366 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
12367   // If we have a CMOV, OR and AND combination such as:
12368   //   if (x & CN)
12369   //     y |= CM;
12370   //
12371   // And:
12372   //   * CN is a single bit;
12373   //   * All bits covered by CM are known zero in y
12374   //
12375   // Then we can convert this into a sequence of BFI instructions. This will
12376   // always be a win if CM is a single bit, will always be no worse than the
12377   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
12378   // three bits (due to the extra IT instruction).
12379 
12380   SDValue Op0 = CMOV->getOperand(0);
12381   SDValue Op1 = CMOV->getOperand(1);
12382   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
12383   auto CC = CCNode->getAPIntValue().getLimitedValue();
12384   SDValue CmpZ = CMOV->getOperand(4);
12385 
12386   // The compare must be against zero.
12387   if (!isNullConstant(CmpZ->getOperand(1)))
12388     return SDValue();
12389 
12390   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
12391   SDValue And = CmpZ->getOperand(0);
12392   if (And->getOpcode() != ISD::AND)
12393     return SDValue();
12394   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
12395   if (!AndC)
12396     return SDValue();
12397   SDValue X = And->getOperand(0);
12398 
12399   if (CC == ARMCC::EQ) {
12400     // We're performing an "equal to zero" compare. Swap the operands so we
12401     // canonicalize on a "not equal to zero" compare.
12402     std::swap(Op0, Op1);
12403   } else {
12404     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
12405   }
12406 
12407   if (Op1->getOpcode() != ISD::OR)
12408     return SDValue();
12409 
12410   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
12411   if (!OrC)
12412     return SDValue();
12413   SDValue Y = Op1->getOperand(0);
12414 
12415   if (Op0 != Y)
12416     return SDValue();
12417 
12418   // Now, is it profitable to continue?
12419   APInt OrCI = OrC->getAPIntValue();
12420   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
12421   if (OrCI.countPopulation() > Heuristic)
12422     return SDValue();
12423 
12424   // Lastly, can we determine that the bits defined by OrCI
12425   // are zero in Y?
12426   KnownBits Known;
12427   DAG.computeKnownBits(Y, Known);
12428   if ((OrCI & Known.Zero) != OrCI)
12429     return SDValue();
12430 
12431   // OK, we can do the combine.
12432   SDValue V = Y;
12433   SDLoc dl(X);
12434   EVT VT = X.getValueType();
12435   unsigned BitInX = AndC->logBase2();
12436 
12437   if (BitInX != 0) {
12438     // We must shift X first.
12439     X = DAG.getNode(ISD::SRL, dl, VT, X,
12440                     DAG.getConstant(BitInX, dl, VT));
12441   }
12442 
12443   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
12444        BitInY < NumActiveBits; ++BitInY) {
12445     if (OrCI[BitInY] == 0)
12446       continue;
12447     APInt Mask(VT.getSizeInBits(), 0);
12448     Mask.setBit(BitInY);
12449     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
12450                     // Confusingly, the operand is an *inverted* mask.
12451                     DAG.getConstant(~Mask, dl, VT));
12452   }
12453 
12454   return V;
12455 }
12456 
12457 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
12458 SDValue
12459 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
12460   SDValue Cmp = N->getOperand(4);
12461   if (Cmp.getOpcode() != ARMISD::CMPZ)
12462     // Only looking at NE cases.
12463     return SDValue();
12464 
12465   EVT VT = N->getValueType(0);
12466   SDLoc dl(N);
12467   SDValue LHS = Cmp.getOperand(0);
12468   SDValue RHS = Cmp.getOperand(1);
12469   SDValue Chain = N->getOperand(0);
12470   SDValue BB = N->getOperand(1);
12471   SDValue ARMcc = N->getOperand(2);
12472   ARMCC::CondCodes CC =
12473     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12474 
12475   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
12476   // -> (brcond Chain BB CC CPSR Cmp)
12477   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
12478       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
12479       LHS->getOperand(0)->hasOneUse()) {
12480     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
12481     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
12482     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12483     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12484     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
12485         (LHS01C && LHS01C->getZExtValue() == 1) &&
12486         (LHS1C && LHS1C->getZExtValue() == 1) &&
12487         (RHSC && RHSC->getZExtValue() == 0)) {
12488       return DAG.getNode(
12489           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
12490           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
12491     }
12492   }
12493 
12494   return SDValue();
12495 }
12496 
12497 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
12498 SDValue
12499 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
12500   SDValue Cmp = N->getOperand(4);
12501   if (Cmp.getOpcode() != ARMISD::CMPZ)
12502     // Only looking at EQ and NE cases.
12503     return SDValue();
12504 
12505   EVT VT = N->getValueType(0);
12506   SDLoc dl(N);
12507   SDValue LHS = Cmp.getOperand(0);
12508   SDValue RHS = Cmp.getOperand(1);
12509   SDValue FalseVal = N->getOperand(0);
12510   SDValue TrueVal = N->getOperand(1);
12511   SDValue ARMcc = N->getOperand(2);
12512   ARMCC::CondCodes CC =
12513     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12514 
12515   // BFI is only available on V6T2+.
12516   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
12517     SDValue R = PerformCMOVToBFICombine(N, DAG);
12518     if (R)
12519       return R;
12520   }
12521 
12522   // Simplify
12523   //   mov     r1, r0
12524   //   cmp     r1, x
12525   //   mov     r0, y
12526   //   moveq   r0, x
12527   // to
12528   //   cmp     r0, x
12529   //   movne   r0, y
12530   //
12531   //   mov     r1, r0
12532   //   cmp     r1, x
12533   //   mov     r0, x
12534   //   movne   r0, y
12535   // to
12536   //   cmp     r0, x
12537   //   movne   r0, y
12538   /// FIXME: Turn this into a target neutral optimization?
12539   SDValue Res;
12540   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
12541     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
12542                       N->getOperand(3), Cmp);
12543   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
12544     SDValue ARMcc;
12545     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
12546     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
12547                       N->getOperand(3), NewCmp);
12548   }
12549 
12550   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
12551   // -> (cmov F T CC CPSR Cmp)
12552   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
12553     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
12554     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12555     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12556     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
12557         (LHS1C && LHS1C->getZExtValue() == 1) &&
12558         (RHSC && RHSC->getZExtValue() == 0)) {
12559       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
12560                          LHS->getOperand(2), LHS->getOperand(3),
12561                          LHS->getOperand(4));
12562     }
12563   }
12564 
12565   if (!VT.isInteger())
12566       return SDValue();
12567 
12568   // Materialize a boolean comparison for integers so we can avoid branching.
12569   if (isNullConstant(FalseVal)) {
12570     if (CC == ARMCC::EQ && isOneConstant(TrueVal)) {
12571       if (!Subtarget->isThumb1Only() && Subtarget->hasV5TOps()) {
12572         // If x == y then x - y == 0 and ARM's CLZ will return 32, shifting it
12573         // right 5 bits will make that 32 be 1, otherwise it will be 0.
12574         // CMOV 0, 1, ==, (CMPZ x, y) -> SRL (CTLZ (SUB x, y)), 5
12575         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12576         Res = DAG.getNode(ISD::SRL, dl, VT, DAG.getNode(ISD::CTLZ, dl, VT, Sub),
12577                           DAG.getConstant(5, dl, MVT::i32));
12578       } else {
12579         // CMOV 0, 1, ==, (CMPZ x, y) ->
12580         //     (ADDCARRY (SUB x, y), t:0, t:1)
12581         // where t = (SUBCARRY 0, (SUB x, y), 0)
12582         //
12583         // The SUBCARRY computes 0 - (x - y) and this will give a borrow when
12584         // x != y. In other words, a carry C == 1 when x == y, C == 0
12585         // otherwise.
12586         // The final ADDCARRY computes
12587         //     x - y + (0 - (x - y)) + C == C
12588         SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12589         SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12590         SDValue Neg = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, Sub);
12591         // ISD::SUBCARRY returns a borrow but we want the carry here
12592         // actually.
12593         SDValue Carry =
12594             DAG.getNode(ISD::SUB, dl, MVT::i32,
12595                         DAG.getConstant(1, dl, MVT::i32), Neg.getValue(1));
12596         Res = DAG.getNode(ISD::ADDCARRY, dl, VTs, Sub, Neg, Carry);
12597       }
12598     } else if (CC == ARMCC::NE && LHS != RHS &&
12599                (!Subtarget->isThumb1Only() || isPowerOf2Constant(TrueVal))) {
12600       // This seems pointless but will allow us to combine it further below.
12601       // CMOV 0, z, !=, (CMPZ x, y) -> CMOV (SUB x, y), z, !=, (CMPZ x, y)
12602       SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12603       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, TrueVal, ARMcc,
12604                         N->getOperand(3), Cmp);
12605     }
12606   } else if (isNullConstant(TrueVal)) {
12607     if (CC == ARMCC::EQ && LHS != RHS &&
12608         (!Subtarget->isThumb1Only() || isPowerOf2Constant(FalseVal))) {
12609       // This seems pointless but will allow us to combine it further below
12610       // Note that we change == for != as this is the dual for the case above.
12611       // CMOV z, 0, ==, (CMPZ x, y) -> CMOV (SUB x, y), z, !=, (CMPZ x, y)
12612       SDValue Sub = DAG.getNode(ISD::SUB, dl, VT, LHS, RHS);
12613       Res = DAG.getNode(ARMISD::CMOV, dl, VT, Sub, FalseVal,
12614                         DAG.getConstant(ARMCC::NE, dl, MVT::i32),
12615                         N->getOperand(3), Cmp);
12616     }
12617   }
12618 
12619   // On Thumb1, the DAG above may be further combined if z is a power of 2
12620   // (z == 2 ^ K).
12621   // CMOV (SUB x, y), z, !=, (CMPZ x, y) ->
12622   //       merge t3, t4
12623   // where t1 = (SUBCARRY (SUB x, y), z, 0)
12624   //       t2 = (SUBCARRY (SUB x, y), t1:0, t1:1)
12625   //       t3 = if K != 0 then (SHL t2:0, K) else t2:0
12626   //       t4 = (SUB 1, t2:1)   [ we want a carry, not a borrow ]
12627   const APInt *TrueConst;
12628   if (Subtarget->isThumb1Only() && CC == ARMCC::NE &&
12629       (FalseVal.getOpcode() == ISD::SUB) && (FalseVal.getOperand(0) == LHS) &&
12630       (FalseVal.getOperand(1) == RHS) &&
12631       (TrueConst = isPowerOf2Constant(TrueVal))) {
12632     SDVTList VTs = DAG.getVTList(VT, MVT::i32);
12633     unsigned ShiftAmount = TrueConst->logBase2();
12634     if (ShiftAmount)
12635       TrueVal = DAG.getConstant(1, dl, VT);
12636     SDValue Subc = DAG.getNode(ISD::USUBO, dl, VTs, FalseVal, TrueVal);
12637     Res = DAG.getNode(ISD::SUBCARRY, dl, VTs, FalseVal, Subc, Subc.getValue(1));
12638     // Make it a carry, not a borrow.
12639     SDValue Carry = DAG.getNode(
12640         ISD::SUB, dl, VT, DAG.getConstant(1, dl, MVT::i32), Res.getValue(1));
12641     Res = DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Res, Carry);
12642 
12643     if (ShiftAmount)
12644       Res = DAG.getNode(ISD::SHL, dl, VT, Res,
12645                         DAG.getConstant(ShiftAmount, dl, MVT::i32));
12646   }
12647 
12648   if (Res.getNode()) {
12649     KnownBits Known;
12650     DAG.computeKnownBits(SDValue(N,0), Known);
12651     // Capture demanded bits information that would be otherwise lost.
12652     if (Known.Zero == 0xfffffffe)
12653       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12654                         DAG.getValueType(MVT::i1));
12655     else if (Known.Zero == 0xffffff00)
12656       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12657                         DAG.getValueType(MVT::i8));
12658     else if (Known.Zero == 0xffff0000)
12659       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12660                         DAG.getValueType(MVT::i16));
12661   }
12662 
12663   return Res;
12664 }
12665 
12666 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
12667                                              DAGCombinerInfo &DCI) const {
12668   switch (N->getOpcode()) {
12669   default: break;
12670   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
12671   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
12672   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
12673   case ISD::SUB:        return PerformSUBCombine(N, DCI);
12674   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
12675   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
12676   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
12677   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
12678   case ARMISD::ADDC:
12679   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
12680   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
12681   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
12682   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
12683   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
12684   case ISD::STORE:      return PerformSTORECombine(N, DCI);
12685   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
12686   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
12687   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
12688   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
12689   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
12690   case ISD::FP_TO_SINT:
12691   case ISD::FP_TO_UINT:
12692     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
12693   case ISD::FDIV:
12694     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
12695   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
12696   case ISD::SHL:
12697   case ISD::SRA:
12698   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
12699   case ISD::SIGN_EXTEND:
12700   case ISD::ZERO_EXTEND:
12701   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
12702   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
12703   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
12704   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
12705   case ARMISD::VLD1DUP:
12706   case ARMISD::VLD2DUP:
12707   case ARMISD::VLD3DUP:
12708   case ARMISD::VLD4DUP:
12709     return PerformVLDCombine(N, DCI);
12710   case ARMISD::BUILD_VECTOR:
12711     return PerformARMBUILD_VECTORCombine(N, DCI);
12712   case ARMISD::SMULWB: {
12713     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12714     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12715     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12716       return SDValue();
12717     break;
12718   }
12719   case ARMISD::SMULWT: {
12720     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12721     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12722     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12723       return SDValue();
12724     break;
12725   }
12726   case ARMISD::SMLALBB: {
12727     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12728     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12729     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12730         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12731       return SDValue();
12732     break;
12733   }
12734   case ARMISD::SMLALBT: {
12735     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12736     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12737     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12738     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12739     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12740         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12741       return SDValue();
12742     break;
12743   }
12744   case ARMISD::SMLALTB: {
12745     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12746     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12747     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12748     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12749     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12750         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12751       return SDValue();
12752     break;
12753   }
12754   case ARMISD::SMLALTT: {
12755     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12756     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12757     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12758         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12759       return SDValue();
12760     break;
12761   }
12762   case ISD::INTRINSIC_VOID:
12763   case ISD::INTRINSIC_W_CHAIN:
12764     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12765     case Intrinsic::arm_neon_vld1:
12766     case Intrinsic::arm_neon_vld2:
12767     case Intrinsic::arm_neon_vld3:
12768     case Intrinsic::arm_neon_vld4:
12769     case Intrinsic::arm_neon_vld2lane:
12770     case Intrinsic::arm_neon_vld3lane:
12771     case Intrinsic::arm_neon_vld4lane:
12772     case Intrinsic::arm_neon_vst1:
12773     case Intrinsic::arm_neon_vst2:
12774     case Intrinsic::arm_neon_vst3:
12775     case Intrinsic::arm_neon_vst4:
12776     case Intrinsic::arm_neon_vst2lane:
12777     case Intrinsic::arm_neon_vst3lane:
12778     case Intrinsic::arm_neon_vst4lane:
12779       return PerformVLDCombine(N, DCI);
12780     default: break;
12781     }
12782     break;
12783   }
12784   return SDValue();
12785 }
12786 
12787 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12788                                                           EVT VT) const {
12789   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12790 }
12791 
12792 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12793                                                        unsigned,
12794                                                        unsigned,
12795                                                        bool *Fast) const {
12796   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12797   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12798 
12799   switch (VT.getSimpleVT().SimpleTy) {
12800   default:
12801     return false;
12802   case MVT::i8:
12803   case MVT::i16:
12804   case MVT::i32: {
12805     // Unaligned access can use (for example) LRDB, LRDH, LDR
12806     if (AllowsUnaligned) {
12807       if (Fast)
12808         *Fast = Subtarget->hasV7Ops();
12809       return true;
12810     }
12811     return false;
12812   }
12813   case MVT::f64:
12814   case MVT::v2f64: {
12815     // For any little-endian targets with neon, we can support unaligned ld/st
12816     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12817     // A big-endian target may also explicitly support unaligned accesses
12818     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12819       if (Fast)
12820         *Fast = true;
12821       return true;
12822     }
12823     return false;
12824   }
12825   }
12826 }
12827 
12828 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12829                        unsigned AlignCheck) {
12830   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12831           (DstAlign == 0 || DstAlign % AlignCheck == 0));
12832 }
12833 
12834 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12835                                            unsigned DstAlign, unsigned SrcAlign,
12836                                            bool IsMemset, bool ZeroMemset,
12837                                            bool MemcpyStrSrc,
12838                                            MachineFunction &MF) const {
12839   const Function &F = MF.getFunction();
12840 
12841   // See if we can use NEON instructions for this...
12842   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12843       !F.hasFnAttribute(Attribute::NoImplicitFloat)) {
12844     bool Fast;
12845     if (Size >= 16 &&
12846         (memOpAlign(SrcAlign, DstAlign, 16) ||
12847          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12848       return MVT::v2f64;
12849     } else if (Size >= 8 &&
12850                (memOpAlign(SrcAlign, DstAlign, 8) ||
12851                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12852                  Fast))) {
12853       return MVT::f64;
12854     }
12855   }
12856 
12857   // Let the target-independent logic figure it out.
12858   return MVT::Other;
12859 }
12860 
12861 // 64-bit integers are split into their high and low parts and held in two
12862 // different registers, so the trunc is free since the low register can just
12863 // be used.
12864 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
12865   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
12866     return false;
12867   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
12868   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
12869   return (SrcBits == 64 && DestBits == 32);
12870 }
12871 
12872 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
12873   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
12874       !DstVT.isInteger())
12875     return false;
12876   unsigned SrcBits = SrcVT.getSizeInBits();
12877   unsigned DestBits = DstVT.getSizeInBits();
12878   return (SrcBits == 64 && DestBits == 32);
12879 }
12880 
12881 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12882   if (Val.getOpcode() != ISD::LOAD)
12883     return false;
12884 
12885   EVT VT1 = Val.getValueType();
12886   if (!VT1.isSimple() || !VT1.isInteger() ||
12887       !VT2.isSimple() || !VT2.isInteger())
12888     return false;
12889 
12890   switch (VT1.getSimpleVT().SimpleTy) {
12891   default: break;
12892   case MVT::i1:
12893   case MVT::i8:
12894   case MVT::i16:
12895     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
12896     return true;
12897   }
12898 
12899   return false;
12900 }
12901 
12902 bool ARMTargetLowering::isFNegFree(EVT VT) const {
12903   if (!VT.isSimple())
12904     return false;
12905 
12906   // There are quite a few FP16 instructions (e.g. VNMLA, VNMLS, etc.) that
12907   // negate values directly (fneg is free). So, we don't want to let the DAG
12908   // combiner rewrite fneg into xors and some other instructions.  For f16 and
12909   // FullFP16 argument passing, some bitcast nodes may be introduced,
12910   // triggering this DAG combine rewrite, so we are avoiding that with this.
12911   switch (VT.getSimpleVT().SimpleTy) {
12912   default: break;
12913   case MVT::f16:
12914     return Subtarget->hasFullFP16();
12915   }
12916 
12917   return false;
12918 }
12919 
12920 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
12921   EVT VT = ExtVal.getValueType();
12922 
12923   if (!isTypeLegal(VT))
12924     return false;
12925 
12926   // Don't create a loadext if we can fold the extension into a wide/long
12927   // instruction.
12928   // If there's more than one user instruction, the loadext is desirable no
12929   // matter what.  There can be two uses by the same instruction.
12930   if (ExtVal->use_empty() ||
12931       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
12932     return true;
12933 
12934   SDNode *U = *ExtVal->use_begin();
12935   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
12936        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
12937     return false;
12938 
12939   return true;
12940 }
12941 
12942 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
12943   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12944     return false;
12945 
12946   if (!isTypeLegal(EVT::getEVT(Ty1)))
12947     return false;
12948 
12949   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
12950 
12951   // Assuming the caller doesn't have a zeroext or signext return parameter,
12952   // truncation all the way down to i1 is valid.
12953   return true;
12954 }
12955 
12956 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
12957                                                 const AddrMode &AM, Type *Ty,
12958                                                 unsigned AS) const {
12959   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
12960     if (Subtarget->hasFPAO())
12961       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
12962     return 0;
12963   }
12964   return -1;
12965 }
12966 
12967 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
12968   if (V < 0)
12969     return false;
12970 
12971   unsigned Scale = 1;
12972   switch (VT.getSimpleVT().SimpleTy) {
12973   default: return false;
12974   case MVT::i1:
12975   case MVT::i8:
12976     // Scale == 1;
12977     break;
12978   case MVT::i16:
12979     // Scale == 2;
12980     Scale = 2;
12981     break;
12982   case MVT::i32:
12983     // Scale == 4;
12984     Scale = 4;
12985     break;
12986   }
12987 
12988   if ((V & (Scale - 1)) != 0)
12989     return false;
12990   V /= Scale;
12991   return V == (V & ((1LL << 5) - 1));
12992 }
12993 
12994 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
12995                                       const ARMSubtarget *Subtarget) {
12996   bool isNeg = false;
12997   if (V < 0) {
12998     isNeg = true;
12999     V = - V;
13000   }
13001 
13002   switch (VT.getSimpleVT().SimpleTy) {
13003   default: return false;
13004   case MVT::i1:
13005   case MVT::i8:
13006   case MVT::i16:
13007   case MVT::i32:
13008     // + imm12 or - imm8
13009     if (isNeg)
13010       return V == (V & ((1LL << 8) - 1));
13011     return V == (V & ((1LL << 12) - 1));
13012   case MVT::f32:
13013   case MVT::f64:
13014     // Same as ARM mode. FIXME: NEON?
13015     if (!Subtarget->hasVFP2())
13016       return false;
13017     if ((V & 3) != 0)
13018       return false;
13019     V >>= 2;
13020     return V == (V & ((1LL << 8) - 1));
13021   }
13022 }
13023 
13024 /// isLegalAddressImmediate - Return true if the integer value can be used
13025 /// as the offset of the target addressing mode for load / store of the
13026 /// given type.
13027 static bool isLegalAddressImmediate(int64_t V, EVT VT,
13028                                     const ARMSubtarget *Subtarget) {
13029   if (V == 0)
13030     return true;
13031 
13032   if (!VT.isSimple())
13033     return false;
13034 
13035   if (Subtarget->isThumb1Only())
13036     return isLegalT1AddressImmediate(V, VT);
13037   else if (Subtarget->isThumb2())
13038     return isLegalT2AddressImmediate(V, VT, Subtarget);
13039 
13040   // ARM mode.
13041   if (V < 0)
13042     V = - V;
13043   switch (VT.getSimpleVT().SimpleTy) {
13044   default: return false;
13045   case MVT::i1:
13046   case MVT::i8:
13047   case MVT::i32:
13048     // +- imm12
13049     return V == (V & ((1LL << 12) - 1));
13050   case MVT::i16:
13051     // +- imm8
13052     return V == (V & ((1LL << 8) - 1));
13053   case MVT::f32:
13054   case MVT::f64:
13055     if (!Subtarget->hasVFP2()) // FIXME: NEON?
13056       return false;
13057     if ((V & 3) != 0)
13058       return false;
13059     V >>= 2;
13060     return V == (V & ((1LL << 8) - 1));
13061   }
13062 }
13063 
13064 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
13065                                                       EVT VT) const {
13066   int Scale = AM.Scale;
13067   if (Scale < 0)
13068     return false;
13069 
13070   switch (VT.getSimpleVT().SimpleTy) {
13071   default: return false;
13072   case MVT::i1:
13073   case MVT::i8:
13074   case MVT::i16:
13075   case MVT::i32:
13076     if (Scale == 1)
13077       return true;
13078     // r + r << imm
13079     Scale = Scale & ~1;
13080     return Scale == 2 || Scale == 4 || Scale == 8;
13081   case MVT::i64:
13082     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
13083     // version in Thumb mode.
13084     // r + r
13085     if (Scale == 1)
13086       return true;
13087     // r * 2 (this can be lowered to r + r).
13088     if (!AM.HasBaseReg && Scale == 2)
13089       return true;
13090     return false;
13091   case MVT::isVoid:
13092     // Note, we allow "void" uses (basically, uses that aren't loads or
13093     // stores), because arm allows folding a scale into many arithmetic
13094     // operations.  This should be made more precise and revisited later.
13095 
13096     // Allow r << imm, but the imm has to be a multiple of two.
13097     if (Scale & 1) return false;
13098     return isPowerOf2_32(Scale);
13099   }
13100 }
13101 
13102 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
13103                                                       EVT VT) const {
13104   const int Scale = AM.Scale;
13105 
13106   // Negative scales are not supported in Thumb1.
13107   if (Scale < 0)
13108     return false;
13109 
13110   // Thumb1 addressing modes do not support register scaling excepting the
13111   // following cases:
13112   // 1. Scale == 1 means no scaling.
13113   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
13114   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
13115 }
13116 
13117 /// isLegalAddressingMode - Return true if the addressing mode represented
13118 /// by AM is legal for this target, for a load/store of the specified type.
13119 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
13120                                               const AddrMode &AM, Type *Ty,
13121                                               unsigned AS, Instruction *I) const {
13122   EVT VT = getValueType(DL, Ty, true);
13123   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
13124     return false;
13125 
13126   // Can never fold addr of global into load/store.
13127   if (AM.BaseGV)
13128     return false;
13129 
13130   switch (AM.Scale) {
13131   case 0:  // no scale reg, must be "r+i" or "r", or "i".
13132     break;
13133   default:
13134     // ARM doesn't support any R+R*scale+imm addr modes.
13135     if (AM.BaseOffs)
13136       return false;
13137 
13138     if (!VT.isSimple())
13139       return false;
13140 
13141     if (Subtarget->isThumb1Only())
13142       return isLegalT1ScaledAddressingMode(AM, VT);
13143 
13144     if (Subtarget->isThumb2())
13145       return isLegalT2ScaledAddressingMode(AM, VT);
13146 
13147     int Scale = AM.Scale;
13148     switch (VT.getSimpleVT().SimpleTy) {
13149     default: return false;
13150     case MVT::i1:
13151     case MVT::i8:
13152     case MVT::i32:
13153       if (Scale < 0) Scale = -Scale;
13154       if (Scale == 1)
13155         return true;
13156       // r + r << imm
13157       return isPowerOf2_32(Scale & ~1);
13158     case MVT::i16:
13159     case MVT::i64:
13160       // r +/- r
13161       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
13162         return true;
13163       // r * 2 (this can be lowered to r + r).
13164       if (!AM.HasBaseReg && Scale == 2)
13165         return true;
13166       return false;
13167 
13168     case MVT::isVoid:
13169       // Note, we allow "void" uses (basically, uses that aren't loads or
13170       // stores), because arm allows folding a scale into many arithmetic
13171       // operations.  This should be made more precise and revisited later.
13172 
13173       // Allow r << imm, but the imm has to be a multiple of two.
13174       if (Scale & 1) return false;
13175       return isPowerOf2_32(Scale);
13176     }
13177   }
13178   return true;
13179 }
13180 
13181 /// isLegalICmpImmediate - Return true if the specified immediate is legal
13182 /// icmp immediate, that is the target has icmp instructions which can compare
13183 /// a register against the immediate without having to materialize the
13184 /// immediate into a register.
13185 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
13186   // Thumb2 and ARM modes can use cmn for negative immediates.
13187   if (!Subtarget->isThumb())
13188     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
13189   if (Subtarget->isThumb2())
13190     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
13191   // Thumb1 doesn't have cmn, and only 8-bit immediates.
13192   return Imm >= 0 && Imm <= 255;
13193 }
13194 
13195 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
13196 /// *or sub* immediate, that is the target has add or sub instructions which can
13197 /// add a register with the immediate without having to materialize the
13198 /// immediate into a register.
13199 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
13200   // Same encoding for add/sub, just flip the sign.
13201   int64_t AbsImm = std::abs(Imm);
13202   if (!Subtarget->isThumb())
13203     return ARM_AM::getSOImmVal(AbsImm) != -1;
13204   if (Subtarget->isThumb2())
13205     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
13206   // Thumb1 only has 8-bit unsigned immediate.
13207   return AbsImm >= 0 && AbsImm <= 255;
13208 }
13209 
13210 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
13211                                       bool isSEXTLoad, SDValue &Base,
13212                                       SDValue &Offset, bool &isInc,
13213                                       SelectionDAG &DAG) {
13214   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13215     return false;
13216 
13217   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
13218     // AddressingMode 3
13219     Base = Ptr->getOperand(0);
13220     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13221       int RHSC = (int)RHS->getZExtValue();
13222       if (RHSC < 0 && RHSC > -256) {
13223         assert(Ptr->getOpcode() == ISD::ADD);
13224         isInc = false;
13225         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13226         return true;
13227       }
13228     }
13229     isInc = (Ptr->getOpcode() == ISD::ADD);
13230     Offset = Ptr->getOperand(1);
13231     return true;
13232   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
13233     // AddressingMode 2
13234     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13235       int RHSC = (int)RHS->getZExtValue();
13236       if (RHSC < 0 && RHSC > -0x1000) {
13237         assert(Ptr->getOpcode() == ISD::ADD);
13238         isInc = false;
13239         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13240         Base = Ptr->getOperand(0);
13241         return true;
13242       }
13243     }
13244 
13245     if (Ptr->getOpcode() == ISD::ADD) {
13246       isInc = true;
13247       ARM_AM::ShiftOpc ShOpcVal=
13248         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
13249       if (ShOpcVal != ARM_AM::no_shift) {
13250         Base = Ptr->getOperand(1);
13251         Offset = Ptr->getOperand(0);
13252       } else {
13253         Base = Ptr->getOperand(0);
13254         Offset = Ptr->getOperand(1);
13255       }
13256       return true;
13257     }
13258 
13259     isInc = (Ptr->getOpcode() == ISD::ADD);
13260     Base = Ptr->getOperand(0);
13261     Offset = Ptr->getOperand(1);
13262     return true;
13263   }
13264 
13265   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
13266   return false;
13267 }
13268 
13269 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
13270                                      bool isSEXTLoad, SDValue &Base,
13271                                      SDValue &Offset, bool &isInc,
13272                                      SelectionDAG &DAG) {
13273   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
13274     return false;
13275 
13276   Base = Ptr->getOperand(0);
13277   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
13278     int RHSC = (int)RHS->getZExtValue();
13279     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
13280       assert(Ptr->getOpcode() == ISD::ADD);
13281       isInc = false;
13282       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13283       return true;
13284     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
13285       isInc = Ptr->getOpcode() == ISD::ADD;
13286       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
13287       return true;
13288     }
13289   }
13290 
13291   return false;
13292 }
13293 
13294 /// getPreIndexedAddressParts - returns true by value, base pointer and
13295 /// offset pointer and addressing mode by reference if the node's address
13296 /// can be legally represented as pre-indexed load / store address.
13297 bool
13298 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
13299                                              SDValue &Offset,
13300                                              ISD::MemIndexedMode &AM,
13301                                              SelectionDAG &DAG) const {
13302   if (Subtarget->isThumb1Only())
13303     return false;
13304 
13305   EVT VT;
13306   SDValue Ptr;
13307   bool isSEXTLoad = false;
13308   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13309     Ptr = LD->getBasePtr();
13310     VT  = LD->getMemoryVT();
13311     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13312   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13313     Ptr = ST->getBasePtr();
13314     VT  = ST->getMemoryVT();
13315   } else
13316     return false;
13317 
13318   bool isInc;
13319   bool isLegal = false;
13320   if (Subtarget->isThumb2())
13321     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13322                                        Offset, isInc, DAG);
13323   else
13324     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13325                                         Offset, isInc, DAG);
13326   if (!isLegal)
13327     return false;
13328 
13329   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
13330   return true;
13331 }
13332 
13333 /// getPostIndexedAddressParts - returns true by value, base pointer and
13334 /// offset pointer and addressing mode by reference if this node can be
13335 /// combined with a load / store to form a post-indexed load / store.
13336 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
13337                                                    SDValue &Base,
13338                                                    SDValue &Offset,
13339                                                    ISD::MemIndexedMode &AM,
13340                                                    SelectionDAG &DAG) const {
13341   EVT VT;
13342   SDValue Ptr;
13343   bool isSEXTLoad = false, isNonExt;
13344   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13345     VT  = LD->getMemoryVT();
13346     Ptr = LD->getBasePtr();
13347     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13348     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
13349   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13350     VT  = ST->getMemoryVT();
13351     Ptr = ST->getBasePtr();
13352     isNonExt = !ST->isTruncatingStore();
13353   } else
13354     return false;
13355 
13356   if (Subtarget->isThumb1Only()) {
13357     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
13358     // must be non-extending/truncating, i32, with an offset of 4.
13359     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
13360     if (Op->getOpcode() != ISD::ADD || !isNonExt)
13361       return false;
13362     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
13363     if (!RHS || RHS->getZExtValue() != 4)
13364       return false;
13365 
13366     Offset = Op->getOperand(1);
13367     Base = Op->getOperand(0);
13368     AM = ISD::POST_INC;
13369     return true;
13370   }
13371 
13372   bool isInc;
13373   bool isLegal = false;
13374   if (Subtarget->isThumb2())
13375     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13376                                        isInc, DAG);
13377   else
13378     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13379                                         isInc, DAG);
13380   if (!isLegal)
13381     return false;
13382 
13383   if (Ptr != Base) {
13384     // Swap base ptr and offset to catch more post-index load / store when
13385     // it's legal. In Thumb2 mode, offset must be an immediate.
13386     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
13387         !Subtarget->isThumb2())
13388       std::swap(Base, Offset);
13389 
13390     // Post-indexed load / store update the base pointer.
13391     if (Ptr != Base)
13392       return false;
13393   }
13394 
13395   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
13396   return true;
13397 }
13398 
13399 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13400                                                       KnownBits &Known,
13401                                                       const APInt &DemandedElts,
13402                                                       const SelectionDAG &DAG,
13403                                                       unsigned Depth) const {
13404   unsigned BitWidth = Known.getBitWidth();
13405   Known.resetAll();
13406   switch (Op.getOpcode()) {
13407   default: break;
13408   case ARMISD::ADDC:
13409   case ARMISD::ADDE:
13410   case ARMISD::SUBC:
13411   case ARMISD::SUBE:
13412     // Special cases when we convert a carry to a boolean.
13413     if (Op.getResNo() == 0) {
13414       SDValue LHS = Op.getOperand(0);
13415       SDValue RHS = Op.getOperand(1);
13416       // (ADDE 0, 0, C) will give us a single bit.
13417       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
13418           isNullConstant(RHS)) {
13419         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13420         return;
13421       }
13422     }
13423     break;
13424   case ARMISD::CMOV: {
13425     // Bits are known zero/one if known on the LHS and RHS.
13426     DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1);
13427     if (Known.isUnknown())
13428       return;
13429 
13430     KnownBits KnownRHS;
13431     DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1);
13432     Known.Zero &= KnownRHS.Zero;
13433     Known.One  &= KnownRHS.One;
13434     return;
13435   }
13436   case ISD::INTRINSIC_W_CHAIN: {
13437     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
13438     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
13439     switch (IntID) {
13440     default: return;
13441     case Intrinsic::arm_ldaex:
13442     case Intrinsic::arm_ldrex: {
13443       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
13444       unsigned MemBits = VT.getScalarSizeInBits();
13445       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
13446       return;
13447     }
13448     }
13449   }
13450   case ARMISD::BFI: {
13451     // Conservatively, we can recurse down the first operand
13452     // and just mask out all affected bits.
13453     DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1);
13454 
13455     // The operand to BFI is already a mask suitable for removing the bits it
13456     // sets.
13457     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
13458     const APInt &Mask = CI->getAPIntValue();
13459     Known.Zero &= Mask;
13460     Known.One &= Mask;
13461     return;
13462   }
13463   }
13464 }
13465 
13466 //===----------------------------------------------------------------------===//
13467 //                           ARM Inline Assembly Support
13468 //===----------------------------------------------------------------------===//
13469 
13470 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
13471   // Looking for "rev" which is V6+.
13472   if (!Subtarget->hasV6Ops())
13473     return false;
13474 
13475   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13476   std::string AsmStr = IA->getAsmString();
13477   SmallVector<StringRef, 4> AsmPieces;
13478   SplitString(AsmStr, AsmPieces, ";\n");
13479 
13480   switch (AsmPieces.size()) {
13481   default: return false;
13482   case 1:
13483     AsmStr = AsmPieces[0];
13484     AsmPieces.clear();
13485     SplitString(AsmStr, AsmPieces, " \t,");
13486 
13487     // rev $0, $1
13488     if (AsmPieces.size() == 3 &&
13489         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
13490         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
13491       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13492       if (Ty && Ty->getBitWidth() == 32)
13493         return IntrinsicLowering::LowerToByteSwap(CI);
13494     }
13495     break;
13496   }
13497 
13498   return false;
13499 }
13500 
13501 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
13502   // At this point, we have to lower this constraint to something else, so we
13503   // lower it to an "r" or "w". However, by doing this we will force the result
13504   // to be in register, while the X constraint is much more permissive.
13505   //
13506   // Although we are correct (we are free to emit anything, without
13507   // constraints), we might break use cases that would expect us to be more
13508   // efficient and emit something else.
13509   if (!Subtarget->hasVFP2())
13510     return "r";
13511   if (ConstraintVT.isFloatingPoint())
13512     return "w";
13513   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
13514      (ConstraintVT.getSizeInBits() == 64 ||
13515       ConstraintVT.getSizeInBits() == 128))
13516     return "w";
13517 
13518   return "r";
13519 }
13520 
13521 /// getConstraintType - Given a constraint letter, return the type of
13522 /// constraint it is for this target.
13523 ARMTargetLowering::ConstraintType
13524 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
13525   if (Constraint.size() == 1) {
13526     switch (Constraint[0]) {
13527     default:  break;
13528     case 'l': return C_RegisterClass;
13529     case 'w': return C_RegisterClass;
13530     case 'h': return C_RegisterClass;
13531     case 'x': return C_RegisterClass;
13532     case 't': return C_RegisterClass;
13533     case 'j': return C_Other; // Constant for movw.
13534       // An address with a single base register. Due to the way we
13535       // currently handle addresses it is the same as an 'r' memory constraint.
13536     case 'Q': return C_Memory;
13537     }
13538   } else if (Constraint.size() == 2) {
13539     switch (Constraint[0]) {
13540     default: break;
13541     // All 'U+' constraints are addresses.
13542     case 'U': return C_Memory;
13543     }
13544   }
13545   return TargetLowering::getConstraintType(Constraint);
13546 }
13547 
13548 /// Examine constraint type and operand type and determine a weight value.
13549 /// This object must already have been set up with the operand type
13550 /// and the current alternative constraint selected.
13551 TargetLowering::ConstraintWeight
13552 ARMTargetLowering::getSingleConstraintMatchWeight(
13553     AsmOperandInfo &info, const char *constraint) const {
13554   ConstraintWeight weight = CW_Invalid;
13555   Value *CallOperandVal = info.CallOperandVal;
13556     // If we don't have a value, we can't do a match,
13557     // but allow it at the lowest weight.
13558   if (!CallOperandVal)
13559     return CW_Default;
13560   Type *type = CallOperandVal->getType();
13561   // Look at the constraint type.
13562   switch (*constraint) {
13563   default:
13564     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13565     break;
13566   case 'l':
13567     if (type->isIntegerTy()) {
13568       if (Subtarget->isThumb())
13569         weight = CW_SpecificReg;
13570       else
13571         weight = CW_Register;
13572     }
13573     break;
13574   case 'w':
13575     if (type->isFloatingPointTy())
13576       weight = CW_Register;
13577     break;
13578   }
13579   return weight;
13580 }
13581 
13582 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
13583 
13584 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
13585     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
13586   if (Constraint.size() == 1) {
13587     // GCC ARM Constraint Letters
13588     switch (Constraint[0]) {
13589     case 'l': // Low regs or general regs.
13590       if (Subtarget->isThumb())
13591         return RCPair(0U, &ARM::tGPRRegClass);
13592       return RCPair(0U, &ARM::GPRRegClass);
13593     case 'h': // High regs or no regs.
13594       if (Subtarget->isThumb())
13595         return RCPair(0U, &ARM::hGPRRegClass);
13596       break;
13597     case 'r':
13598       if (Subtarget->isThumb1Only())
13599         return RCPair(0U, &ARM::tGPRRegClass);
13600       return RCPair(0U, &ARM::GPRRegClass);
13601     case 'w':
13602       if (VT == MVT::Other)
13603         break;
13604       if (VT == MVT::f32)
13605         return RCPair(0U, &ARM::SPRRegClass);
13606       if (VT.getSizeInBits() == 64)
13607         return RCPair(0U, &ARM::DPRRegClass);
13608       if (VT.getSizeInBits() == 128)
13609         return RCPair(0U, &ARM::QPRRegClass);
13610       break;
13611     case 'x':
13612       if (VT == MVT::Other)
13613         break;
13614       if (VT == MVT::f32)
13615         return RCPair(0U, &ARM::SPR_8RegClass);
13616       if (VT.getSizeInBits() == 64)
13617         return RCPair(0U, &ARM::DPR_8RegClass);
13618       if (VT.getSizeInBits() == 128)
13619         return RCPair(0U, &ARM::QPR_8RegClass);
13620       break;
13621     case 't':
13622       if (VT == MVT::Other)
13623         break;
13624       if (VT == MVT::f32 || VT == MVT::i32)
13625         return RCPair(0U, &ARM::SPRRegClass);
13626       if (VT.getSizeInBits() == 64)
13627         return RCPair(0U, &ARM::DPR_VFP2RegClass);
13628       if (VT.getSizeInBits() == 128)
13629         return RCPair(0U, &ARM::QPR_VFP2RegClass);
13630       break;
13631     }
13632   }
13633   if (StringRef("{cc}").equals_lower(Constraint))
13634     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
13635 
13636   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13637 }
13638 
13639 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13640 /// vector.  If it is invalid, don't add anything to Ops.
13641 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13642                                                      std::string &Constraint,
13643                                                      std::vector<SDValue>&Ops,
13644                                                      SelectionDAG &DAG) const {
13645   SDValue Result;
13646 
13647   // Currently only support length 1 constraints.
13648   if (Constraint.length() != 1) return;
13649 
13650   char ConstraintLetter = Constraint[0];
13651   switch (ConstraintLetter) {
13652   default: break;
13653   case 'j':
13654   case 'I': case 'J': case 'K': case 'L':
13655   case 'M': case 'N': case 'O':
13656     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
13657     if (!C)
13658       return;
13659 
13660     int64_t CVal64 = C->getSExtValue();
13661     int CVal = (int) CVal64;
13662     // None of these constraints allow values larger than 32 bits.  Check
13663     // that the value fits in an int.
13664     if (CVal != CVal64)
13665       return;
13666 
13667     switch (ConstraintLetter) {
13668       case 'j':
13669         // Constant suitable for movw, must be between 0 and
13670         // 65535.
13671         if (Subtarget->hasV6T2Ops())
13672           if (CVal >= 0 && CVal <= 65535)
13673             break;
13674         return;
13675       case 'I':
13676         if (Subtarget->isThumb1Only()) {
13677           // This must be a constant between 0 and 255, for ADD
13678           // immediates.
13679           if (CVal >= 0 && CVal <= 255)
13680             break;
13681         } else if (Subtarget->isThumb2()) {
13682           // A constant that can be used as an immediate value in a
13683           // data-processing instruction.
13684           if (ARM_AM::getT2SOImmVal(CVal) != -1)
13685             break;
13686         } else {
13687           // A constant that can be used as an immediate value in a
13688           // data-processing instruction.
13689           if (ARM_AM::getSOImmVal(CVal) != -1)
13690             break;
13691         }
13692         return;
13693 
13694       case 'J':
13695         if (Subtarget->isThumb1Only()) {
13696           // This must be a constant between -255 and -1, for negated ADD
13697           // immediates. This can be used in GCC with an "n" modifier that
13698           // prints the negated value, for use with SUB instructions. It is
13699           // not useful otherwise but is implemented for compatibility.
13700           if (CVal >= -255 && CVal <= -1)
13701             break;
13702         } else {
13703           // This must be a constant between -4095 and 4095. It is not clear
13704           // what this constraint is intended for. Implemented for
13705           // compatibility with GCC.
13706           if (CVal >= -4095 && CVal <= 4095)
13707             break;
13708         }
13709         return;
13710 
13711       case 'K':
13712         if (Subtarget->isThumb1Only()) {
13713           // A 32-bit value where only one byte has a nonzero value. Exclude
13714           // zero to match GCC. This constraint is used by GCC internally for
13715           // constants that can be loaded with a move/shift combination.
13716           // It is not useful otherwise but is implemented for compatibility.
13717           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
13718             break;
13719         } else if (Subtarget->isThumb2()) {
13720           // A constant whose bitwise inverse can be used as an immediate
13721           // value in a data-processing instruction. This can be used in GCC
13722           // with a "B" modifier that prints the inverted value, for use with
13723           // BIC and MVN instructions. It is not useful otherwise but is
13724           // implemented for compatibility.
13725           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
13726             break;
13727         } else {
13728           // A constant whose bitwise inverse can be used as an immediate
13729           // value in a data-processing instruction. This can be used in GCC
13730           // with a "B" modifier that prints the inverted value, for use with
13731           // BIC and MVN instructions. It is not useful otherwise but is
13732           // implemented for compatibility.
13733           if (ARM_AM::getSOImmVal(~CVal) != -1)
13734             break;
13735         }
13736         return;
13737 
13738       case 'L':
13739         if (Subtarget->isThumb1Only()) {
13740           // This must be a constant between -7 and 7,
13741           // for 3-operand ADD/SUB immediate instructions.
13742           if (CVal >= -7 && CVal < 7)
13743             break;
13744         } else if (Subtarget->isThumb2()) {
13745           // A constant whose negation can be used as an immediate value in a
13746           // data-processing instruction. This can be used in GCC with an "n"
13747           // modifier that prints the negated value, for use with SUB
13748           // instructions. It is not useful otherwise but is implemented for
13749           // compatibility.
13750           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
13751             break;
13752         } else {
13753           // A constant whose negation can be used as an immediate value in a
13754           // data-processing instruction. This can be used in GCC with an "n"
13755           // modifier that prints the negated value, for use with SUB
13756           // instructions. It is not useful otherwise but is implemented for
13757           // compatibility.
13758           if (ARM_AM::getSOImmVal(-CVal) != -1)
13759             break;
13760         }
13761         return;
13762 
13763       case 'M':
13764         if (Subtarget->isThumb1Only()) {
13765           // This must be a multiple of 4 between 0 and 1020, for
13766           // ADD sp + immediate.
13767           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
13768             break;
13769         } else {
13770           // A power of two or a constant between 0 and 32.  This is used in
13771           // GCC for the shift amount on shifted register operands, but it is
13772           // useful in general for any shift amounts.
13773           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
13774             break;
13775         }
13776         return;
13777 
13778       case 'N':
13779         if (Subtarget->isThumb()) {  // FIXME thumb2
13780           // This must be a constant between 0 and 31, for shift amounts.
13781           if (CVal >= 0 && CVal <= 31)
13782             break;
13783         }
13784         return;
13785 
13786       case 'O':
13787         if (Subtarget->isThumb()) {  // FIXME thumb2
13788           // This must be a multiple of 4 between -508 and 508, for
13789           // ADD/SUB sp = sp + immediate.
13790           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
13791             break;
13792         }
13793         return;
13794     }
13795     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
13796     break;
13797   }
13798 
13799   if (Result.getNode()) {
13800     Ops.push_back(Result);
13801     return;
13802   }
13803   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13804 }
13805 
13806 static RTLIB::Libcall getDivRemLibcall(
13807     const SDNode *N, MVT::SimpleValueType SVT) {
13808   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13809           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13810          "Unhandled Opcode in getDivRemLibcall");
13811   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13812                   N->getOpcode() == ISD::SREM;
13813   RTLIB::Libcall LC;
13814   switch (SVT) {
13815   default: llvm_unreachable("Unexpected request for libcall!");
13816   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
13817   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
13818   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
13819   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
13820   }
13821   return LC;
13822 }
13823 
13824 static TargetLowering::ArgListTy getDivRemArgList(
13825     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
13826   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13827           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13828          "Unhandled Opcode in getDivRemArgList");
13829   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13830                   N->getOpcode() == ISD::SREM;
13831   TargetLowering::ArgListTy Args;
13832   TargetLowering::ArgListEntry Entry;
13833   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13834     EVT ArgVT = N->getOperand(i).getValueType();
13835     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
13836     Entry.Node = N->getOperand(i);
13837     Entry.Ty = ArgTy;
13838     Entry.IsSExt = isSigned;
13839     Entry.IsZExt = !isSigned;
13840     Args.push_back(Entry);
13841   }
13842   if (Subtarget->isTargetWindows() && Args.size() >= 2)
13843     std::swap(Args[0], Args[1]);
13844   return Args;
13845 }
13846 
13847 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
13848   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
13849           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
13850           Subtarget->isTargetWindows()) &&
13851          "Register-based DivRem lowering only");
13852   unsigned Opcode = Op->getOpcode();
13853   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
13854          "Invalid opcode for Div/Rem lowering");
13855   bool isSigned = (Opcode == ISD::SDIVREM);
13856   EVT VT = Op->getValueType(0);
13857   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
13858   SDLoc dl(Op);
13859 
13860   // If the target has hardware divide, use divide + multiply + subtract:
13861   //     div = a / b
13862   //     rem = a - b * div
13863   //     return {div, rem}
13864   // This should be lowered into UDIV/SDIV + MLS later on.
13865   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
13866                                         : Subtarget->hasDivideInARMMode();
13867   if (hasDivide && Op->getValueType(0).isSimple() &&
13868       Op->getSimpleValueType(0) == MVT::i32) {
13869     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
13870     const SDValue Dividend = Op->getOperand(0);
13871     const SDValue Divisor = Op->getOperand(1);
13872     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
13873     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
13874     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13875 
13876     SDValue Values[2] = {Div, Rem};
13877     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
13878   }
13879 
13880   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
13881                                        VT.getSimpleVT().SimpleTy);
13882   SDValue InChain = DAG.getEntryNode();
13883 
13884   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
13885                                                     DAG.getContext(),
13886                                                     Subtarget);
13887 
13888   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13889                                          getPointerTy(DAG.getDataLayout()));
13890 
13891   Type *RetTy = StructType::get(Ty, Ty);
13892 
13893   if (Subtarget->isTargetWindows())
13894     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
13895 
13896   TargetLowering::CallLoweringInfo CLI(DAG);
13897   CLI.setDebugLoc(dl).setChain(InChain)
13898     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
13899     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13900 
13901   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13902   return CallInfo.first;
13903 }
13904 
13905 // Lowers REM using divmod helpers
13906 // see RTABI section 4.2/4.3
13907 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
13908   // Build return types (div and rem)
13909   std::vector<Type*> RetTyParams;
13910   Type *RetTyElement;
13911 
13912   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
13913   default: llvm_unreachable("Unexpected request for libcall!");
13914   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
13915   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
13916   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
13917   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
13918   }
13919 
13920   RetTyParams.push_back(RetTyElement);
13921   RetTyParams.push_back(RetTyElement);
13922   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
13923   Type *RetTy = StructType::get(*DAG.getContext(), ret);
13924 
13925   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
13926                                                              SimpleTy);
13927   SDValue InChain = DAG.getEntryNode();
13928   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
13929                                                     Subtarget);
13930   bool isSigned = N->getOpcode() == ISD::SREM;
13931   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13932                                          getPointerTy(DAG.getDataLayout()));
13933 
13934   if (Subtarget->isTargetWindows())
13935     InChain = WinDBZCheckDenominator(DAG, N, InChain);
13936 
13937   // Lower call
13938   CallLoweringInfo CLI(DAG);
13939   CLI.setChain(InChain)
13940      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
13941      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
13942   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
13943 
13944   // Return second (rem) result operand (first contains div)
13945   SDNode *ResNode = CallResult.first.getNode();
13946   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
13947   return ResNode->getOperand(1);
13948 }
13949 
13950 SDValue
13951 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
13952   assert(Subtarget->isTargetWindows() && "unsupported target platform");
13953   SDLoc DL(Op);
13954 
13955   // Get the inputs.
13956   SDValue Chain = Op.getOperand(0);
13957   SDValue Size  = Op.getOperand(1);
13958 
13959   if (DAG.getMachineFunction().getFunction().hasFnAttribute(
13960           "no-stack-arg-probe")) {
13961     unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13962     SDValue SP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
13963     Chain = SP.getValue(1);
13964     SP = DAG.getNode(ISD::SUB, DL, MVT::i32, SP, Size);
13965     if (Align)
13966       SP = DAG.getNode(ISD::AND, DL, MVT::i32, SP.getValue(0),
13967                        DAG.getConstant(-(uint64_t)Align, DL, MVT::i32));
13968     Chain = DAG.getCopyToReg(Chain, DL, ARM::SP, SP);
13969     SDValue Ops[2] = { SP, Chain };
13970     return DAG.getMergeValues(Ops, DL);
13971   }
13972 
13973   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
13974                               DAG.getConstant(2, DL, MVT::i32));
13975 
13976   SDValue Flag;
13977   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
13978   Flag = Chain.getValue(1);
13979 
13980   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13981   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
13982 
13983   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
13984   Chain = NewSP.getValue(1);
13985 
13986   SDValue Ops[2] = { NewSP, Chain };
13987   return DAG.getMergeValues(Ops, DL);
13988 }
13989 
13990 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
13991   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
13992          "Unexpected type for custom-lowering FP_EXTEND");
13993 
13994   RTLIB::Libcall LC;
13995   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
13996 
13997   SDValue SrcVal = Op.getOperand(0);
13998   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13999                      SDLoc(Op)).first;
14000 }
14001 
14002 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
14003   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
14004          Subtarget->isFPOnlySP() &&
14005          "Unexpected type for custom-lowering FP_ROUND");
14006 
14007   RTLIB::Libcall LC;
14008   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
14009 
14010   SDValue SrcVal = Op.getOperand(0);
14011   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
14012                      SDLoc(Op)).first;
14013 }
14014 
14015 bool
14016 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
14017   // The ARM target isn't yet aware of offsets.
14018   return false;
14019 }
14020 
14021 bool ARM::isBitFieldInvertedMask(unsigned v) {
14022   if (v == 0xffffffff)
14023     return false;
14024 
14025   // there can be 1's on either or both "outsides", all the "inside"
14026   // bits must be 0's
14027   return isShiftedMask_32(~v);
14028 }
14029 
14030 /// isFPImmLegal - Returns true if the target can instruction select the
14031 /// specified FP immediate natively. If false, the legalizer will
14032 /// materialize the FP immediate as a load from a constant pool.
14033 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
14034   if (!Subtarget->hasVFP3())
14035     return false;
14036   if (VT == MVT::f16 && Subtarget->hasFullFP16())
14037     return ARM_AM::getFP16Imm(Imm) != -1;
14038   if (VT == MVT::f32)
14039     return ARM_AM::getFP32Imm(Imm) != -1;
14040   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
14041     return ARM_AM::getFP64Imm(Imm) != -1;
14042   return false;
14043 }
14044 
14045 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
14046 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
14047 /// specified in the intrinsic calls.
14048 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
14049                                            const CallInst &I,
14050                                            MachineFunction &MF,
14051                                            unsigned Intrinsic) const {
14052   switch (Intrinsic) {
14053   case Intrinsic::arm_neon_vld1:
14054   case Intrinsic::arm_neon_vld2:
14055   case Intrinsic::arm_neon_vld3:
14056   case Intrinsic::arm_neon_vld4:
14057   case Intrinsic::arm_neon_vld2lane:
14058   case Intrinsic::arm_neon_vld3lane:
14059   case Intrinsic::arm_neon_vld4lane: {
14060     Info.opc = ISD::INTRINSIC_W_CHAIN;
14061     // Conservatively set memVT to the entire set of vectors loaded.
14062     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14063     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
14064     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14065     Info.ptrVal = I.getArgOperand(0);
14066     Info.offset = 0;
14067     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
14068     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
14069     // volatile loads with NEON intrinsics not supported
14070     Info.flags = MachineMemOperand::MOLoad;
14071     return true;
14072   }
14073   case Intrinsic::arm_neon_vst1:
14074   case Intrinsic::arm_neon_vst2:
14075   case Intrinsic::arm_neon_vst3:
14076   case Intrinsic::arm_neon_vst4:
14077   case Intrinsic::arm_neon_vst2lane:
14078   case Intrinsic::arm_neon_vst3lane:
14079   case Intrinsic::arm_neon_vst4lane: {
14080     Info.opc = ISD::INTRINSIC_VOID;
14081     // Conservatively set memVT to the entire set of vectors stored.
14082     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14083     unsigned NumElts = 0;
14084     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
14085       Type *ArgTy = I.getArgOperand(ArgI)->getType();
14086       if (!ArgTy->isVectorTy())
14087         break;
14088       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
14089     }
14090     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
14091     Info.ptrVal = I.getArgOperand(0);
14092     Info.offset = 0;
14093     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
14094     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
14095     // volatile stores with NEON intrinsics not supported
14096     Info.flags = MachineMemOperand::MOStore;
14097     return true;
14098   }
14099   case Intrinsic::arm_ldaex:
14100   case Intrinsic::arm_ldrex: {
14101     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14102     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
14103     Info.opc = ISD::INTRINSIC_W_CHAIN;
14104     Info.memVT = MVT::getVT(PtrTy->getElementType());
14105     Info.ptrVal = I.getArgOperand(0);
14106     Info.offset = 0;
14107     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
14108     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
14109     return true;
14110   }
14111   case Intrinsic::arm_stlex:
14112   case Intrinsic::arm_strex: {
14113     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
14114     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
14115     Info.opc = ISD::INTRINSIC_W_CHAIN;
14116     Info.memVT = MVT::getVT(PtrTy->getElementType());
14117     Info.ptrVal = I.getArgOperand(1);
14118     Info.offset = 0;
14119     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
14120     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
14121     return true;
14122   }
14123   case Intrinsic::arm_stlexd:
14124   case Intrinsic::arm_strexd:
14125     Info.opc = ISD::INTRINSIC_W_CHAIN;
14126     Info.memVT = MVT::i64;
14127     Info.ptrVal = I.getArgOperand(2);
14128     Info.offset = 0;
14129     Info.align = 8;
14130     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
14131     return true;
14132 
14133   case Intrinsic::arm_ldaexd:
14134   case Intrinsic::arm_ldrexd:
14135     Info.opc = ISD::INTRINSIC_W_CHAIN;
14136     Info.memVT = MVT::i64;
14137     Info.ptrVal = I.getArgOperand(0);
14138     Info.offset = 0;
14139     Info.align = 8;
14140     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
14141     return true;
14142 
14143   default:
14144     break;
14145   }
14146 
14147   return false;
14148 }
14149 
14150 /// \brief Returns true if it is beneficial to convert a load of a constant
14151 /// to just the constant itself.
14152 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
14153                                                           Type *Ty) const {
14154   assert(Ty->isIntegerTy());
14155 
14156   unsigned Bits = Ty->getPrimitiveSizeInBits();
14157   if (Bits == 0 || Bits > 32)
14158     return false;
14159   return true;
14160 }
14161 
14162 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
14163                                                 unsigned Index) const {
14164   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
14165     return false;
14166 
14167   return (Index == 0 || Index == ResVT.getVectorNumElements());
14168 }
14169 
14170 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
14171                                         ARM_MB::MemBOpt Domain) const {
14172   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14173 
14174   // First, if the target has no DMB, see what fallback we can use.
14175   if (!Subtarget->hasDataBarrier()) {
14176     // Some ARMv6 cpus can support data barriers with an mcr instruction.
14177     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
14178     // here.
14179     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
14180       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
14181       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
14182                         Builder.getInt32(0), Builder.getInt32(7),
14183                         Builder.getInt32(10), Builder.getInt32(5)};
14184       return Builder.CreateCall(MCR, args);
14185     } else {
14186       // Instead of using barriers, atomic accesses on these subtargets use
14187       // libcalls.
14188       llvm_unreachable("makeDMB on a target so old that it has no barriers");
14189     }
14190   } else {
14191     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
14192     // Only a full system barrier exists in the M-class architectures.
14193     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
14194     Constant *CDomain = Builder.getInt32(Domain);
14195     return Builder.CreateCall(DMB, CDomain);
14196   }
14197 }
14198 
14199 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
14200 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
14201                                                  Instruction *Inst,
14202                                                  AtomicOrdering Ord) const {
14203   switch (Ord) {
14204   case AtomicOrdering::NotAtomic:
14205   case AtomicOrdering::Unordered:
14206     llvm_unreachable("Invalid fence: unordered/non-atomic");
14207   case AtomicOrdering::Monotonic:
14208   case AtomicOrdering::Acquire:
14209     return nullptr; // Nothing to do
14210   case AtomicOrdering::SequentiallyConsistent:
14211     if (!Inst->hasAtomicStore())
14212       return nullptr; // Nothing to do
14213     LLVM_FALLTHROUGH;
14214   case AtomicOrdering::Release:
14215   case AtomicOrdering::AcquireRelease:
14216     if (Subtarget->preferISHSTBarriers())
14217       return makeDMB(Builder, ARM_MB::ISHST);
14218     // FIXME: add a comment with a link to documentation justifying this.
14219     else
14220       return makeDMB(Builder, ARM_MB::ISH);
14221   }
14222   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
14223 }
14224 
14225 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
14226                                                   Instruction *Inst,
14227                                                   AtomicOrdering Ord) const {
14228   switch (Ord) {
14229   case AtomicOrdering::NotAtomic:
14230   case AtomicOrdering::Unordered:
14231     llvm_unreachable("Invalid fence: unordered/not-atomic");
14232   case AtomicOrdering::Monotonic:
14233   case AtomicOrdering::Release:
14234     return nullptr; // Nothing to do
14235   case AtomicOrdering::Acquire:
14236   case AtomicOrdering::AcquireRelease:
14237   case AtomicOrdering::SequentiallyConsistent:
14238     return makeDMB(Builder, ARM_MB::ISH);
14239   }
14240   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
14241 }
14242 
14243 // Loads and stores less than 64-bits are already atomic; ones above that
14244 // are doomed anyway, so defer to the default libcall and blame the OS when
14245 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
14246 // anything for those.
14247 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
14248   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
14249   return (Size == 64) && !Subtarget->isMClass();
14250 }
14251 
14252 // Loads and stores less than 64-bits are already atomic; ones above that
14253 // are doomed anyway, so defer to the default libcall and blame the OS when
14254 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
14255 // anything for those.
14256 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
14257 // guarantee, see DDI0406C ARM architecture reference manual,
14258 // sections A8.8.72-74 LDRD)
14259 TargetLowering::AtomicExpansionKind
14260 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
14261   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
14262   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
14263                                                   : AtomicExpansionKind::None;
14264 }
14265 
14266 // For the real atomic operations, we have ldrex/strex up to 32 bits,
14267 // and up to 64 bits on the non-M profiles
14268 TargetLowering::AtomicExpansionKind
14269 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
14270   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
14271   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
14272   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
14273              ? AtomicExpansionKind::LLSC
14274              : AtomicExpansionKind::None;
14275 }
14276 
14277 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
14278     AtomicCmpXchgInst *AI) const {
14279   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
14280   // implement cmpxchg without spilling. If the address being exchanged is also
14281   // on the stack and close enough to the spill slot, this can lead to a
14282   // situation where the monitor always gets cleared and the atomic operation
14283   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
14284   bool hasAtomicCmpXchg =
14285       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
14286   return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg;
14287 }
14288 
14289 bool ARMTargetLowering::shouldInsertFencesForAtomic(
14290     const Instruction *I) const {
14291   return InsertFencesForAtomic;
14292 }
14293 
14294 // This has so far only been implemented for MachO.
14295 bool ARMTargetLowering::useLoadStackGuardNode() const {
14296   return Subtarget->isTargetMachO();
14297 }
14298 
14299 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
14300                                                   unsigned &Cost) const {
14301   // If we do not have NEON, vector types are not natively supported.
14302   if (!Subtarget->hasNEON())
14303     return false;
14304 
14305   // Floating point values and vector values map to the same register file.
14306   // Therefore, although we could do a store extract of a vector type, this is
14307   // better to leave at float as we have more freedom in the addressing mode for
14308   // those.
14309   if (VectorTy->isFPOrFPVectorTy())
14310     return false;
14311 
14312   // If the index is unknown at compile time, this is very expensive to lower
14313   // and it is not possible to combine the store with the extract.
14314   if (!isa<ConstantInt>(Idx))
14315     return false;
14316 
14317   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
14318   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
14319   // We can do a store + vector extract on any vector that fits perfectly in a D
14320   // or Q register.
14321   if (BitWidth == 64 || BitWidth == 128) {
14322     Cost = 0;
14323     return true;
14324   }
14325   return false;
14326 }
14327 
14328 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
14329   return Subtarget->hasV6T2Ops();
14330 }
14331 
14332 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
14333   return Subtarget->hasV6T2Ops();
14334 }
14335 
14336 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
14337                                          AtomicOrdering Ord) const {
14338   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14339   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
14340   bool IsAcquire = isAcquireOrStronger(Ord);
14341 
14342   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
14343   // intrinsic must return {i32, i32} and we have to recombine them into a
14344   // single i64 here.
14345   if (ValTy->getPrimitiveSizeInBits() == 64) {
14346     Intrinsic::ID Int =
14347         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
14348     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
14349 
14350     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14351     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
14352 
14353     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
14354     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
14355     if (!Subtarget->isLittle())
14356       std::swap (Lo, Hi);
14357     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
14358     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
14359     return Builder.CreateOr(
14360         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
14361   }
14362 
14363   Type *Tys[] = { Addr->getType() };
14364   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
14365   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
14366 
14367   return Builder.CreateTruncOrBitCast(
14368       Builder.CreateCall(Ldrex, Addr),
14369       cast<PointerType>(Addr->getType())->getElementType());
14370 }
14371 
14372 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
14373     IRBuilder<> &Builder) const {
14374   if (!Subtarget->hasV7Ops())
14375     return;
14376   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14377   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
14378 }
14379 
14380 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
14381                                                Value *Addr,
14382                                                AtomicOrdering Ord) const {
14383   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14384   bool IsRelease = isReleaseOrStronger(Ord);
14385 
14386   // Since the intrinsics must have legal type, the i64 intrinsics take two
14387   // parameters: "i32, i32". We must marshal Val into the appropriate form
14388   // before the call.
14389   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
14390     Intrinsic::ID Int =
14391         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
14392     Function *Strex = Intrinsic::getDeclaration(M, Int);
14393     Type *Int32Ty = Type::getInt32Ty(M->getContext());
14394 
14395     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
14396     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
14397     if (!Subtarget->isLittle())
14398       std::swap(Lo, Hi);
14399     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14400     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
14401   }
14402 
14403   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
14404   Type *Tys[] = { Addr->getType() };
14405   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
14406 
14407   return Builder.CreateCall(
14408       Strex, {Builder.CreateZExtOrBitCast(
14409                   Val, Strex->getFunctionType()->getParamType(0)),
14410               Addr});
14411 }
14412 
14413 /// A helper function for determining the number of interleaved accesses we
14414 /// will generate when lowering accesses of the given type.
14415 unsigned
14416 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
14417                                              const DataLayout &DL) const {
14418   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
14419 }
14420 
14421 bool ARMTargetLowering::isLegalInterleavedAccessType(
14422     VectorType *VecTy, const DataLayout &DL) const {
14423 
14424   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
14425   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
14426 
14427   // Ensure the vector doesn't have f16 elements. Even though we could do an
14428   // i16 vldN, we can't hold the f16 vectors and will end up converting via
14429   // f32.
14430   if (VecTy->getElementType()->isHalfTy())
14431     return false;
14432 
14433   // Ensure the number of vector elements is greater than 1.
14434   if (VecTy->getNumElements() < 2)
14435     return false;
14436 
14437   // Ensure the element type is legal.
14438   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
14439     return false;
14440 
14441   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
14442   // 128 will be split into multiple interleaved accesses.
14443   return VecSize == 64 || VecSize % 128 == 0;
14444 }
14445 
14446 /// \brief Lower an interleaved load into a vldN intrinsic.
14447 ///
14448 /// E.g. Lower an interleaved load (Factor = 2):
14449 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
14450 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
14451 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
14452 ///
14453 ///      Into:
14454 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
14455 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
14456 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
14457 bool ARMTargetLowering::lowerInterleavedLoad(
14458     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
14459     ArrayRef<unsigned> Indices, unsigned Factor) const {
14460   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14461          "Invalid interleave factor");
14462   assert(!Shuffles.empty() && "Empty shufflevector input");
14463   assert(Shuffles.size() == Indices.size() &&
14464          "Unmatched number of shufflevectors and indices");
14465 
14466   VectorType *VecTy = Shuffles[0]->getType();
14467   Type *EltTy = VecTy->getVectorElementType();
14468 
14469   const DataLayout &DL = LI->getModule()->getDataLayout();
14470 
14471   // Skip if we do not have NEON and skip illegal vector types. We can
14472   // "legalize" wide vector types into multiple interleaved accesses as long as
14473   // the vector types are divisible by 128.
14474   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
14475     return false;
14476 
14477   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
14478 
14479   // A pointer vector can not be the return type of the ldN intrinsics. Need to
14480   // load integer vectors first and then convert to pointer vectors.
14481   if (EltTy->isPointerTy())
14482     VecTy =
14483         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
14484 
14485   IRBuilder<> Builder(LI);
14486 
14487   // The base address of the load.
14488   Value *BaseAddr = LI->getPointerOperand();
14489 
14490   if (NumLoads > 1) {
14491     // If we're going to generate more than one load, reset the sub-vector type
14492     // to something legal.
14493     VecTy = VectorType::get(VecTy->getVectorElementType(),
14494                             VecTy->getVectorNumElements() / NumLoads);
14495 
14496     // We will compute the pointer operand of each load from the original base
14497     // address using GEPs. Cast the base address to a pointer to the scalar
14498     // element type.
14499     BaseAddr = Builder.CreateBitCast(
14500         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
14501                       LI->getPointerAddressSpace()));
14502   }
14503 
14504   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
14505 
14506   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
14507   Type *Tys[] = {VecTy, Int8Ptr};
14508   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
14509                                             Intrinsic::arm_neon_vld3,
14510                                             Intrinsic::arm_neon_vld4};
14511   Function *VldnFunc =
14512       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
14513 
14514   // Holds sub-vectors extracted from the load intrinsic return values. The
14515   // sub-vectors are associated with the shufflevector instructions they will
14516   // replace.
14517   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
14518 
14519   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
14520     // If we're generating more than one load, compute the base address of
14521     // subsequent loads as an offset from the previous.
14522     if (LoadCount > 0)
14523       BaseAddr = Builder.CreateConstGEP1_32(
14524           BaseAddr, VecTy->getVectorNumElements() * Factor);
14525 
14526     SmallVector<Value *, 2> Ops;
14527     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14528     Ops.push_back(Builder.getInt32(LI->getAlignment()));
14529 
14530     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
14531 
14532     // Replace uses of each shufflevector with the corresponding vector loaded
14533     // by ldN.
14534     for (unsigned i = 0; i < Shuffles.size(); i++) {
14535       ShuffleVectorInst *SV = Shuffles[i];
14536       unsigned Index = Indices[i];
14537 
14538       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
14539 
14540       // Convert the integer vector to pointer vector if the element is pointer.
14541       if (EltTy->isPointerTy())
14542         SubVec = Builder.CreateIntToPtr(
14543             SubVec, VectorType::get(SV->getType()->getVectorElementType(),
14544                                     VecTy->getVectorNumElements()));
14545 
14546       SubVecs[SV].push_back(SubVec);
14547     }
14548   }
14549 
14550   // Replace uses of the shufflevector instructions with the sub-vectors
14551   // returned by the load intrinsic. If a shufflevector instruction is
14552   // associated with more than one sub-vector, those sub-vectors will be
14553   // concatenated into a single wide vector.
14554   for (ShuffleVectorInst *SVI : Shuffles) {
14555     auto &SubVec = SubVecs[SVI];
14556     auto *WideVec =
14557         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
14558     SVI->replaceAllUsesWith(WideVec);
14559   }
14560 
14561   return true;
14562 }
14563 
14564 /// \brief Lower an interleaved store into a vstN intrinsic.
14565 ///
14566 /// E.g. Lower an interleaved store (Factor = 3):
14567 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
14568 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
14569 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
14570 ///
14571 ///      Into:
14572 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
14573 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
14574 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
14575 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14576 ///
14577 /// Note that the new shufflevectors will be removed and we'll only generate one
14578 /// vst3 instruction in CodeGen.
14579 ///
14580 /// Example for a more general valid mask (Factor 3). Lower:
14581 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
14582 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
14583 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
14584 ///
14585 ///      Into:
14586 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
14587 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
14588 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
14589 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14590 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
14591                                               ShuffleVectorInst *SVI,
14592                                               unsigned Factor) const {
14593   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14594          "Invalid interleave factor");
14595 
14596   VectorType *VecTy = SVI->getType();
14597   assert(VecTy->getVectorNumElements() % Factor == 0 &&
14598          "Invalid interleaved store");
14599 
14600   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
14601   Type *EltTy = VecTy->getVectorElementType();
14602   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
14603 
14604   const DataLayout &DL = SI->getModule()->getDataLayout();
14605 
14606   // Skip if we do not have NEON and skip illegal vector types. We can
14607   // "legalize" wide vector types into multiple interleaved accesses as long as
14608   // the vector types are divisible by 128.
14609   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
14610     return false;
14611 
14612   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
14613 
14614   Value *Op0 = SVI->getOperand(0);
14615   Value *Op1 = SVI->getOperand(1);
14616   IRBuilder<> Builder(SI);
14617 
14618   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
14619   // vectors to integer vectors.
14620   if (EltTy->isPointerTy()) {
14621     Type *IntTy = DL.getIntPtrType(EltTy);
14622 
14623     // Convert to the corresponding integer vector.
14624     Type *IntVecTy =
14625         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
14626     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
14627     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
14628 
14629     SubVecTy = VectorType::get(IntTy, LaneLen);
14630   }
14631 
14632   // The base address of the store.
14633   Value *BaseAddr = SI->getPointerOperand();
14634 
14635   if (NumStores > 1) {
14636     // If we're going to generate more than one store, reset the lane length
14637     // and sub-vector type to something legal.
14638     LaneLen /= NumStores;
14639     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
14640 
14641     // We will compute the pointer operand of each store from the original base
14642     // address using GEPs. Cast the base address to a pointer to the scalar
14643     // element type.
14644     BaseAddr = Builder.CreateBitCast(
14645         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
14646                       SI->getPointerAddressSpace()));
14647   }
14648 
14649   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
14650 
14651   auto Mask = SVI->getShuffleMask();
14652 
14653   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
14654   Type *Tys[] = {Int8Ptr, SubVecTy};
14655   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
14656                                              Intrinsic::arm_neon_vst3,
14657                                              Intrinsic::arm_neon_vst4};
14658 
14659   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
14660     // If we generating more than one store, we compute the base address of
14661     // subsequent stores as an offset from the previous.
14662     if (StoreCount > 0)
14663       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
14664 
14665     SmallVector<Value *, 6> Ops;
14666     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14667 
14668     Function *VstNFunc =
14669         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
14670 
14671     // Split the shufflevector operands into sub vectors for the new vstN call.
14672     for (unsigned i = 0; i < Factor; i++) {
14673       unsigned IdxI = StoreCount * LaneLen * Factor + i;
14674       if (Mask[IdxI] >= 0) {
14675         Ops.push_back(Builder.CreateShuffleVector(
14676             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
14677       } else {
14678         unsigned StartMask = 0;
14679         for (unsigned j = 1; j < LaneLen; j++) {
14680           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
14681           if (Mask[IdxJ * Factor + IdxI] >= 0) {
14682             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
14683             break;
14684           }
14685         }
14686         // Note: If all elements in a chunk are undefs, StartMask=0!
14687         // Note: Filling undef gaps with random elements is ok, since
14688         // those elements were being written anyway (with undefs).
14689         // In the case of all undefs we're defaulting to using elems from 0
14690         // Note: StartMask cannot be negative, it's checked in
14691         // isReInterleaveMask
14692         Ops.push_back(Builder.CreateShuffleVector(
14693             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
14694       }
14695     }
14696 
14697     Ops.push_back(Builder.getInt32(SI->getAlignment()));
14698     Builder.CreateCall(VstNFunc, Ops);
14699   }
14700   return true;
14701 }
14702 
14703 enum HABaseType {
14704   HA_UNKNOWN = 0,
14705   HA_FLOAT,
14706   HA_DOUBLE,
14707   HA_VECT64,
14708   HA_VECT128
14709 };
14710 
14711 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
14712                                    uint64_t &Members) {
14713   if (auto *ST = dyn_cast<StructType>(Ty)) {
14714     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
14715       uint64_t SubMembers = 0;
14716       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
14717         return false;
14718       Members += SubMembers;
14719     }
14720   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
14721     uint64_t SubMembers = 0;
14722     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
14723       return false;
14724     Members += SubMembers * AT->getNumElements();
14725   } else if (Ty->isFloatTy()) {
14726     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
14727       return false;
14728     Members = 1;
14729     Base = HA_FLOAT;
14730   } else if (Ty->isDoubleTy()) {
14731     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
14732       return false;
14733     Members = 1;
14734     Base = HA_DOUBLE;
14735   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
14736     Members = 1;
14737     switch (Base) {
14738     case HA_FLOAT:
14739     case HA_DOUBLE:
14740       return false;
14741     case HA_VECT64:
14742       return VT->getBitWidth() == 64;
14743     case HA_VECT128:
14744       return VT->getBitWidth() == 128;
14745     case HA_UNKNOWN:
14746       switch (VT->getBitWidth()) {
14747       case 64:
14748         Base = HA_VECT64;
14749         return true;
14750       case 128:
14751         Base = HA_VECT128;
14752         return true;
14753       default:
14754         return false;
14755       }
14756     }
14757   }
14758 
14759   return (Members > 0 && Members <= 4);
14760 }
14761 
14762 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
14763 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
14764 /// passing according to AAPCS rules.
14765 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
14766     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
14767   if (getEffectiveCallingConv(CallConv, isVarArg) !=
14768       CallingConv::ARM_AAPCS_VFP)
14769     return false;
14770 
14771   HABaseType Base = HA_UNKNOWN;
14772   uint64_t Members = 0;
14773   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
14774   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
14775 
14776   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
14777   return IsHA || IsIntArray;
14778 }
14779 
14780 unsigned ARMTargetLowering::getExceptionPointerRegister(
14781     const Constant *PersonalityFn) const {
14782   // Platforms which do not use SjLj EH may return values in these registers
14783   // via the personality function.
14784   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
14785 }
14786 
14787 unsigned ARMTargetLowering::getExceptionSelectorRegister(
14788     const Constant *PersonalityFn) const {
14789   // Platforms which do not use SjLj EH may return values in these registers
14790   // via the personality function.
14791   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
14792 }
14793 
14794 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14795   // Update IsSplitCSR in ARMFunctionInfo.
14796   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
14797   AFI->setIsSplitCSR(true);
14798 }
14799 
14800 void ARMTargetLowering::insertCopiesSplitCSR(
14801     MachineBasicBlock *Entry,
14802     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14803   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
14804   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14805   if (!IStart)
14806     return;
14807 
14808   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
14809   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14810   MachineBasicBlock::iterator MBBI = Entry->begin();
14811   for (const MCPhysReg *I = IStart; *I; ++I) {
14812     const TargetRegisterClass *RC = nullptr;
14813     if (ARM::GPRRegClass.contains(*I))
14814       RC = &ARM::GPRRegClass;
14815     else if (ARM::DPRRegClass.contains(*I))
14816       RC = &ARM::DPRRegClass;
14817     else
14818       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14819 
14820     unsigned NewVR = MRI->createVirtualRegister(RC);
14821     // Create copy from CSR to a virtual register.
14822     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14823     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14824     // nounwind. If we want to generalize this later, we may need to emit
14825     // CFI pseudo-instructions.
14826     assert(Entry->getParent()->getFunction().hasFnAttribute(
14827                Attribute::NoUnwind) &&
14828            "Function should be nounwind in insertCopiesSplitCSR!");
14829     Entry->addLiveIn(*I);
14830     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14831         .addReg(*I);
14832 
14833     // Insert the copy-back instructions right before the terminator.
14834     for (auto *Exit : Exits)
14835       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14836               TII->get(TargetOpcode::COPY), *I)
14837           .addReg(NewVR);
14838   }
14839 }
14840 
14841 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
14842   MF.getFrameInfo().computeMaxCallFrameSize(MF);
14843   TargetLoweringBase::finalizeLowering(MF);
14844 }
14845