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   for (MVT VT : MVT::vector_valuetypes()) {
526     for (MVT InnerVT : MVT::vector_valuetypes()) {
527       setTruncStoreAction(VT, InnerVT, Expand);
528       setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
529       setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
530       setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
531     }
532 
533     setOperationAction(ISD::MULHS, VT, Expand);
534     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
535     setOperationAction(ISD::MULHU, VT, Expand);
536     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
537 
538     setOperationAction(ISD::BSWAP, VT, Expand);
539   }
540 
541   setOperationAction(ISD::ConstantFP, MVT::f32, Custom);
542   setOperationAction(ISD::ConstantFP, MVT::f64, Custom);
543 
544   setOperationAction(ISD::READ_REGISTER, MVT::i64, Custom);
545   setOperationAction(ISD::WRITE_REGISTER, MVT::i64, Custom);
546 
547   if (Subtarget->hasNEON()) {
548     addDRTypeForNEON(MVT::v2f32);
549     addDRTypeForNEON(MVT::v8i8);
550     addDRTypeForNEON(MVT::v4i16);
551     addDRTypeForNEON(MVT::v2i32);
552     addDRTypeForNEON(MVT::v1i64);
553 
554     addQRTypeForNEON(MVT::v4f32);
555     addQRTypeForNEON(MVT::v2f64);
556     addQRTypeForNEON(MVT::v16i8);
557     addQRTypeForNEON(MVT::v8i16);
558     addQRTypeForNEON(MVT::v4i32);
559     addQRTypeForNEON(MVT::v2i64);
560 
561     // v2f64 is legal so that QR subregs can be extracted as f64 elements, but
562     // neither Neon nor VFP support any arithmetic operations on it.
563     // The same with v4f32. But keep in mind that vadd, vsub, vmul are natively
564     // supported for v4f32.
565     setOperationAction(ISD::FADD, MVT::v2f64, Expand);
566     setOperationAction(ISD::FSUB, MVT::v2f64, Expand);
567     setOperationAction(ISD::FMUL, MVT::v2f64, Expand);
568     // FIXME: Code duplication: FDIV and FREM are expanded always, see
569     // ARMTargetLowering::addTypeForNEON method for details.
570     setOperationAction(ISD::FDIV, MVT::v2f64, Expand);
571     setOperationAction(ISD::FREM, MVT::v2f64, Expand);
572     // FIXME: Create unittest.
573     // In another words, find a way when "copysign" appears in DAG with vector
574     // operands.
575     setOperationAction(ISD::FCOPYSIGN, MVT::v2f64, Expand);
576     // FIXME: Code duplication: SETCC has custom operation action, see
577     // ARMTargetLowering::addTypeForNEON method for details.
578     setOperationAction(ISD::SETCC, MVT::v2f64, Expand);
579     // FIXME: Create unittest for FNEG and for FABS.
580     setOperationAction(ISD::FNEG, MVT::v2f64, Expand);
581     setOperationAction(ISD::FABS, MVT::v2f64, Expand);
582     setOperationAction(ISD::FSQRT, MVT::v2f64, Expand);
583     setOperationAction(ISD::FSIN, MVT::v2f64, Expand);
584     setOperationAction(ISD::FCOS, MVT::v2f64, Expand);
585     setOperationAction(ISD::FPOW, MVT::v2f64, Expand);
586     setOperationAction(ISD::FLOG, MVT::v2f64, Expand);
587     setOperationAction(ISD::FLOG2, MVT::v2f64, Expand);
588     setOperationAction(ISD::FLOG10, MVT::v2f64, Expand);
589     setOperationAction(ISD::FEXP, MVT::v2f64, Expand);
590     setOperationAction(ISD::FEXP2, MVT::v2f64, Expand);
591     // FIXME: Create unittest for FCEIL, FTRUNC, FRINT, FNEARBYINT, FFLOOR.
592     setOperationAction(ISD::FCEIL, MVT::v2f64, Expand);
593     setOperationAction(ISD::FTRUNC, MVT::v2f64, Expand);
594     setOperationAction(ISD::FRINT, MVT::v2f64, Expand);
595     setOperationAction(ISD::FNEARBYINT, MVT::v2f64, Expand);
596     setOperationAction(ISD::FFLOOR, MVT::v2f64, Expand);
597     setOperationAction(ISD::FMA, MVT::v2f64, Expand);
598 
599     setOperationAction(ISD::FSQRT, MVT::v4f32, Expand);
600     setOperationAction(ISD::FSIN, MVT::v4f32, Expand);
601     setOperationAction(ISD::FCOS, MVT::v4f32, Expand);
602     setOperationAction(ISD::FPOW, MVT::v4f32, Expand);
603     setOperationAction(ISD::FLOG, MVT::v4f32, Expand);
604     setOperationAction(ISD::FLOG2, MVT::v4f32, Expand);
605     setOperationAction(ISD::FLOG10, MVT::v4f32, Expand);
606     setOperationAction(ISD::FEXP, MVT::v4f32, Expand);
607     setOperationAction(ISD::FEXP2, MVT::v4f32, Expand);
608     setOperationAction(ISD::FCEIL, MVT::v4f32, Expand);
609     setOperationAction(ISD::FTRUNC, MVT::v4f32, Expand);
610     setOperationAction(ISD::FRINT, MVT::v4f32, Expand);
611     setOperationAction(ISD::FNEARBYINT, MVT::v4f32, Expand);
612     setOperationAction(ISD::FFLOOR, MVT::v4f32, Expand);
613 
614     // Mark v2f32 intrinsics.
615     setOperationAction(ISD::FSQRT, MVT::v2f32, Expand);
616     setOperationAction(ISD::FSIN, MVT::v2f32, Expand);
617     setOperationAction(ISD::FCOS, MVT::v2f32, Expand);
618     setOperationAction(ISD::FPOW, MVT::v2f32, Expand);
619     setOperationAction(ISD::FLOG, MVT::v2f32, Expand);
620     setOperationAction(ISD::FLOG2, MVT::v2f32, Expand);
621     setOperationAction(ISD::FLOG10, MVT::v2f32, Expand);
622     setOperationAction(ISD::FEXP, MVT::v2f32, Expand);
623     setOperationAction(ISD::FEXP2, MVT::v2f32, Expand);
624     setOperationAction(ISD::FCEIL, MVT::v2f32, Expand);
625     setOperationAction(ISD::FTRUNC, MVT::v2f32, Expand);
626     setOperationAction(ISD::FRINT, MVT::v2f32, Expand);
627     setOperationAction(ISD::FNEARBYINT, MVT::v2f32, Expand);
628     setOperationAction(ISD::FFLOOR, MVT::v2f32, Expand);
629 
630     // Neon does not support some operations on v1i64 and v2i64 types.
631     setOperationAction(ISD::MUL, MVT::v1i64, Expand);
632     // Custom handling for some quad-vector types to detect VMULL.
633     setOperationAction(ISD::MUL, MVT::v8i16, Custom);
634     setOperationAction(ISD::MUL, MVT::v4i32, Custom);
635     setOperationAction(ISD::MUL, MVT::v2i64, Custom);
636     // Custom handling for some vector types to avoid expensive expansions
637     setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
638     setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
639     setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
640     setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
641     // Neon does not have single instruction SINT_TO_FP and UINT_TO_FP with
642     // a destination type that is wider than the source, and nor does
643     // it have a FP_TO_[SU]INT instruction with a narrower destination than
644     // source.
645     setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
646     setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
647     setOperationAction(ISD::FP_TO_UINT, MVT::v4i16, Custom);
648     setOperationAction(ISD::FP_TO_SINT, MVT::v4i16, Custom);
649 
650     setOperationAction(ISD::FP_ROUND,   MVT::v2f32, Expand);
651     setOperationAction(ISD::FP_EXTEND,  MVT::v2f64, Expand);
652 
653     // NEON does not have single instruction CTPOP for vectors with element
654     // types wider than 8-bits.  However, custom lowering can leverage the
655     // v8i8/v16i8 vcnt instruction.
656     setOperationAction(ISD::CTPOP,      MVT::v2i32, Custom);
657     setOperationAction(ISD::CTPOP,      MVT::v4i32, Custom);
658     setOperationAction(ISD::CTPOP,      MVT::v4i16, Custom);
659     setOperationAction(ISD::CTPOP,      MVT::v8i16, Custom);
660     setOperationAction(ISD::CTPOP,      MVT::v1i64, Expand);
661     setOperationAction(ISD::CTPOP,      MVT::v2i64, Expand);
662 
663     setOperationAction(ISD::CTLZ,       MVT::v1i64, Expand);
664     setOperationAction(ISD::CTLZ,       MVT::v2i64, Expand);
665 
666     // NEON does not have single instruction CTTZ for vectors.
667     setOperationAction(ISD::CTTZ, MVT::v8i8, Custom);
668     setOperationAction(ISD::CTTZ, MVT::v4i16, Custom);
669     setOperationAction(ISD::CTTZ, MVT::v2i32, Custom);
670     setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
671 
672     setOperationAction(ISD::CTTZ, MVT::v16i8, Custom);
673     setOperationAction(ISD::CTTZ, MVT::v8i16, Custom);
674     setOperationAction(ISD::CTTZ, MVT::v4i32, Custom);
675     setOperationAction(ISD::CTTZ, MVT::v2i64, Custom);
676 
677     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i8, Custom);
678     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i16, Custom);
679     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i32, Custom);
680     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v1i64, Custom);
681 
682     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v16i8, Custom);
683     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v8i16, Custom);
684     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v4i32, Custom);
685     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::v2i64, Custom);
686 
687     // NEON only has FMA instructions as of VFP4.
688     if (!Subtarget->hasVFP4()) {
689       setOperationAction(ISD::FMA, MVT::v2f32, Expand);
690       setOperationAction(ISD::FMA, MVT::v4f32, Expand);
691     }
692 
693     setTargetDAGCombine(ISD::INTRINSIC_VOID);
694     setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
695     setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
696     setTargetDAGCombine(ISD::SHL);
697     setTargetDAGCombine(ISD::SRL);
698     setTargetDAGCombine(ISD::SRA);
699     setTargetDAGCombine(ISD::SIGN_EXTEND);
700     setTargetDAGCombine(ISD::ZERO_EXTEND);
701     setTargetDAGCombine(ISD::ANY_EXTEND);
702     setTargetDAGCombine(ISD::BUILD_VECTOR);
703     setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
704     setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
705     setTargetDAGCombine(ISD::STORE);
706     setTargetDAGCombine(ISD::FP_TO_SINT);
707     setTargetDAGCombine(ISD::FP_TO_UINT);
708     setTargetDAGCombine(ISD::FDIV);
709     setTargetDAGCombine(ISD::LOAD);
710 
711     // It is legal to extload from v4i8 to v4i16 or v4i32.
712     for (MVT Ty : {MVT::v8i8, MVT::v4i8, MVT::v2i8, MVT::v4i16, MVT::v2i16,
713                    MVT::v2i32}) {
714       for (MVT VT : MVT::integer_vector_valuetypes()) {
715         setLoadExtAction(ISD::EXTLOAD, VT, Ty, Legal);
716         setLoadExtAction(ISD::ZEXTLOAD, VT, Ty, Legal);
717         setLoadExtAction(ISD::SEXTLOAD, VT, Ty, Legal);
718       }
719     }
720   }
721 
722   if (Subtarget->isFPOnlySP()) {
723     // When targeting a floating-point unit with only single-precision
724     // operations, f64 is legal for the few double-precision instructions which
725     // are present However, no double-precision operations other than moves,
726     // loads and stores are provided by the hardware.
727     setOperationAction(ISD::FADD,       MVT::f64, Expand);
728     setOperationAction(ISD::FSUB,       MVT::f64, Expand);
729     setOperationAction(ISD::FMUL,       MVT::f64, Expand);
730     setOperationAction(ISD::FMA,        MVT::f64, Expand);
731     setOperationAction(ISD::FDIV,       MVT::f64, Expand);
732     setOperationAction(ISD::FREM,       MVT::f64, Expand);
733     setOperationAction(ISD::FCOPYSIGN,  MVT::f64, Expand);
734     setOperationAction(ISD::FGETSIGN,   MVT::f64, Expand);
735     setOperationAction(ISD::FNEG,       MVT::f64, Expand);
736     setOperationAction(ISD::FABS,       MVT::f64, Expand);
737     setOperationAction(ISD::FSQRT,      MVT::f64, Expand);
738     setOperationAction(ISD::FSIN,       MVT::f64, Expand);
739     setOperationAction(ISD::FCOS,       MVT::f64, Expand);
740     setOperationAction(ISD::FPOW,       MVT::f64, Expand);
741     setOperationAction(ISD::FLOG,       MVT::f64, Expand);
742     setOperationAction(ISD::FLOG2,      MVT::f64, Expand);
743     setOperationAction(ISD::FLOG10,     MVT::f64, Expand);
744     setOperationAction(ISD::FEXP,       MVT::f64, Expand);
745     setOperationAction(ISD::FEXP2,      MVT::f64, Expand);
746     setOperationAction(ISD::FCEIL,      MVT::f64, Expand);
747     setOperationAction(ISD::FTRUNC,     MVT::f64, Expand);
748     setOperationAction(ISD::FRINT,      MVT::f64, Expand);
749     setOperationAction(ISD::FNEARBYINT, MVT::f64, Expand);
750     setOperationAction(ISD::FFLOOR,     MVT::f64, Expand);
751     setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
752     setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
753     setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
754     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
755     setOperationAction(ISD::FP_TO_SINT, MVT::f64, Custom);
756     setOperationAction(ISD::FP_TO_UINT, MVT::f64, Custom);
757     setOperationAction(ISD::FP_ROUND,   MVT::f32, Custom);
758     setOperationAction(ISD::FP_EXTEND,  MVT::f64, Custom);
759   }
760 
761   computeRegisterProperties(Subtarget->getRegisterInfo());
762 
763   // ARM does not have floating-point extending loads.
764   for (MVT VT : MVT::fp_valuetypes()) {
765     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
766     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
767   }
768 
769   // ... or truncating stores
770   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
771   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
772   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
773 
774   // ARM does not have i1 sign extending load.
775   for (MVT VT : MVT::integer_valuetypes())
776     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
777 
778   // ARM supports all 4 flavors of integer indexed load / store.
779   if (!Subtarget->isThumb1Only()) {
780     for (unsigned im = (unsigned)ISD::PRE_INC;
781          im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
782       setIndexedLoadAction(im,  MVT::i1,  Legal);
783       setIndexedLoadAction(im,  MVT::i8,  Legal);
784       setIndexedLoadAction(im,  MVT::i16, Legal);
785       setIndexedLoadAction(im,  MVT::i32, Legal);
786       setIndexedStoreAction(im, MVT::i1,  Legal);
787       setIndexedStoreAction(im, MVT::i8,  Legal);
788       setIndexedStoreAction(im, MVT::i16, Legal);
789       setIndexedStoreAction(im, MVT::i32, Legal);
790     }
791   } else {
792     // Thumb-1 has limited post-inc load/store support - LDM r0!, {r1}.
793     setIndexedLoadAction(ISD::POST_INC, MVT::i32,  Legal);
794     setIndexedStoreAction(ISD::POST_INC, MVT::i32,  Legal);
795   }
796 
797   setOperationAction(ISD::SADDO, MVT::i32, Custom);
798   setOperationAction(ISD::UADDO, MVT::i32, Custom);
799   setOperationAction(ISD::SSUBO, MVT::i32, Custom);
800   setOperationAction(ISD::USUBO, MVT::i32, Custom);
801 
802   setOperationAction(ISD::ADDCARRY, MVT::i32, Custom);
803   setOperationAction(ISD::SUBCARRY, MVT::i32, Custom);
804 
805   // i64 operation support.
806   setOperationAction(ISD::MUL,     MVT::i64, Expand);
807   setOperationAction(ISD::MULHU,   MVT::i32, Expand);
808   if (Subtarget->isThumb1Only()) {
809     setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
810     setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
811   }
812   if (Subtarget->isThumb1Only() || !Subtarget->hasV6Ops()
813       || (Subtarget->isThumb2() && !Subtarget->hasDSP()))
814     setOperationAction(ISD::MULHS, MVT::i32, Expand);
815 
816   setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
817   setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
818   setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
819   setOperationAction(ISD::SRL,       MVT::i64, Custom);
820   setOperationAction(ISD::SRA,       MVT::i64, Custom);
821   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
822 
823   // Expand to __aeabi_l{lsl,lsr,asr} calls for Thumb1.
824   if (Subtarget->isThumb1Only()) {
825     setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
826     setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
827     setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
828   }
829 
830   setOperationAction(ISD::ADDC,      MVT::i32, Custom);
831   setOperationAction(ISD::ADDE,      MVT::i32, Custom);
832   setOperationAction(ISD::SUBC,      MVT::i32, Custom);
833   setOperationAction(ISD::SUBE,      MVT::i32, Custom);
834 
835   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops())
836     setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
837 
838   // ARM does not have ROTL.
839   setOperationAction(ISD::ROTL, MVT::i32, Expand);
840   for (MVT VT : MVT::vector_valuetypes()) {
841     setOperationAction(ISD::ROTL, VT, Expand);
842     setOperationAction(ISD::ROTR, VT, Expand);
843   }
844   setOperationAction(ISD::CTTZ,  MVT::i32, Custom);
845   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
846   if (!Subtarget->hasV5TOps() || Subtarget->isThumb1Only())
847     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
848 
849   // @llvm.readcyclecounter requires the Performance Monitors extension.
850   // Default to the 0 expansion on unsupported platforms.
851   // FIXME: Technically there are older ARM CPUs that have
852   // implementation-specific ways of obtaining this information.
853   if (Subtarget->hasPerfMon())
854     setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Custom);
855 
856   // Only ARMv6 has BSWAP.
857   if (!Subtarget->hasV6Ops())
858     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
859 
860   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
861                                         : Subtarget->hasDivideInARMMode();
862   if (!hasDivide) {
863     // These are expanded into libcalls if the cpu doesn't have HW divider.
864     setOperationAction(ISD::SDIV,  MVT::i32, LibCall);
865     setOperationAction(ISD::UDIV,  MVT::i32, LibCall);
866   }
867 
868   if (Subtarget->isTargetWindows() && !Subtarget->hasDivideInThumbMode()) {
869     setOperationAction(ISD::SDIV, MVT::i32, Custom);
870     setOperationAction(ISD::UDIV, MVT::i32, Custom);
871 
872     setOperationAction(ISD::SDIV, MVT::i64, Custom);
873     setOperationAction(ISD::UDIV, MVT::i64, Custom);
874   }
875 
876   setOperationAction(ISD::SREM,  MVT::i32, Expand);
877   setOperationAction(ISD::UREM,  MVT::i32, Expand);
878 
879   // Register based DivRem for AEABI (RTABI 4.2)
880   if (Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
881       Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
882       Subtarget->isTargetWindows()) {
883     setOperationAction(ISD::SREM, MVT::i64, Custom);
884     setOperationAction(ISD::UREM, MVT::i64, Custom);
885     HasStandaloneRem = false;
886 
887     if (Subtarget->isTargetWindows()) {
888       const struct {
889         const RTLIB::Libcall Op;
890         const char * const Name;
891         const CallingConv::ID CC;
892       } LibraryCalls[] = {
893         { RTLIB::SDIVREM_I8, "__rt_sdiv", CallingConv::ARM_AAPCS },
894         { RTLIB::SDIVREM_I16, "__rt_sdiv", CallingConv::ARM_AAPCS },
895         { RTLIB::SDIVREM_I32, "__rt_sdiv", CallingConv::ARM_AAPCS },
896         { RTLIB::SDIVREM_I64, "__rt_sdiv64", CallingConv::ARM_AAPCS },
897 
898         { RTLIB::UDIVREM_I8, "__rt_udiv", CallingConv::ARM_AAPCS },
899         { RTLIB::UDIVREM_I16, "__rt_udiv", CallingConv::ARM_AAPCS },
900         { RTLIB::UDIVREM_I32, "__rt_udiv", CallingConv::ARM_AAPCS },
901         { RTLIB::UDIVREM_I64, "__rt_udiv64", CallingConv::ARM_AAPCS },
902       };
903 
904       for (const auto &LC : LibraryCalls) {
905         setLibcallName(LC.Op, LC.Name);
906         setLibcallCallingConv(LC.Op, LC.CC);
907       }
908     } else {
909       const struct {
910         const RTLIB::Libcall Op;
911         const char * const Name;
912         const CallingConv::ID CC;
913       } LibraryCalls[] = {
914         { RTLIB::SDIVREM_I8, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
915         { RTLIB::SDIVREM_I16, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
916         { RTLIB::SDIVREM_I32, "__aeabi_idivmod", CallingConv::ARM_AAPCS },
917         { RTLIB::SDIVREM_I64, "__aeabi_ldivmod", CallingConv::ARM_AAPCS },
918 
919         { RTLIB::UDIVREM_I8, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
920         { RTLIB::UDIVREM_I16, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
921         { RTLIB::UDIVREM_I32, "__aeabi_uidivmod", CallingConv::ARM_AAPCS },
922         { RTLIB::UDIVREM_I64, "__aeabi_uldivmod", CallingConv::ARM_AAPCS },
923       };
924 
925       for (const auto &LC : LibraryCalls) {
926         setLibcallName(LC.Op, LC.Name);
927         setLibcallCallingConv(LC.Op, LC.CC);
928       }
929     }
930 
931     setOperationAction(ISD::SDIVREM, MVT::i32, Custom);
932     setOperationAction(ISD::UDIVREM, MVT::i32, Custom);
933     setOperationAction(ISD::SDIVREM, MVT::i64, Custom);
934     setOperationAction(ISD::UDIVREM, MVT::i64, Custom);
935   } else {
936     setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
937     setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
938   }
939 
940   if (Subtarget->isTargetWindows() && Subtarget->getTargetTriple().isOSMSVCRT())
941     for (auto &VT : {MVT::f32, MVT::f64})
942       setOperationAction(ISD::FPOWI, VT, Custom);
943 
944   setOperationAction(ISD::GlobalAddress, MVT::i32,   Custom);
945   setOperationAction(ISD::ConstantPool,  MVT::i32,   Custom);
946   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
947   setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
948 
949   setOperationAction(ISD::TRAP, MVT::Other, Legal);
950 
951   // Use the default implementation.
952   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
953   setOperationAction(ISD::VAARG,              MVT::Other, Expand);
954   setOperationAction(ISD::VACOPY,             MVT::Other, Expand);
955   setOperationAction(ISD::VAEND,              MVT::Other, Expand);
956   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
957   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
958 
959   if (Subtarget->isTargetWindows())
960     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
961   else
962     setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
963 
964   // ARMv6 Thumb1 (except for CPUs that support dmb / dsb) and earlier use
965   // the default expansion.
966   InsertFencesForAtomic = false;
967   if (Subtarget->hasAnyDataBarrier() &&
968       (!Subtarget->isThumb() || Subtarget->hasV8MBaselineOps())) {
969     // ATOMIC_FENCE needs custom lowering; the others should have been expanded
970     // to ldrex/strex loops already.
971     setOperationAction(ISD::ATOMIC_FENCE,     MVT::Other, Custom);
972     if (!Subtarget->isThumb() || !Subtarget->isMClass())
973       setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i64, Custom);
974 
975     // On v8, we have particularly efficient implementations of atomic fences
976     // if they can be combined with nearby atomic loads and stores.
977     if (!Subtarget->hasV8Ops() || getTargetMachine().getOptLevel() == 0) {
978       // Automatically insert fences (dmb ish) around ATOMIC_SWAP etc.
979       InsertFencesForAtomic = true;
980     }
981   } else {
982     // If there's anything we can use as a barrier, go through custom lowering
983     // for ATOMIC_FENCE.
984     // If target has DMB in thumb, Fences can be inserted.
985     if (Subtarget->hasDataBarrier())
986       InsertFencesForAtomic = true;
987 
988     setOperationAction(ISD::ATOMIC_FENCE,   MVT::Other,
989                        Subtarget->hasAnyDataBarrier() ? Custom : Expand);
990 
991     // Set them all for expansion, which will force libcalls.
992     setOperationAction(ISD::ATOMIC_CMP_SWAP,  MVT::i32, Expand);
993     setOperationAction(ISD::ATOMIC_SWAP,      MVT::i32, Expand);
994     setOperationAction(ISD::ATOMIC_LOAD_ADD,  MVT::i32, Expand);
995     setOperationAction(ISD::ATOMIC_LOAD_SUB,  MVT::i32, Expand);
996     setOperationAction(ISD::ATOMIC_LOAD_AND,  MVT::i32, Expand);
997     setOperationAction(ISD::ATOMIC_LOAD_OR,   MVT::i32, Expand);
998     setOperationAction(ISD::ATOMIC_LOAD_XOR,  MVT::i32, Expand);
999     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
1000     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
1001     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
1002     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
1003     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
1004     // Mark ATOMIC_LOAD and ATOMIC_STORE custom so we can handle the
1005     // Unordered/Monotonic case.
1006     if (!InsertFencesForAtomic) {
1007       setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Custom);
1008       setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Custom);
1009     }
1010   }
1011 
1012   setOperationAction(ISD::PREFETCH,         MVT::Other, Custom);
1013 
1014   // Requires SXTB/SXTH, available on v6 and up in both ARM and Thumb modes.
1015   if (!Subtarget->hasV6Ops()) {
1016     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1017     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
1018   }
1019   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
1020 
1021   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1022       !Subtarget->isThumb1Only()) {
1023     // Turn f64->i64 into VMOVRRD, i64 -> f64 to VMOVDRR
1024     // iff target supports vfp2.
1025     setOperationAction(ISD::BITCAST, MVT::i64, Custom);
1026     setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
1027   }
1028 
1029   // We want to custom lower some of our intrinsics.
1030   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1031   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
1032   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
1033   setOperationAction(ISD::EH_SJLJ_SETUP_DISPATCH, MVT::Other, Custom);
1034   if (Subtarget->useSjLjEH())
1035     setLibcallName(RTLIB::UNWIND_RESUME, "_Unwind_SjLj_Resume");
1036 
1037   setOperationAction(ISD::SETCC,     MVT::i32, Expand);
1038   setOperationAction(ISD::SETCC,     MVT::f32, Expand);
1039   setOperationAction(ISD::SETCC,     MVT::f64, Expand);
1040   setOperationAction(ISD::SELECT,    MVT::i32, Custom);
1041   setOperationAction(ISD::SELECT,    MVT::f32, Custom);
1042   setOperationAction(ISD::SELECT,    MVT::f64, Custom);
1043   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1044   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1045   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1046 
1047   // Thumb-1 cannot currently select ARMISD::SUBE.
1048   if (!Subtarget->isThumb1Only())
1049     setOperationAction(ISD::SETCCE, MVT::i32, Custom);
1050 
1051   setOperationAction(ISD::BRCOND,    MVT::Other, Custom);
1052   setOperationAction(ISD::BR_CC,     MVT::i32,   Custom);
1053   setOperationAction(ISD::BR_CC,     MVT::f32,   Custom);
1054   setOperationAction(ISD::BR_CC,     MVT::f64,   Custom);
1055   setOperationAction(ISD::BR_JT,     MVT::Other, Custom);
1056 
1057   // We don't support sin/cos/fmod/copysign/pow
1058   setOperationAction(ISD::FSIN,      MVT::f64, Expand);
1059   setOperationAction(ISD::FSIN,      MVT::f32, Expand);
1060   setOperationAction(ISD::FCOS,      MVT::f32, Expand);
1061   setOperationAction(ISD::FCOS,      MVT::f64, Expand);
1062   setOperationAction(ISD::FSINCOS,   MVT::f64, Expand);
1063   setOperationAction(ISD::FSINCOS,   MVT::f32, Expand);
1064   setOperationAction(ISD::FREM,      MVT::f64, Expand);
1065   setOperationAction(ISD::FREM,      MVT::f32, Expand);
1066   if (!Subtarget->useSoftFloat() && Subtarget->hasVFP2() &&
1067       !Subtarget->isThumb1Only()) {
1068     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
1069     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
1070   }
1071   setOperationAction(ISD::FPOW,      MVT::f64, Expand);
1072   setOperationAction(ISD::FPOW,      MVT::f32, Expand);
1073 
1074   if (!Subtarget->hasVFP4()) {
1075     setOperationAction(ISD::FMA, MVT::f64, Expand);
1076     setOperationAction(ISD::FMA, MVT::f32, Expand);
1077   }
1078 
1079   // Various VFP goodness
1080   if (!Subtarget->useSoftFloat() && !Subtarget->isThumb1Only()) {
1081     // FP-ARMv8 adds f64 <-> f16 conversion. Before that it should be expanded.
1082     if (!Subtarget->hasFPARMv8() || Subtarget->isFPOnlySP()) {
1083       setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
1084       setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
1085     }
1086 
1087     // fp16 is a special v7 extension that adds f16 <-> f32 conversions.
1088     if (!Subtarget->hasFP16()) {
1089       setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
1090       setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
1091     }
1092   }
1093 
1094   // Use __sincos_stret if available.
1095   if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
1096       getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
1097     setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1098     setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1099   }
1100 
1101   // FP-ARMv8 implements a lot of rounding-like FP operations.
1102   if (Subtarget->hasFPARMv8()) {
1103     setOperationAction(ISD::FFLOOR, MVT::f32, Legal);
1104     setOperationAction(ISD::FCEIL, MVT::f32, Legal);
1105     setOperationAction(ISD::FROUND, MVT::f32, Legal);
1106     setOperationAction(ISD::FTRUNC, MVT::f32, Legal);
1107     setOperationAction(ISD::FNEARBYINT, MVT::f32, Legal);
1108     setOperationAction(ISD::FRINT, MVT::f32, Legal);
1109     setOperationAction(ISD::FMINNUM, MVT::f32, Legal);
1110     setOperationAction(ISD::FMAXNUM, MVT::f32, Legal);
1111     setOperationAction(ISD::FMINNUM, MVT::v2f32, Legal);
1112     setOperationAction(ISD::FMAXNUM, MVT::v2f32, Legal);
1113     setOperationAction(ISD::FMINNUM, MVT::v4f32, Legal);
1114     setOperationAction(ISD::FMAXNUM, MVT::v4f32, Legal);
1115 
1116     if (!Subtarget->isFPOnlySP()) {
1117       setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
1118       setOperationAction(ISD::FCEIL, MVT::f64, Legal);
1119       setOperationAction(ISD::FROUND, MVT::f64, Legal);
1120       setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
1121       setOperationAction(ISD::FNEARBYINT, MVT::f64, Legal);
1122       setOperationAction(ISD::FRINT, MVT::f64, Legal);
1123       setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
1124       setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
1125     }
1126   }
1127 
1128   if (Subtarget->hasNEON()) {
1129     // vmin and vmax aren't available in a scalar form, so we use
1130     // a NEON instruction with an undef lane instead.
1131     setOperationAction(ISD::FMINNAN, MVT::f32, Legal);
1132     setOperationAction(ISD::FMAXNAN, MVT::f32, Legal);
1133     setOperationAction(ISD::FMINNAN, MVT::v2f32, Legal);
1134     setOperationAction(ISD::FMAXNAN, MVT::v2f32, Legal);
1135     setOperationAction(ISD::FMINNAN, MVT::v4f32, Legal);
1136     setOperationAction(ISD::FMAXNAN, MVT::v4f32, Legal);
1137   }
1138 
1139   // We have target-specific dag combine patterns for the following nodes:
1140   // ARMISD::VMOVRRD  - No need to call setTargetDAGCombine
1141   setTargetDAGCombine(ISD::ADD);
1142   setTargetDAGCombine(ISD::SUB);
1143   setTargetDAGCombine(ISD::MUL);
1144   setTargetDAGCombine(ISD::AND);
1145   setTargetDAGCombine(ISD::OR);
1146   setTargetDAGCombine(ISD::XOR);
1147 
1148   if (Subtarget->hasV6Ops())
1149     setTargetDAGCombine(ISD::SRL);
1150 
1151   setStackPointerRegisterToSaveRestore(ARM::SP);
1152 
1153   if (Subtarget->useSoftFloat() || Subtarget->isThumb1Only() ||
1154       !Subtarget->hasVFP2())
1155     setSchedulingPreference(Sched::RegPressure);
1156   else
1157     setSchedulingPreference(Sched::Hybrid);
1158 
1159   //// temporary - rewrite interface to use type
1160   MaxStoresPerMemset = 8;
1161   MaxStoresPerMemsetOptSize = 4;
1162   MaxStoresPerMemcpy = 4; // For @llvm.memcpy -> sequence of stores
1163   MaxStoresPerMemcpyOptSize = 2;
1164   MaxStoresPerMemmove = 4; // For @llvm.memmove -> sequence of stores
1165   MaxStoresPerMemmoveOptSize = 2;
1166 
1167   // On ARM arguments smaller than 4 bytes are extended, so all arguments
1168   // are at least 4 bytes aligned.
1169   setMinStackArgumentAlignment(4);
1170 
1171   // Prefer likely predicted branches to selects on out-of-order cores.
1172   PredictableSelectIsExpensive = Subtarget->getSchedModel().isOutOfOrder();
1173 
1174   setMinFunctionAlignment(Subtarget->isThumb() ? 1 : 2);
1175 }
1176 
1177 bool ARMTargetLowering::useSoftFloat() const {
1178   return Subtarget->useSoftFloat();
1179 }
1180 
1181 // FIXME: It might make sense to define the representative register class as the
1182 // nearest super-register that has a non-null superset. For example, DPR_VFP2 is
1183 // a super-register of SPR, and DPR is a superset if DPR_VFP2. Consequently,
1184 // SPR's representative would be DPR_VFP2. This should work well if register
1185 // pressure tracking were modified such that a register use would increment the
1186 // pressure of the register class's representative and all of it's super
1187 // classes' representatives transitively. We have not implemented this because
1188 // of the difficulty prior to coalescing of modeling operand register classes
1189 // due to the common occurrence of cross class copies and subregister insertions
1190 // and extractions.
1191 std::pair<const TargetRegisterClass *, uint8_t>
1192 ARMTargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1193                                            MVT VT) const {
1194   const TargetRegisterClass *RRC = nullptr;
1195   uint8_t Cost = 1;
1196   switch (VT.SimpleTy) {
1197   default:
1198     return TargetLowering::findRepresentativeClass(TRI, VT);
1199   // Use DPR as representative register class for all floating point
1200   // and vector types. Since there are 32 SPR registers and 32 DPR registers so
1201   // the cost is 1 for both f32 and f64.
1202   case MVT::f32: case MVT::f64: case MVT::v8i8: case MVT::v4i16:
1203   case MVT::v2i32: case MVT::v1i64: case MVT::v2f32:
1204     RRC = &ARM::DPRRegClass;
1205     // When NEON is used for SP, only half of the register file is available
1206     // because operations that define both SP and DP results will be constrained
1207     // to the VFP2 class (D0-D15). We currently model this constraint prior to
1208     // coalescing by double-counting the SP regs. See the FIXME above.
1209     if (Subtarget->useNEONForSinglePrecisionFP())
1210       Cost = 2;
1211     break;
1212   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1213   case MVT::v4f32: case MVT::v2f64:
1214     RRC = &ARM::DPRRegClass;
1215     Cost = 2;
1216     break;
1217   case MVT::v4i64:
1218     RRC = &ARM::DPRRegClass;
1219     Cost = 4;
1220     break;
1221   case MVT::v8i64:
1222     RRC = &ARM::DPRRegClass;
1223     Cost = 8;
1224     break;
1225   }
1226   return std::make_pair(RRC, Cost);
1227 }
1228 
1229 const char *ARMTargetLowering::getTargetNodeName(unsigned Opcode) const {
1230   switch ((ARMISD::NodeType)Opcode) {
1231   case ARMISD::FIRST_NUMBER:  break;
1232   case ARMISD::Wrapper:       return "ARMISD::Wrapper";
1233   case ARMISD::WrapperPIC:    return "ARMISD::WrapperPIC";
1234   case ARMISD::WrapperJT:     return "ARMISD::WrapperJT";
1235   case ARMISD::COPY_STRUCT_BYVAL: return "ARMISD::COPY_STRUCT_BYVAL";
1236   case ARMISD::CALL:          return "ARMISD::CALL";
1237   case ARMISD::CALL_PRED:     return "ARMISD::CALL_PRED";
1238   case ARMISD::CALL_NOLINK:   return "ARMISD::CALL_NOLINK";
1239   case ARMISD::BRCOND:        return "ARMISD::BRCOND";
1240   case ARMISD::BR_JT:         return "ARMISD::BR_JT";
1241   case ARMISD::BR2_JT:        return "ARMISD::BR2_JT";
1242   case ARMISD::RET_FLAG:      return "ARMISD::RET_FLAG";
1243   case ARMISD::INTRET_FLAG:   return "ARMISD::INTRET_FLAG";
1244   case ARMISD::PIC_ADD:       return "ARMISD::PIC_ADD";
1245   case ARMISD::CMP:           return "ARMISD::CMP";
1246   case ARMISD::CMN:           return "ARMISD::CMN";
1247   case ARMISD::CMPZ:          return "ARMISD::CMPZ";
1248   case ARMISD::CMPFP:         return "ARMISD::CMPFP";
1249   case ARMISD::CMPFPw0:       return "ARMISD::CMPFPw0";
1250   case ARMISD::BCC_i64:       return "ARMISD::BCC_i64";
1251   case ARMISD::FMSTAT:        return "ARMISD::FMSTAT";
1252 
1253   case ARMISD::CMOV:          return "ARMISD::CMOV";
1254 
1255   case ARMISD::SSAT:          return "ARMISD::SSAT";
1256   case ARMISD::USAT:          return "ARMISD::USAT";
1257 
1258   case ARMISD::SRL_FLAG:      return "ARMISD::SRL_FLAG";
1259   case ARMISD::SRA_FLAG:      return "ARMISD::SRA_FLAG";
1260   case ARMISD::RRX:           return "ARMISD::RRX";
1261 
1262   case ARMISD::ADDC:          return "ARMISD::ADDC";
1263   case ARMISD::ADDE:          return "ARMISD::ADDE";
1264   case ARMISD::SUBC:          return "ARMISD::SUBC";
1265   case ARMISD::SUBE:          return "ARMISD::SUBE";
1266 
1267   case ARMISD::VMOVRRD:       return "ARMISD::VMOVRRD";
1268   case ARMISD::VMOVDRR:       return "ARMISD::VMOVDRR";
1269 
1270   case ARMISD::EH_SJLJ_SETJMP: return "ARMISD::EH_SJLJ_SETJMP";
1271   case ARMISD::EH_SJLJ_LONGJMP: return "ARMISD::EH_SJLJ_LONGJMP";
1272   case ARMISD::EH_SJLJ_SETUP_DISPATCH: return "ARMISD::EH_SJLJ_SETUP_DISPATCH";
1273 
1274   case ARMISD::TC_RETURN:     return "ARMISD::TC_RETURN";
1275 
1276   case ARMISD::THREAD_POINTER:return "ARMISD::THREAD_POINTER";
1277 
1278   case ARMISD::DYN_ALLOC:     return "ARMISD::DYN_ALLOC";
1279 
1280   case ARMISD::MEMBARRIER_MCR: return "ARMISD::MEMBARRIER_MCR";
1281 
1282   case ARMISD::PRELOAD:       return "ARMISD::PRELOAD";
1283 
1284   case ARMISD::WIN__CHKSTK:   return "ARMISD::WIN__CHKSTK";
1285   case ARMISD::WIN__DBZCHK:   return "ARMISD::WIN__DBZCHK";
1286 
1287   case ARMISD::VCEQ:          return "ARMISD::VCEQ";
1288   case ARMISD::VCEQZ:         return "ARMISD::VCEQZ";
1289   case ARMISD::VCGE:          return "ARMISD::VCGE";
1290   case ARMISD::VCGEZ:         return "ARMISD::VCGEZ";
1291   case ARMISD::VCLEZ:         return "ARMISD::VCLEZ";
1292   case ARMISD::VCGEU:         return "ARMISD::VCGEU";
1293   case ARMISD::VCGT:          return "ARMISD::VCGT";
1294   case ARMISD::VCGTZ:         return "ARMISD::VCGTZ";
1295   case ARMISD::VCLTZ:         return "ARMISD::VCLTZ";
1296   case ARMISD::VCGTU:         return "ARMISD::VCGTU";
1297   case ARMISD::VTST:          return "ARMISD::VTST";
1298 
1299   case ARMISD::VSHL:          return "ARMISD::VSHL";
1300   case ARMISD::VSHRs:         return "ARMISD::VSHRs";
1301   case ARMISD::VSHRu:         return "ARMISD::VSHRu";
1302   case ARMISD::VRSHRs:        return "ARMISD::VRSHRs";
1303   case ARMISD::VRSHRu:        return "ARMISD::VRSHRu";
1304   case ARMISD::VRSHRN:        return "ARMISD::VRSHRN";
1305   case ARMISD::VQSHLs:        return "ARMISD::VQSHLs";
1306   case ARMISD::VQSHLu:        return "ARMISD::VQSHLu";
1307   case ARMISD::VQSHLsu:       return "ARMISD::VQSHLsu";
1308   case ARMISD::VQSHRNs:       return "ARMISD::VQSHRNs";
1309   case ARMISD::VQSHRNu:       return "ARMISD::VQSHRNu";
1310   case ARMISD::VQSHRNsu:      return "ARMISD::VQSHRNsu";
1311   case ARMISD::VQRSHRNs:      return "ARMISD::VQRSHRNs";
1312   case ARMISD::VQRSHRNu:      return "ARMISD::VQRSHRNu";
1313   case ARMISD::VQRSHRNsu:     return "ARMISD::VQRSHRNsu";
1314   case ARMISD::VSLI:          return "ARMISD::VSLI";
1315   case ARMISD::VSRI:          return "ARMISD::VSRI";
1316   case ARMISD::VGETLANEu:     return "ARMISD::VGETLANEu";
1317   case ARMISD::VGETLANEs:     return "ARMISD::VGETLANEs";
1318   case ARMISD::VMOVIMM:       return "ARMISD::VMOVIMM";
1319   case ARMISD::VMVNIMM:       return "ARMISD::VMVNIMM";
1320   case ARMISD::VMOVFPIMM:     return "ARMISD::VMOVFPIMM";
1321   case ARMISD::VDUP:          return "ARMISD::VDUP";
1322   case ARMISD::VDUPLANE:      return "ARMISD::VDUPLANE";
1323   case ARMISD::VEXT:          return "ARMISD::VEXT";
1324   case ARMISD::VREV64:        return "ARMISD::VREV64";
1325   case ARMISD::VREV32:        return "ARMISD::VREV32";
1326   case ARMISD::VREV16:        return "ARMISD::VREV16";
1327   case ARMISD::VZIP:          return "ARMISD::VZIP";
1328   case ARMISD::VUZP:          return "ARMISD::VUZP";
1329   case ARMISD::VTRN:          return "ARMISD::VTRN";
1330   case ARMISD::VTBL1:         return "ARMISD::VTBL1";
1331   case ARMISD::VTBL2:         return "ARMISD::VTBL2";
1332   case ARMISD::VMULLs:        return "ARMISD::VMULLs";
1333   case ARMISD::VMULLu:        return "ARMISD::VMULLu";
1334   case ARMISD::UMAAL:         return "ARMISD::UMAAL";
1335   case ARMISD::UMLAL:         return "ARMISD::UMLAL";
1336   case ARMISD::SMLAL:         return "ARMISD::SMLAL";
1337   case ARMISD::SMLALBB:       return "ARMISD::SMLALBB";
1338   case ARMISD::SMLALBT:       return "ARMISD::SMLALBT";
1339   case ARMISD::SMLALTB:       return "ARMISD::SMLALTB";
1340   case ARMISD::SMLALTT:       return "ARMISD::SMLALTT";
1341   case ARMISD::SMULWB:        return "ARMISD::SMULWB";
1342   case ARMISD::SMULWT:        return "ARMISD::SMULWT";
1343   case ARMISD::SMLALD:        return "ARMISD::SMLALD";
1344   case ARMISD::SMLALDX:       return "ARMISD::SMLALDX";
1345   case ARMISD::SMLSLD:        return "ARMISD::SMLSLD";
1346   case ARMISD::SMLSLDX:       return "ARMISD::SMLSLDX";
1347   case ARMISD::SMMLAR:        return "ARMISD::SMMLAR";
1348   case ARMISD::SMMLSR:        return "ARMISD::SMMLSR";
1349   case ARMISD::BUILD_VECTOR:  return "ARMISD::BUILD_VECTOR";
1350   case ARMISD::BFI:           return "ARMISD::BFI";
1351   case ARMISD::VORRIMM:       return "ARMISD::VORRIMM";
1352   case ARMISD::VBICIMM:       return "ARMISD::VBICIMM";
1353   case ARMISD::VBSL:          return "ARMISD::VBSL";
1354   case ARMISD::MEMCPY:        return "ARMISD::MEMCPY";
1355   case ARMISD::VLD1DUP:       return "ARMISD::VLD1DUP";
1356   case ARMISD::VLD2DUP:       return "ARMISD::VLD2DUP";
1357   case ARMISD::VLD3DUP:       return "ARMISD::VLD3DUP";
1358   case ARMISD::VLD4DUP:       return "ARMISD::VLD4DUP";
1359   case ARMISD::VLD1_UPD:      return "ARMISD::VLD1_UPD";
1360   case ARMISD::VLD2_UPD:      return "ARMISD::VLD2_UPD";
1361   case ARMISD::VLD3_UPD:      return "ARMISD::VLD3_UPD";
1362   case ARMISD::VLD4_UPD:      return "ARMISD::VLD4_UPD";
1363   case ARMISD::VLD2LN_UPD:    return "ARMISD::VLD2LN_UPD";
1364   case ARMISD::VLD3LN_UPD:    return "ARMISD::VLD3LN_UPD";
1365   case ARMISD::VLD4LN_UPD:    return "ARMISD::VLD4LN_UPD";
1366   case ARMISD::VLD1DUP_UPD:   return "ARMISD::VLD1DUP_UPD";
1367   case ARMISD::VLD2DUP_UPD:   return "ARMISD::VLD2DUP_UPD";
1368   case ARMISD::VLD3DUP_UPD:   return "ARMISD::VLD3DUP_UPD";
1369   case ARMISD::VLD4DUP_UPD:   return "ARMISD::VLD4DUP_UPD";
1370   case ARMISD::VST1_UPD:      return "ARMISD::VST1_UPD";
1371   case ARMISD::VST2_UPD:      return "ARMISD::VST2_UPD";
1372   case ARMISD::VST3_UPD:      return "ARMISD::VST3_UPD";
1373   case ARMISD::VST4_UPD:      return "ARMISD::VST4_UPD";
1374   case ARMISD::VST2LN_UPD:    return "ARMISD::VST2LN_UPD";
1375   case ARMISD::VST3LN_UPD:    return "ARMISD::VST3LN_UPD";
1376   case ARMISD::VST4LN_UPD:    return "ARMISD::VST4LN_UPD";
1377   }
1378   return nullptr;
1379 }
1380 
1381 EVT ARMTargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1382                                           EVT VT) const {
1383   if (!VT.isVector())
1384     return getPointerTy(DL);
1385   return VT.changeVectorElementTypeToInteger();
1386 }
1387 
1388 /// getRegClassFor - Return the register class that should be used for the
1389 /// specified value type.
1390 const TargetRegisterClass *ARMTargetLowering::getRegClassFor(MVT VT) const {
1391   // Map v4i64 to QQ registers but do not make the type legal. Similarly map
1392   // v8i64 to QQQQ registers. v4i64 and v8i64 are only used for REG_SEQUENCE to
1393   // load / store 4 to 8 consecutive D registers.
1394   if (Subtarget->hasNEON()) {
1395     if (VT == MVT::v4i64)
1396       return &ARM::QQPRRegClass;
1397     if (VT == MVT::v8i64)
1398       return &ARM::QQQQPRRegClass;
1399   }
1400   return TargetLowering::getRegClassFor(VT);
1401 }
1402 
1403 // memcpy, and other memory intrinsics, typically tries to use LDM/STM if the
1404 // source/dest is aligned and the copy size is large enough. We therefore want
1405 // to align such objects passed to memory intrinsics.
1406 bool ARMTargetLowering::shouldAlignPointerArgs(CallInst *CI, unsigned &MinSize,
1407                                                unsigned &PrefAlign) const {
1408   if (!isa<MemIntrinsic>(CI))
1409     return false;
1410   MinSize = 8;
1411   // On ARM11 onwards (excluding M class) 8-byte aligned LDM is typically 1
1412   // cycle faster than 4-byte aligned LDM.
1413   PrefAlign = (Subtarget->hasV6Ops() && !Subtarget->isMClass() ? 8 : 4);
1414   return true;
1415 }
1416 
1417 // Create a fast isel object.
1418 FastISel *
1419 ARMTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
1420                                   const TargetLibraryInfo *libInfo) const {
1421   return ARM::createFastISel(funcInfo, libInfo);
1422 }
1423 
1424 Sched::Preference ARMTargetLowering::getSchedulingPreference(SDNode *N) const {
1425   unsigned NumVals = N->getNumValues();
1426   if (!NumVals)
1427     return Sched::RegPressure;
1428 
1429   for (unsigned i = 0; i != NumVals; ++i) {
1430     EVT VT = N->getValueType(i);
1431     if (VT == MVT::Glue || VT == MVT::Other)
1432       continue;
1433     if (VT.isFloatingPoint() || VT.isVector())
1434       return Sched::ILP;
1435   }
1436 
1437   if (!N->isMachineOpcode())
1438     return Sched::RegPressure;
1439 
1440   // Load are scheduled for latency even if there instruction itinerary
1441   // is not available.
1442   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1443   const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
1444 
1445   if (MCID.getNumDefs() == 0)
1446     return Sched::RegPressure;
1447   if (!Itins->isEmpty() &&
1448       Itins->getOperandCycle(MCID.getSchedClass(), 0) > 2)
1449     return Sched::ILP;
1450 
1451   return Sched::RegPressure;
1452 }
1453 
1454 //===----------------------------------------------------------------------===//
1455 // Lowering Code
1456 //===----------------------------------------------------------------------===//
1457 
1458 static bool isSRL16(const SDValue &Op) {
1459   if (Op.getOpcode() != ISD::SRL)
1460     return false;
1461   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1462     return Const->getZExtValue() == 16;
1463   return false;
1464 }
1465 
1466 static bool isSRA16(const SDValue &Op) {
1467   if (Op.getOpcode() != ISD::SRA)
1468     return false;
1469   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1470     return Const->getZExtValue() == 16;
1471   return false;
1472 }
1473 
1474 static bool isSHL16(const SDValue &Op) {
1475   if (Op.getOpcode() != ISD::SHL)
1476     return false;
1477   if (auto Const = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1478     return Const->getZExtValue() == 16;
1479   return false;
1480 }
1481 
1482 // Check for a signed 16-bit value. We special case SRA because it makes it
1483 // more simple when also looking for SRAs that aren't sign extending a
1484 // smaller value. Without the check, we'd need to take extra care with
1485 // checking order for some operations.
1486 static bool isS16(const SDValue &Op, SelectionDAG &DAG) {
1487   if (isSRA16(Op))
1488     return isSHL16(Op.getOperand(0));
1489   return DAG.ComputeNumSignBits(Op) == 17;
1490 }
1491 
1492 /// IntCCToARMCC - Convert a DAG integer condition code to an ARM CC
1493 static ARMCC::CondCodes IntCCToARMCC(ISD::CondCode CC) {
1494   switch (CC) {
1495   default: llvm_unreachable("Unknown condition code!");
1496   case ISD::SETNE:  return ARMCC::NE;
1497   case ISD::SETEQ:  return ARMCC::EQ;
1498   case ISD::SETGT:  return ARMCC::GT;
1499   case ISD::SETGE:  return ARMCC::GE;
1500   case ISD::SETLT:  return ARMCC::LT;
1501   case ISD::SETLE:  return ARMCC::LE;
1502   case ISD::SETUGT: return ARMCC::HI;
1503   case ISD::SETUGE: return ARMCC::HS;
1504   case ISD::SETULT: return ARMCC::LO;
1505   case ISD::SETULE: return ARMCC::LS;
1506   }
1507 }
1508 
1509 /// FPCCToARMCC - Convert a DAG fp condition code to an ARM CC.
1510 static void FPCCToARMCC(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
1511                         ARMCC::CondCodes &CondCode2, bool &InvalidOnQNaN) {
1512   CondCode2 = ARMCC::AL;
1513   InvalidOnQNaN = true;
1514   switch (CC) {
1515   default: llvm_unreachable("Unknown FP condition!");
1516   case ISD::SETEQ:
1517   case ISD::SETOEQ:
1518     CondCode = ARMCC::EQ;
1519     InvalidOnQNaN = false;
1520     break;
1521   case ISD::SETGT:
1522   case ISD::SETOGT: CondCode = ARMCC::GT; break;
1523   case ISD::SETGE:
1524   case ISD::SETOGE: CondCode = ARMCC::GE; break;
1525   case ISD::SETOLT: CondCode = ARMCC::MI; break;
1526   case ISD::SETOLE: CondCode = ARMCC::LS; break;
1527   case ISD::SETONE:
1528     CondCode = ARMCC::MI;
1529     CondCode2 = ARMCC::GT;
1530     InvalidOnQNaN = false;
1531     break;
1532   case ISD::SETO:   CondCode = ARMCC::VC; break;
1533   case ISD::SETUO:  CondCode = ARMCC::VS; break;
1534   case ISD::SETUEQ:
1535     CondCode = ARMCC::EQ;
1536     CondCode2 = ARMCC::VS;
1537     InvalidOnQNaN = false;
1538     break;
1539   case ISD::SETUGT: CondCode = ARMCC::HI; break;
1540   case ISD::SETUGE: CondCode = ARMCC::PL; break;
1541   case ISD::SETLT:
1542   case ISD::SETULT: CondCode = ARMCC::LT; break;
1543   case ISD::SETLE:
1544   case ISD::SETULE: CondCode = ARMCC::LE; break;
1545   case ISD::SETNE:
1546   case ISD::SETUNE:
1547     CondCode = ARMCC::NE;
1548     InvalidOnQNaN = false;
1549     break;
1550   }
1551 }
1552 
1553 //===----------------------------------------------------------------------===//
1554 //                      Calling Convention Implementation
1555 //===----------------------------------------------------------------------===//
1556 
1557 #include "ARMGenCallingConv.inc"
1558 
1559 /// getEffectiveCallingConv - Get the effective calling convention, taking into
1560 /// account presence of floating point hardware and calling convention
1561 /// limitations, such as support for variadic functions.
1562 CallingConv::ID
1563 ARMTargetLowering::getEffectiveCallingConv(CallingConv::ID CC,
1564                                            bool isVarArg) const {
1565   switch (CC) {
1566   default:
1567     report_fatal_error("Unsupported calling convention");
1568   case CallingConv::ARM_AAPCS:
1569   case CallingConv::ARM_APCS:
1570   case CallingConv::GHC:
1571     return CC;
1572   case CallingConv::PreserveMost:
1573     return CallingConv::PreserveMost;
1574   case CallingConv::ARM_AAPCS_VFP:
1575   case CallingConv::Swift:
1576     return isVarArg ? CallingConv::ARM_AAPCS : CallingConv::ARM_AAPCS_VFP;
1577   case CallingConv::C:
1578     if (!Subtarget->isAAPCS_ABI())
1579       return CallingConv::ARM_APCS;
1580     else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() &&
1581              getTargetMachine().Options.FloatABIType == FloatABI::Hard &&
1582              !isVarArg)
1583       return CallingConv::ARM_AAPCS_VFP;
1584     else
1585       return CallingConv::ARM_AAPCS;
1586   case CallingConv::Fast:
1587   case CallingConv::CXX_FAST_TLS:
1588     if (!Subtarget->isAAPCS_ABI()) {
1589       if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1590         return CallingConv::Fast;
1591       return CallingConv::ARM_APCS;
1592     } else if (Subtarget->hasVFP2() && !Subtarget->isThumb1Only() && !isVarArg)
1593       return CallingConv::ARM_AAPCS_VFP;
1594     else
1595       return CallingConv::ARM_AAPCS;
1596   }
1597 }
1598 
1599 CCAssignFn *ARMTargetLowering::CCAssignFnForCall(CallingConv::ID CC,
1600                                                  bool isVarArg) const {
1601   return CCAssignFnForNode(CC, false, isVarArg);
1602 }
1603 
1604 CCAssignFn *ARMTargetLowering::CCAssignFnForReturn(CallingConv::ID CC,
1605                                                    bool isVarArg) const {
1606   return CCAssignFnForNode(CC, true, isVarArg);
1607 }
1608 
1609 /// CCAssignFnForNode - Selects the correct CCAssignFn for the given
1610 /// CallingConvention.
1611 CCAssignFn *ARMTargetLowering::CCAssignFnForNode(CallingConv::ID CC,
1612                                                  bool Return,
1613                                                  bool isVarArg) const {
1614   switch (getEffectiveCallingConv(CC, isVarArg)) {
1615   default:
1616     report_fatal_error("Unsupported calling convention");
1617   case CallingConv::ARM_APCS:
1618     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS);
1619   case CallingConv::ARM_AAPCS:
1620     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1621   case CallingConv::ARM_AAPCS_VFP:
1622     return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1623   case CallingConv::Fast:
1624     return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1625   case CallingConv::GHC:
1626     return (Return ? RetCC_ARM_APCS : CC_ARM_APCS_GHC);
1627   case CallingConv::PreserveMost:
1628     return (Return ? RetCC_ARM_AAPCS : CC_ARM_AAPCS);
1629   }
1630 }
1631 
1632 /// LowerCallResult - Lower the result values of a call into the
1633 /// appropriate copies out of appropriate physical registers.
1634 SDValue ARMTargetLowering::LowerCallResult(
1635     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
1636     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
1637     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
1638     SDValue ThisVal) const {
1639   // Assign locations to each value returned by this call.
1640   SmallVector<CCValAssign, 16> RVLocs;
1641   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1642                  *DAG.getContext());
1643   CCInfo.AnalyzeCallResult(Ins, CCAssignFnForReturn(CallConv, isVarArg));
1644 
1645   // Copy all of the result registers out of their specified physreg.
1646   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1647     CCValAssign VA = RVLocs[i];
1648 
1649     // Pass 'this' value directly from the argument to return value, to avoid
1650     // reg unit interference
1651     if (i == 0 && isThisReturn) {
1652       assert(!VA.needsCustom() && VA.getLocVT() == MVT::i32 &&
1653              "unexpected return calling convention register assignment");
1654       InVals.push_back(ThisVal);
1655       continue;
1656     }
1657 
1658     SDValue Val;
1659     if (VA.needsCustom()) {
1660       // Handle f64 or half of a v2f64.
1661       SDValue Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1662                                       InFlag);
1663       Chain = Lo.getValue(1);
1664       InFlag = Lo.getValue(2);
1665       VA = RVLocs[++i]; // skip ahead to next loc
1666       SDValue Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32,
1667                                       InFlag);
1668       Chain = Hi.getValue(1);
1669       InFlag = Hi.getValue(2);
1670       if (!Subtarget->isLittle())
1671         std::swap (Lo, Hi);
1672       Val = DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
1673 
1674       if (VA.getLocVT() == MVT::v2f64) {
1675         SDValue Vec = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
1676         Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1677                           DAG.getConstant(0, dl, MVT::i32));
1678 
1679         VA = RVLocs[++i]; // skip ahead to next loc
1680         Lo = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, InFlag);
1681         Chain = Lo.getValue(1);
1682         InFlag = Lo.getValue(2);
1683         VA = RVLocs[++i]; // skip ahead to next loc
1684         Hi = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), MVT::i32, 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         Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Vec, Val,
1691                           DAG.getConstant(1, dl, MVT::i32));
1692       }
1693     } else {
1694       Val = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(), VA.getLocVT(),
1695                                InFlag);
1696       Chain = Val.getValue(1);
1697       InFlag = Val.getValue(2);
1698     }
1699 
1700     switch (VA.getLocInfo()) {
1701     default: llvm_unreachable("Unknown loc info!");
1702     case CCValAssign::Full: break;
1703     case CCValAssign::BCvt:
1704       Val = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), Val);
1705       break;
1706     }
1707 
1708     InVals.push_back(Val);
1709   }
1710 
1711   return Chain;
1712 }
1713 
1714 /// LowerMemOpCallTo - Store the argument to the stack.
1715 SDValue ARMTargetLowering::LowerMemOpCallTo(SDValue Chain, SDValue StackPtr,
1716                                             SDValue Arg, const SDLoc &dl,
1717                                             SelectionDAG &DAG,
1718                                             const CCValAssign &VA,
1719                                             ISD::ArgFlagsTy Flags) const {
1720   unsigned LocMemOffset = VA.getLocMemOffset();
1721   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1722   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
1723                        StackPtr, PtrOff);
1724   return DAG.getStore(
1725       Chain, dl, Arg, PtrOff,
1726       MachinePointerInfo::getStack(DAG.getMachineFunction(), LocMemOffset));
1727 }
1728 
1729 void ARMTargetLowering::PassF64ArgInRegs(const SDLoc &dl, SelectionDAG &DAG,
1730                                          SDValue Chain, SDValue &Arg,
1731                                          RegsToPassVector &RegsToPass,
1732                                          CCValAssign &VA, CCValAssign &NextVA,
1733                                          SDValue &StackPtr,
1734                                          SmallVectorImpl<SDValue> &MemOpChains,
1735                                          ISD::ArgFlagsTy Flags) const {
1736   SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
1737                               DAG.getVTList(MVT::i32, MVT::i32), Arg);
1738   unsigned id = Subtarget->isLittle() ? 0 : 1;
1739   RegsToPass.push_back(std::make_pair(VA.getLocReg(), fmrrd.getValue(id)));
1740 
1741   if (NextVA.isRegLoc())
1742     RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), fmrrd.getValue(1-id)));
1743   else {
1744     assert(NextVA.isMemLoc());
1745     if (!StackPtr.getNode())
1746       StackPtr = DAG.getCopyFromReg(Chain, dl, ARM::SP,
1747                                     getPointerTy(DAG.getDataLayout()));
1748 
1749     MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, fmrrd.getValue(1-id),
1750                                            dl, DAG, NextVA,
1751                                            Flags));
1752   }
1753 }
1754 
1755 /// LowerCall - Lowering a call into a callseq_start <-
1756 /// ARMISD:CALL <- callseq_end chain. Also add input and output parameter
1757 /// nodes.
1758 SDValue
1759 ARMTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
1760                              SmallVectorImpl<SDValue> &InVals) const {
1761   SelectionDAG &DAG                     = CLI.DAG;
1762   SDLoc &dl                             = CLI.DL;
1763   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
1764   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
1765   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
1766   SDValue Chain                         = CLI.Chain;
1767   SDValue Callee                        = CLI.Callee;
1768   bool &isTailCall                      = CLI.IsTailCall;
1769   CallingConv::ID CallConv              = CLI.CallConv;
1770   bool doesNotRet                       = CLI.DoesNotReturn;
1771   bool isVarArg                         = CLI.IsVarArg;
1772 
1773   MachineFunction &MF = DAG.getMachineFunction();
1774   bool isStructRet    = (Outs.empty()) ? false : Outs[0].Flags.isSRet();
1775   bool isThisReturn   = false;
1776   bool isSibCall      = false;
1777   auto Attr = MF.getFunction().getFnAttribute("disable-tail-calls");
1778 
1779   // Disable tail calls if they're not supported.
1780   if (!Subtarget->supportsTailCall() || Attr.getValueAsString() == "true")
1781     isTailCall = false;
1782 
1783   if (isTailCall) {
1784     // Check if it's really possible to do a tail call.
1785     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
1786                     isVarArg, isStructRet, MF.getFunction().hasStructRetAttr(),
1787                                                    Outs, OutVals, Ins, DAG);
1788     if (!isTailCall && CLI.CS && CLI.CS.isMustTailCall())
1789       report_fatal_error("failed to perform tail call elimination on a call "
1790                          "site marked musttail");
1791     // We don't support GuaranteedTailCallOpt for ARM, only automatically
1792     // detected sibcalls.
1793     if (isTailCall) {
1794       ++NumTailCalls;
1795       isSibCall = true;
1796     }
1797   }
1798 
1799   // Analyze operands of the call, assigning locations to each operand.
1800   SmallVector<CCValAssign, 16> ArgLocs;
1801   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1802                  *DAG.getContext());
1803   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CallConv, isVarArg));
1804 
1805   // Get a count of how many bytes are to be pushed on the stack.
1806   unsigned NumBytes = CCInfo.getNextStackOffset();
1807 
1808   // For tail calls, memory operands are available in our caller's stack.
1809   if (isSibCall)
1810     NumBytes = 0;
1811 
1812   // Adjust the stack pointer for the new arguments...
1813   // These operations are automatically eliminated by the prolog/epilog pass
1814   if (!isSibCall)
1815     Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, dl);
1816 
1817   SDValue StackPtr =
1818       DAG.getCopyFromReg(Chain, dl, ARM::SP, getPointerTy(DAG.getDataLayout()));
1819 
1820   RegsToPassVector RegsToPass;
1821   SmallVector<SDValue, 8> MemOpChains;
1822 
1823   // Walk the register/memloc assignments, inserting copies/loads.  In the case
1824   // of tail call optimization, arguments are handled later.
1825   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
1826        i != e;
1827        ++i, ++realArgIdx) {
1828     CCValAssign &VA = ArgLocs[i];
1829     SDValue Arg = OutVals[realArgIdx];
1830     ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
1831     bool isByVal = Flags.isByVal();
1832 
1833     // Promote the value if needed.
1834     switch (VA.getLocInfo()) {
1835     default: llvm_unreachable("Unknown loc info!");
1836     case CCValAssign::Full: break;
1837     case CCValAssign::SExt:
1838       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
1839       break;
1840     case CCValAssign::ZExt:
1841       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
1842       break;
1843     case CCValAssign::AExt:
1844       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
1845       break;
1846     case CCValAssign::BCvt:
1847       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
1848       break;
1849     }
1850 
1851     // f64 and v2f64 might be passed in i32 pairs and must be split into pieces
1852     if (VA.needsCustom()) {
1853       if (VA.getLocVT() == MVT::v2f64) {
1854         SDValue Op0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1855                                   DAG.getConstant(0, dl, MVT::i32));
1856         SDValue Op1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
1857                                   DAG.getConstant(1, dl, MVT::i32));
1858 
1859         PassF64ArgInRegs(dl, DAG, Chain, Op0, RegsToPass,
1860                          VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1861 
1862         VA = ArgLocs[++i]; // skip ahead to next loc
1863         if (VA.isRegLoc()) {
1864           PassF64ArgInRegs(dl, DAG, Chain, Op1, RegsToPass,
1865                            VA, ArgLocs[++i], StackPtr, MemOpChains, Flags);
1866         } else {
1867           assert(VA.isMemLoc());
1868 
1869           MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Op1,
1870                                                  dl, DAG, VA, Flags));
1871         }
1872       } else {
1873         PassF64ArgInRegs(dl, DAG, Chain, Arg, RegsToPass, VA, ArgLocs[++i],
1874                          StackPtr, MemOpChains, Flags);
1875       }
1876     } else if (VA.isRegLoc()) {
1877       if (realArgIdx == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
1878           Outs[0].VT == MVT::i32) {
1879         assert(VA.getLocVT() == MVT::i32 &&
1880                "unexpected calling convention register assignment");
1881         assert(!Ins.empty() && Ins[0].VT == MVT::i32 &&
1882                "unexpected use of 'returned'");
1883         isThisReturn = true;
1884       }
1885       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
1886     } else if (isByVal) {
1887       assert(VA.isMemLoc());
1888       unsigned offset = 0;
1889 
1890       // True if this byval aggregate will be split between registers
1891       // and memory.
1892       unsigned ByValArgsCount = CCInfo.getInRegsParamsCount();
1893       unsigned CurByValIdx = CCInfo.getInRegsParamsProcessed();
1894 
1895       if (CurByValIdx < ByValArgsCount) {
1896 
1897         unsigned RegBegin, RegEnd;
1898         CCInfo.getInRegsParamInfo(CurByValIdx, RegBegin, RegEnd);
1899 
1900         EVT PtrVT =
1901             DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
1902         unsigned int i, j;
1903         for (i = 0, j = RegBegin; j < RegEnd; i++, j++) {
1904           SDValue Const = DAG.getConstant(4*i, dl, MVT::i32);
1905           SDValue AddArg = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, Const);
1906           SDValue Load = DAG.getLoad(PtrVT, dl, Chain, AddArg,
1907                                      MachinePointerInfo(),
1908                                      DAG.InferPtrAlignment(AddArg));
1909           MemOpChains.push_back(Load.getValue(1));
1910           RegsToPass.push_back(std::make_pair(j, Load));
1911         }
1912 
1913         // If parameter size outsides register area, "offset" value
1914         // helps us to calculate stack slot for remained part properly.
1915         offset = RegEnd - RegBegin;
1916 
1917         CCInfo.nextInRegsParam();
1918       }
1919 
1920       if (Flags.getByValSize() > 4*offset) {
1921         auto PtrVT = getPointerTy(DAG.getDataLayout());
1922         unsigned LocMemOffset = VA.getLocMemOffset();
1923         SDValue StkPtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
1924         SDValue Dst = DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, StkPtrOff);
1925         SDValue SrcOffset = DAG.getIntPtrConstant(4*offset, dl);
1926         SDValue Src = DAG.getNode(ISD::ADD, dl, PtrVT, Arg, SrcOffset);
1927         SDValue SizeNode = DAG.getConstant(Flags.getByValSize() - 4*offset, dl,
1928                                            MVT::i32);
1929         SDValue AlignNode = DAG.getConstant(Flags.getByValAlign(), dl,
1930                                             MVT::i32);
1931 
1932         SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
1933         SDValue Ops[] = { Chain, Dst, Src, SizeNode, AlignNode};
1934         MemOpChains.push_back(DAG.getNode(ARMISD::COPY_STRUCT_BYVAL, dl, VTs,
1935                                           Ops));
1936       }
1937     } else if (!isSibCall) {
1938       assert(VA.isMemLoc());
1939 
1940       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
1941                                              dl, DAG, VA, Flags));
1942     }
1943   }
1944 
1945   if (!MemOpChains.empty())
1946     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
1947 
1948   // Build a sequence of copy-to-reg nodes chained together with token chain
1949   // and flag operands which copy the outgoing args into the appropriate regs.
1950   SDValue InFlag;
1951   // Tail call byval lowering might overwrite argument registers so in case of
1952   // tail call optimization the copies to registers are lowered later.
1953   if (!isTailCall)
1954     for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1955       Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
1956                                RegsToPass[i].second, InFlag);
1957       InFlag = Chain.getValue(1);
1958     }
1959 
1960   // For tail calls lower the arguments to the 'real' stack slot.
1961   if (isTailCall) {
1962     // Force all the incoming stack arguments to be loaded from the stack
1963     // before any new outgoing arguments are stored to the stack, because the
1964     // outgoing stack slots may alias the incoming argument stack slots, and
1965     // the alias isn't otherwise explicit. This is slightly more conservative
1966     // than necessary, because it means that each store effectively depends
1967     // on every argument instead of just those arguments it would clobber.
1968 
1969     // Do not flag preceding copytoreg stuff together with the following stuff.
1970     InFlag = SDValue();
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     InFlag = SDValue();
1977   }
1978 
1979   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
1980   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
1981   // node so that legalize doesn't hack it.
1982   bool isDirect = false;
1983 
1984   const TargetMachine &TM = getTargetMachine();
1985   const Module *Mod = MF.getFunction().getParent();
1986   const GlobalValue *GV = nullptr;
1987   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1988     GV = G->getGlobal();
1989   bool isStub =
1990       !TM.shouldAssumeDSOLocal(*Mod, GV) && Subtarget->isTargetMachO();
1991 
1992   bool isARMFunc = !Subtarget->isThumb() || (isStub && !Subtarget->isMClass());
1993   bool isLocalARMFunc = false;
1994   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
1995   auto PtrVt = getPointerTy(DAG.getDataLayout());
1996 
1997   if (Subtarget->genLongCalls()) {
1998     assert((!isPositionIndependent() || Subtarget->isTargetWindows()) &&
1999            "long-calls codegen is not position independent!");
2000     // Handle a global address or an external symbol. If it's not one of
2001     // those, the target's already in a register, so we don't need to do
2002     // anything extra.
2003     if (isa<GlobalAddressSDNode>(Callee)) {
2004       // Create a constant pool entry for the callee address
2005       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2006       ARMConstantPoolValue *CPV =
2007         ARMConstantPoolConstant::Create(GV, ARMPCLabelIndex, ARMCP::CPValue, 0);
2008 
2009       // Get the address of the callee into a register
2010       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2011       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2012       Callee = DAG.getLoad(
2013           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2014           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2015     } else if (ExternalSymbolSDNode *S=dyn_cast<ExternalSymbolSDNode>(Callee)) {
2016       const char *Sym = S->getSymbol();
2017 
2018       // Create a constant pool entry for the callee address
2019       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2020       ARMConstantPoolValue *CPV =
2021         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2022                                       ARMPCLabelIndex, 0);
2023       // Get the address of the callee into a register
2024       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2025       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2026       Callee = DAG.getLoad(
2027           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2028           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2029     }
2030   } else if (isa<GlobalAddressSDNode>(Callee)) {
2031     // If we're optimizing for minimum size and the function is called three or
2032     // more times in this block, we can improve codesize by calling indirectly
2033     // as BLXr has a 16-bit encoding.
2034     auto *GV = cast<GlobalAddressSDNode>(Callee)->getGlobal();
2035     auto *BB = CLI.CS.getParent();
2036     bool PreferIndirect =
2037         Subtarget->isThumb() && MF.getFunction().optForMinSize() &&
2038         count_if(GV->users(), [&BB](const User *U) {
2039           return isa<Instruction>(U) && cast<Instruction>(U)->getParent() == BB;
2040         }) > 2;
2041 
2042     if (!PreferIndirect) {
2043       isDirect = true;
2044       bool isDef = GV->isStrongDefinitionForLinker();
2045 
2046       // ARM call to a local ARM function is predicable.
2047       isLocalARMFunc = !Subtarget->isThumb() && (isDef || !ARMInterworking);
2048       // tBX takes a register source operand.
2049       if (isStub && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2050         assert(Subtarget->isTargetMachO() && "WrapperPIC use on non-MachO?");
2051         Callee = DAG.getNode(
2052             ARMISD::WrapperPIC, dl, PtrVt,
2053             DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, ARMII::MO_NONLAZY));
2054         Callee = DAG.getLoad(
2055             PtrVt, dl, DAG.getEntryNode(), Callee,
2056             MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2057             /* Alignment = */ 0, MachineMemOperand::MODereferenceable |
2058                                      MachineMemOperand::MOInvariant);
2059       } else if (Subtarget->isTargetCOFF()) {
2060         assert(Subtarget->isTargetWindows() &&
2061                "Windows is the only supported COFF target");
2062         unsigned TargetFlags = GV->hasDLLImportStorageClass()
2063                                    ? ARMII::MO_DLLIMPORT
2064                                    : ARMII::MO_NO_FLAG;
2065         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, /*Offset=*/0,
2066                                             TargetFlags);
2067         if (GV->hasDLLImportStorageClass())
2068           Callee =
2069               DAG.getLoad(PtrVt, dl, DAG.getEntryNode(),
2070                           DAG.getNode(ARMISD::Wrapper, dl, PtrVt, Callee),
2071                           MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2072       } else {
2073         Callee = DAG.getTargetGlobalAddress(GV, dl, PtrVt, 0, 0);
2074       }
2075     }
2076   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2077     isDirect = true;
2078     // tBX takes a register source operand.
2079     const char *Sym = S->getSymbol();
2080     if (isARMFunc && Subtarget->isThumb1Only() && !Subtarget->hasV5TOps()) {
2081       unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2082       ARMConstantPoolValue *CPV =
2083         ARMConstantPoolSymbol::Create(*DAG.getContext(), Sym,
2084                                       ARMPCLabelIndex, 4);
2085       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVt, 4);
2086       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
2087       Callee = DAG.getLoad(
2088           PtrVt, dl, DAG.getEntryNode(), CPAddr,
2089           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2090       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2091       Callee = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVt, Callee, PICLabel);
2092     } else {
2093       Callee = DAG.getTargetExternalSymbol(Sym, PtrVt, 0);
2094     }
2095   }
2096 
2097   // FIXME: handle tail calls differently.
2098   unsigned CallOpc;
2099   if (Subtarget->isThumb()) {
2100     if ((!isDirect || isARMFunc) && !Subtarget->hasV5TOps())
2101       CallOpc = ARMISD::CALL_NOLINK;
2102     else
2103       CallOpc = ARMISD::CALL;
2104   } else {
2105     if (!isDirect && !Subtarget->hasV5TOps())
2106       CallOpc = ARMISD::CALL_NOLINK;
2107     else if (doesNotRet && isDirect && Subtarget->hasRetAddrStack() &&
2108              // Emit regular call when code size is the priority
2109              !MF.getFunction().optForMinSize())
2110       // "mov lr, pc; b _foo" to avoid confusing the RSP
2111       CallOpc = ARMISD::CALL_NOLINK;
2112     else
2113       CallOpc = isLocalARMFunc ? ARMISD::CALL_PRED : ARMISD::CALL;
2114   }
2115 
2116   std::vector<SDValue> Ops;
2117   Ops.push_back(Chain);
2118   Ops.push_back(Callee);
2119 
2120   // Add argument registers to the end of the list so that they are known live
2121   // into the call.
2122   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2123     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2124                                   RegsToPass[i].second.getValueType()));
2125 
2126   // Add a register mask operand representing the call-preserved registers.
2127   if (!isTailCall) {
2128     const uint32_t *Mask;
2129     const ARMBaseRegisterInfo *ARI = Subtarget->getRegisterInfo();
2130     if (isThisReturn) {
2131       // For 'this' returns, use the R0-preserving mask if applicable
2132       Mask = ARI->getThisReturnPreservedMask(MF, CallConv);
2133       if (!Mask) {
2134         // Set isThisReturn to false if the calling convention is not one that
2135         // allows 'returned' to be modeled in this way, so LowerCallResult does
2136         // not try to pass 'this' straight through
2137         isThisReturn = false;
2138         Mask = ARI->getCallPreservedMask(MF, CallConv);
2139       }
2140     } else
2141       Mask = ARI->getCallPreservedMask(MF, CallConv);
2142 
2143     assert(Mask && "Missing call preserved mask for calling convention");
2144     Ops.push_back(DAG.getRegisterMask(Mask));
2145   }
2146 
2147   if (InFlag.getNode())
2148     Ops.push_back(InFlag);
2149 
2150   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2151   if (isTailCall) {
2152     MF.getFrameInfo().setHasTailCall();
2153     return DAG.getNode(ARMISD::TC_RETURN, dl, NodeTys, Ops);
2154   }
2155 
2156   // Returns a chain and a flag for retval copy to use.
2157   Chain = DAG.getNode(CallOpc, dl, NodeTys, Ops);
2158   InFlag = Chain.getValue(1);
2159 
2160   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, dl, true),
2161                              DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
2162   if (!Ins.empty())
2163     InFlag = Chain.getValue(1);
2164 
2165   // Handle result values, copying them out of physregs into vregs that we
2166   // return.
2167   return LowerCallResult(Chain, InFlag, CallConv, isVarArg, Ins, dl, DAG,
2168                          InVals, isThisReturn,
2169                          isThisReturn ? OutVals[0] : SDValue());
2170 }
2171 
2172 /// HandleByVal - Every parameter *after* a byval parameter is passed
2173 /// on the stack.  Remember the next parameter register to allocate,
2174 /// and then confiscate the rest of the parameter registers to insure
2175 /// this.
2176 void ARMTargetLowering::HandleByVal(CCState *State, unsigned &Size,
2177                                     unsigned Align) const {
2178   // Byval (as with any stack) slots are always at least 4 byte aligned.
2179   Align = std::max(Align, 4U);
2180 
2181   unsigned Reg = State->AllocateReg(GPRArgRegs);
2182   if (!Reg)
2183     return;
2184 
2185   unsigned AlignInRegs = Align / 4;
2186   unsigned Waste = (ARM::R4 - Reg) % AlignInRegs;
2187   for (unsigned i = 0; i < Waste; ++i)
2188     Reg = State->AllocateReg(GPRArgRegs);
2189 
2190   if (!Reg)
2191     return;
2192 
2193   unsigned Excess = 4 * (ARM::R4 - Reg);
2194 
2195   // Special case when NSAA != SP and parameter size greater than size of
2196   // all remained GPR regs. In that case we can't split parameter, we must
2197   // send it to stack. We also must set NCRN to R4, so waste all
2198   // remained registers.
2199   const unsigned NSAAOffset = State->getNextStackOffset();
2200   if (NSAAOffset != 0 && Size > Excess) {
2201     while (State->AllocateReg(GPRArgRegs))
2202       ;
2203     return;
2204   }
2205 
2206   // First register for byval parameter is the first register that wasn't
2207   // allocated before this method call, so it would be "reg".
2208   // If parameter is small enough to be saved in range [reg, r4), then
2209   // the end (first after last) register would be reg + param-size-in-regs,
2210   // else parameter would be splitted between registers and stack,
2211   // end register would be r4 in this case.
2212   unsigned ByValRegBegin = Reg;
2213   unsigned ByValRegEnd = std::min<unsigned>(Reg + Size / 4, ARM::R4);
2214   State->addInRegsParamInfo(ByValRegBegin, ByValRegEnd);
2215   // Note, first register is allocated in the beginning of function already,
2216   // allocate remained amount of registers we need.
2217   for (unsigned i = Reg + 1; i != ByValRegEnd; ++i)
2218     State->AllocateReg(GPRArgRegs);
2219   // A byval parameter that is split between registers and memory needs its
2220   // size truncated here.
2221   // In the case where the entire structure fits in registers, we set the
2222   // size in memory to zero.
2223   Size = std::max<int>(Size - Excess, 0);
2224 }
2225 
2226 /// MatchingStackOffset - Return true if the given stack call argument is
2227 /// already available in the same position (relatively) of the caller's
2228 /// incoming argument stack.
2229 static
2230 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
2231                          MachineFrameInfo &MFI, const MachineRegisterInfo *MRI,
2232                          const TargetInstrInfo *TII) {
2233   unsigned Bytes = Arg.getValueSizeInBits() / 8;
2234   int FI = std::numeric_limits<int>::max();
2235   if (Arg.getOpcode() == ISD::CopyFromReg) {
2236     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
2237     if (!TargetRegisterInfo::isVirtualRegister(VR))
2238       return false;
2239     MachineInstr *Def = MRI->getVRegDef(VR);
2240     if (!Def)
2241       return false;
2242     if (!Flags.isByVal()) {
2243       if (!TII->isLoadFromStackSlot(*Def, FI))
2244         return false;
2245     } else {
2246       return false;
2247     }
2248   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
2249     if (Flags.isByVal())
2250       // ByVal argument is passed in as a pointer but it's now being
2251       // dereferenced. e.g.
2252       // define @foo(%struct.X* %A) {
2253       //   tail call @bar(%struct.X* byval %A)
2254       // }
2255       return false;
2256     SDValue Ptr = Ld->getBasePtr();
2257     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
2258     if (!FINode)
2259       return false;
2260     FI = FINode->getIndex();
2261   } else
2262     return false;
2263 
2264   assert(FI != std::numeric_limits<int>::max());
2265   if (!MFI.isFixedObjectIndex(FI))
2266     return false;
2267   return Offset == MFI.getObjectOffset(FI) && Bytes == MFI.getObjectSize(FI);
2268 }
2269 
2270 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2271 /// for tail call optimization. Targets which want to do tail call
2272 /// optimization should implement this function.
2273 bool
2274 ARMTargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
2275                                                      CallingConv::ID CalleeCC,
2276                                                      bool isVarArg,
2277                                                      bool isCalleeStructRet,
2278                                                      bool isCallerStructRet,
2279                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
2280                                     const SmallVectorImpl<SDValue> &OutVals,
2281                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2282                                                      SelectionDAG& DAG) const {
2283   MachineFunction &MF = DAG.getMachineFunction();
2284   const Function &CallerF = MF.getFunction();
2285   CallingConv::ID CallerCC = CallerF.getCallingConv();
2286 
2287   assert(Subtarget->supportsTailCall());
2288 
2289   // Tail calls to function pointers cannot be optimized for Thumb1 if the args
2290   // to the call take up r0-r3. The reason is that there are no legal registers
2291   // left to hold the pointer to the function to be called.
2292   if (Subtarget->isThumb1Only() && Outs.size() >= 4 &&
2293       !isa<GlobalAddressSDNode>(Callee.getNode()))
2294       return false;
2295 
2296   // Look for obvious safe cases to perform tail call optimization that do not
2297   // require ABI changes. This is what gcc calls sibcall.
2298 
2299   // Exception-handling functions need a special set of instructions to indicate
2300   // a return to the hardware. Tail-calling another function would probably
2301   // break this.
2302   if (CallerF.hasFnAttribute("interrupt"))
2303     return false;
2304 
2305   // Also avoid sibcall optimization if either caller or callee uses struct
2306   // return semantics.
2307   if (isCalleeStructRet || isCallerStructRet)
2308     return false;
2309 
2310   // Externally-defined functions with weak linkage should not be
2311   // tail-called on ARM when the OS does not support dynamic
2312   // pre-emption of symbols, as the AAELF spec requires normal calls
2313   // to undefined weak functions to be replaced with a NOP or jump to the
2314   // next instruction. The behaviour of branch instructions in this
2315   // situation (as used for tail calls) is implementation-defined, so we
2316   // cannot rely on the linker replacing the tail call with a return.
2317   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2318     const GlobalValue *GV = G->getGlobal();
2319     const Triple &TT = getTargetMachine().getTargetTriple();
2320     if (GV->hasExternalWeakLinkage() &&
2321         (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
2322       return false;
2323   }
2324 
2325   // Check that the call results are passed in the same way.
2326   LLVMContext &C = *DAG.getContext();
2327   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
2328                                   CCAssignFnForReturn(CalleeCC, isVarArg),
2329                                   CCAssignFnForReturn(CallerCC, isVarArg)))
2330     return false;
2331   // The callee has to preserve all registers the caller needs to preserve.
2332   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2333   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2334   if (CalleeCC != CallerCC) {
2335     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2336     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2337       return false;
2338   }
2339 
2340   // If Caller's vararg or byval argument has been split between registers and
2341   // stack, do not perform tail call, since part of the argument is in caller's
2342   // local frame.
2343   const ARMFunctionInfo *AFI_Caller = MF.getInfo<ARMFunctionInfo>();
2344   if (AFI_Caller->getArgRegsSaveSize())
2345     return false;
2346 
2347   // If the callee takes no arguments then go on to check the results of the
2348   // call.
2349   if (!Outs.empty()) {
2350     // Check if stack adjustment is needed. For now, do not do this if any
2351     // argument is passed on the stack.
2352     SmallVector<CCValAssign, 16> ArgLocs;
2353     CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
2354     CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
2355     if (CCInfo.getNextStackOffset()) {
2356       // Check if the arguments are already laid out in the right way as
2357       // the caller's fixed stack objects.
2358       MachineFrameInfo &MFI = MF.getFrameInfo();
2359       const MachineRegisterInfo *MRI = &MF.getRegInfo();
2360       const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2361       for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size();
2362            i != e;
2363            ++i, ++realArgIdx) {
2364         CCValAssign &VA = ArgLocs[i];
2365         EVT RegVT = VA.getLocVT();
2366         SDValue Arg = OutVals[realArgIdx];
2367         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2368         if (VA.getLocInfo() == CCValAssign::Indirect)
2369           return false;
2370         if (VA.needsCustom()) {
2371           // f64 and vector types are split into multiple registers or
2372           // register/stack-slot combinations.  The types will not match
2373           // the registers; give up on memory f64 refs until we figure
2374           // out what to do about this.
2375           if (!VA.isRegLoc())
2376             return false;
2377           if (!ArgLocs[++i].isRegLoc())
2378             return false;
2379           if (RegVT == MVT::v2f64) {
2380             if (!ArgLocs[++i].isRegLoc())
2381               return false;
2382             if (!ArgLocs[++i].isRegLoc())
2383               return false;
2384           }
2385         } else if (!VA.isRegLoc()) {
2386           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
2387                                    MFI, MRI, TII))
2388             return false;
2389         }
2390       }
2391     }
2392 
2393     const MachineRegisterInfo &MRI = MF.getRegInfo();
2394     if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
2395       return false;
2396   }
2397 
2398   return true;
2399 }
2400 
2401 bool
2402 ARMTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2403                                   MachineFunction &MF, bool isVarArg,
2404                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
2405                                   LLVMContext &Context) const {
2406   SmallVector<CCValAssign, 16> RVLocs;
2407   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2408   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2409 }
2410 
2411 static SDValue LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
2412                                     const SDLoc &DL, SelectionDAG &DAG) {
2413   const MachineFunction &MF = DAG.getMachineFunction();
2414   const Function &F = MF.getFunction();
2415 
2416   StringRef IntKind = F.getFnAttribute("interrupt").getValueAsString();
2417 
2418   // See ARM ARM v7 B1.8.3. On exception entry LR is set to a possibly offset
2419   // version of the "preferred return address". These offsets affect the return
2420   // instruction if this is a return from PL1 without hypervisor extensions.
2421   //    IRQ/FIQ: +4     "subs pc, lr, #4"
2422   //    SWI:     0      "subs pc, lr, #0"
2423   //    ABORT:   +4     "subs pc, lr, #4"
2424   //    UNDEF:   +4/+2  "subs pc, lr, #0"
2425   // UNDEF varies depending on where the exception came from ARM or Thumb
2426   // mode. Alongside GCC, we throw our hands up in disgust and pretend it's 0.
2427 
2428   int64_t LROffset;
2429   if (IntKind == "" || IntKind == "IRQ" || IntKind == "FIQ" ||
2430       IntKind == "ABORT")
2431     LROffset = 4;
2432   else if (IntKind == "SWI" || IntKind == "UNDEF")
2433     LROffset = 0;
2434   else
2435     report_fatal_error("Unsupported interrupt attribute. If present, value "
2436                        "must be one of: IRQ, FIQ, SWI, ABORT or UNDEF");
2437 
2438   RetOps.insert(RetOps.begin() + 1,
2439                 DAG.getConstant(LROffset, DL, MVT::i32, false));
2440 
2441   return DAG.getNode(ARMISD::INTRET_FLAG, DL, MVT::Other, RetOps);
2442 }
2443 
2444 SDValue
2445 ARMTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2446                                bool isVarArg,
2447                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2448                                const SmallVectorImpl<SDValue> &OutVals,
2449                                const SDLoc &dl, SelectionDAG &DAG) const {
2450   // CCValAssign - represent the assignment of the return value to a location.
2451   SmallVector<CCValAssign, 16> RVLocs;
2452 
2453   // CCState - Info about the registers and stack slots.
2454   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2455                  *DAG.getContext());
2456 
2457   // Analyze outgoing return values.
2458   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2459 
2460   SDValue Flag;
2461   SmallVector<SDValue, 4> RetOps;
2462   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2463   bool isLittleEndian = Subtarget->isLittle();
2464 
2465   MachineFunction &MF = DAG.getMachineFunction();
2466   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2467   AFI->setReturnRegsCount(RVLocs.size());
2468 
2469   // Copy the result values into the output registers.
2470   for (unsigned i = 0, realRVLocIdx = 0;
2471        i != RVLocs.size();
2472        ++i, ++realRVLocIdx) {
2473     CCValAssign &VA = RVLocs[i];
2474     assert(VA.isRegLoc() && "Can only return in registers!");
2475 
2476     SDValue Arg = OutVals[realRVLocIdx];
2477 
2478     switch (VA.getLocInfo()) {
2479     default: llvm_unreachable("Unknown loc info!");
2480     case CCValAssign::Full: break;
2481     case CCValAssign::BCvt:
2482       Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
2483       break;
2484     }
2485 
2486     if (VA.needsCustom()) {
2487       if (VA.getLocVT() == MVT::v2f64) {
2488         // Extract the first half and return it in two registers.
2489         SDValue Half = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2490                                    DAG.getConstant(0, dl, MVT::i32));
2491         SDValue HalfGPRs = DAG.getNode(ARMISD::VMOVRRD, dl,
2492                                        DAG.getVTList(MVT::i32, MVT::i32), Half);
2493 
2494         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2495                                  HalfGPRs.getValue(isLittleEndian ? 0 : 1),
2496                                  Flag);
2497         Flag = Chain.getValue(1);
2498         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2499         VA = RVLocs[++i]; // skip ahead to next loc
2500         Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2501                                  HalfGPRs.getValue(isLittleEndian ? 1 : 0),
2502                                  Flag);
2503         Flag = Chain.getValue(1);
2504         RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2505         VA = RVLocs[++i]; // skip ahead to next loc
2506 
2507         // Extract the 2nd half and fall through to handle it as an f64 value.
2508         Arg = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Arg,
2509                           DAG.getConstant(1, dl, MVT::i32));
2510       }
2511       // Legalize ret f64 -> ret 2 x i32.  We always have fmrrd if f64 is
2512       // available.
2513       SDValue fmrrd = DAG.getNode(ARMISD::VMOVRRD, dl,
2514                                   DAG.getVTList(MVT::i32, MVT::i32), Arg);
2515       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2516                                fmrrd.getValue(isLittleEndian ? 0 : 1),
2517                                Flag);
2518       Flag = Chain.getValue(1);
2519       RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2520       VA = RVLocs[++i]; // skip ahead to next loc
2521       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2522                                fmrrd.getValue(isLittleEndian ? 1 : 0),
2523                                Flag);
2524     } else
2525       Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), Arg, Flag);
2526 
2527     // Guarantee that all emitted copies are
2528     // stuck together, avoiding something bad.
2529     Flag = Chain.getValue(1);
2530     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2531   }
2532   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
2533   const MCPhysReg *I =
2534       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2535   if (I) {
2536     for (; *I; ++I) {
2537       if (ARM::GPRRegClass.contains(*I))
2538         RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2539       else if (ARM::DPRRegClass.contains(*I))
2540         RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
2541       else
2542         llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2543     }
2544   }
2545 
2546   // Update chain and glue.
2547   RetOps[0] = Chain;
2548   if (Flag.getNode())
2549     RetOps.push_back(Flag);
2550 
2551   // CPUs which aren't M-class use a special sequence to return from
2552   // exceptions (roughly, any instruction setting pc and cpsr simultaneously,
2553   // though we use "subs pc, lr, #N").
2554   //
2555   // M-class CPUs actually use a normal return sequence with a special
2556   // (hardware-provided) value in LR, so the normal code path works.
2557   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt") &&
2558       !Subtarget->isMClass()) {
2559     if (Subtarget->isThumb1Only())
2560       report_fatal_error("interrupt attribute is not supported in Thumb1");
2561     return LowerInterruptReturn(RetOps, dl, DAG);
2562   }
2563 
2564   return DAG.getNode(ARMISD::RET_FLAG, dl, MVT::Other, RetOps);
2565 }
2566 
2567 bool ARMTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2568   if (N->getNumValues() != 1)
2569     return false;
2570   if (!N->hasNUsesOfValue(1, 0))
2571     return false;
2572 
2573   SDValue TCChain = Chain;
2574   SDNode *Copy = *N->use_begin();
2575   if (Copy->getOpcode() == ISD::CopyToReg) {
2576     // If the copy has a glue operand, we conservatively assume it isn't safe to
2577     // perform a tail call.
2578     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2579       return false;
2580     TCChain = Copy->getOperand(0);
2581   } else if (Copy->getOpcode() == ARMISD::VMOVRRD) {
2582     SDNode *VMov = Copy;
2583     // f64 returned in a pair of GPRs.
2584     SmallPtrSet<SDNode*, 2> Copies;
2585     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2586          UI != UE; ++UI) {
2587       if (UI->getOpcode() != ISD::CopyToReg)
2588         return false;
2589       Copies.insert(*UI);
2590     }
2591     if (Copies.size() > 2)
2592       return false;
2593 
2594     for (SDNode::use_iterator UI = VMov->use_begin(), UE = VMov->use_end();
2595          UI != UE; ++UI) {
2596       SDValue UseChain = UI->getOperand(0);
2597       if (Copies.count(UseChain.getNode()))
2598         // Second CopyToReg
2599         Copy = *UI;
2600       else {
2601         // We are at the top of this chain.
2602         // If the copy has a glue operand, we conservatively assume it
2603         // isn't safe to perform a tail call.
2604         if (UI->getOperand(UI->getNumOperands()-1).getValueType() == MVT::Glue)
2605           return false;
2606         // First CopyToReg
2607         TCChain = UseChain;
2608       }
2609     }
2610   } else if (Copy->getOpcode() == ISD::BITCAST) {
2611     // f32 returned in a single GPR.
2612     if (!Copy->hasOneUse())
2613       return false;
2614     Copy = *Copy->use_begin();
2615     if (Copy->getOpcode() != ISD::CopyToReg || !Copy->hasNUsesOfValue(1, 0))
2616       return false;
2617     // If the copy has a glue operand, we conservatively assume it isn't safe to
2618     // perform a tail call.
2619     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2620       return false;
2621     TCChain = Copy->getOperand(0);
2622   } else {
2623     return false;
2624   }
2625 
2626   bool HasRet = false;
2627   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2628        UI != UE; ++UI) {
2629     if (UI->getOpcode() != ARMISD::RET_FLAG &&
2630         UI->getOpcode() != ARMISD::INTRET_FLAG)
2631       return false;
2632     HasRet = true;
2633   }
2634 
2635   if (!HasRet)
2636     return false;
2637 
2638   Chain = TCChain;
2639   return true;
2640 }
2641 
2642 bool ARMTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2643   if (!Subtarget->supportsTailCall())
2644     return false;
2645 
2646   auto Attr =
2647       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2648   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2649     return false;
2650 
2651   return true;
2652 }
2653 
2654 // Trying to write a 64 bit value so need to split into two 32 bit values first,
2655 // and pass the lower and high parts through.
2656 static SDValue LowerWRITE_REGISTER(SDValue Op, SelectionDAG &DAG) {
2657   SDLoc DL(Op);
2658   SDValue WriteValue = Op->getOperand(2);
2659 
2660   // This function is only supposed to be called for i64 type argument.
2661   assert(WriteValue.getValueType() == MVT::i64
2662           && "LowerWRITE_REGISTER called for non-i64 type argument.");
2663 
2664   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2665                            DAG.getConstant(0, DL, MVT::i32));
2666   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, WriteValue,
2667                            DAG.getConstant(1, DL, MVT::i32));
2668   SDValue Ops[] = { Op->getOperand(0), Op->getOperand(1), Lo, Hi };
2669   return DAG.getNode(ISD::WRITE_REGISTER, DL, MVT::Other, Ops);
2670 }
2671 
2672 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
2673 // their target counterpart wrapped in the ARMISD::Wrapper node. Suppose N is
2674 // one of the above mentioned nodes. It has to be wrapped because otherwise
2675 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
2676 // be used to form addressing mode. These wrapped nodes will be selected
2677 // into MOVi.
2678 SDValue ARMTargetLowering::LowerConstantPool(SDValue Op,
2679                                              SelectionDAG &DAG) const {
2680   EVT PtrVT = Op.getValueType();
2681   // FIXME there is no actual debug info here
2682   SDLoc dl(Op);
2683   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
2684   SDValue Res;
2685 
2686   // When generating execute-only code Constant Pools must be promoted to the
2687   // global data section. It's a bit ugly that we can't share them across basic
2688   // blocks, but this way we guarantee that execute-only behaves correct with
2689   // position-independent addressing modes.
2690   if (Subtarget->genExecuteOnly()) {
2691     auto AFI = DAG.getMachineFunction().getInfo<ARMFunctionInfo>();
2692     auto T = const_cast<Type*>(CP->getType());
2693     auto C = const_cast<Constant*>(CP->getConstVal());
2694     auto M = const_cast<Module*>(DAG.getMachineFunction().
2695                                  getFunction().getParent());
2696     auto GV = new GlobalVariable(
2697                     *M, T, /*isConst=*/true, GlobalVariable::InternalLinkage, C,
2698                     Twine(DAG.getDataLayout().getPrivateGlobalPrefix()) + "CP" +
2699                     Twine(DAG.getMachineFunction().getFunctionNumber()) + "_" +
2700                     Twine(AFI->createPICLabelUId())
2701                   );
2702     SDValue GA = DAG.getTargetGlobalAddress(dyn_cast<GlobalValue>(GV),
2703                                             dl, PtrVT);
2704     return LowerGlobalAddress(GA, DAG);
2705   }
2706 
2707   if (CP->isMachineConstantPoolEntry())
2708     Res = DAG.getTargetConstantPool(CP->getMachineCPVal(), PtrVT,
2709                                     CP->getAlignment());
2710   else
2711     Res = DAG.getTargetConstantPool(CP->getConstVal(), PtrVT,
2712                                     CP->getAlignment());
2713   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Res);
2714 }
2715 
2716 unsigned ARMTargetLowering::getJumpTableEncoding() const {
2717   return MachineJumpTableInfo::EK_Inline;
2718 }
2719 
2720 SDValue ARMTargetLowering::LowerBlockAddress(SDValue Op,
2721                                              SelectionDAG &DAG) const {
2722   MachineFunction &MF = DAG.getMachineFunction();
2723   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2724   unsigned ARMPCLabelIndex = 0;
2725   SDLoc DL(Op);
2726   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2727   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
2728   SDValue CPAddr;
2729   bool IsPositionIndependent = isPositionIndependent() || Subtarget->isROPI();
2730   if (!IsPositionIndependent) {
2731     CPAddr = DAG.getTargetConstantPool(BA, PtrVT, 4);
2732   } else {
2733     unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2734     ARMPCLabelIndex = AFI->createPICLabelUId();
2735     ARMConstantPoolValue *CPV =
2736       ARMConstantPoolConstant::Create(BA, ARMPCLabelIndex,
2737                                       ARMCP::CPBlockAddress, PCAdj);
2738     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2739   }
2740   CPAddr = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, CPAddr);
2741   SDValue Result = DAG.getLoad(
2742       PtrVT, DL, DAG.getEntryNode(), CPAddr,
2743       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2744   if (!IsPositionIndependent)
2745     return Result;
2746   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, DL, MVT::i32);
2747   return DAG.getNode(ARMISD::PIC_ADD, DL, PtrVT, Result, PICLabel);
2748 }
2749 
2750 /// \brief Convert a TLS address reference into the correct sequence of loads
2751 /// and calls to compute the variable's address for Darwin, and return an
2752 /// SDValue containing the final node.
2753 
2754 /// Darwin only has one TLS scheme which must be capable of dealing with the
2755 /// fully general situation, in the worst case. This means:
2756 ///     + "extern __thread" declaration.
2757 ///     + Defined in a possibly unknown dynamic library.
2758 ///
2759 /// The general system is that each __thread variable has a [3 x i32] descriptor
2760 /// which contains information used by the runtime to calculate the address. The
2761 /// only part of this the compiler needs to know about is the first word, which
2762 /// contains a function pointer that must be called with the address of the
2763 /// entire descriptor in "r0".
2764 ///
2765 /// Since this descriptor may be in a different unit, in general access must
2766 /// proceed along the usual ARM rules. A common sequence to produce is:
2767 ///
2768 ///     movw rT1, :lower16:_var$non_lazy_ptr
2769 ///     movt rT1, :upper16:_var$non_lazy_ptr
2770 ///     ldr r0, [rT1]
2771 ///     ldr rT2, [r0]
2772 ///     blx rT2
2773 ///     [...address now in r0...]
2774 SDValue
2775 ARMTargetLowering::LowerGlobalTLSAddressDarwin(SDValue Op,
2776                                                SelectionDAG &DAG) const {
2777   assert(Subtarget->isTargetDarwin() &&
2778          "This function expects a Darwin target");
2779   SDLoc DL(Op);
2780 
2781   // First step is to get the address of the actua global symbol. This is where
2782   // the TLS descriptor lives.
2783   SDValue DescAddr = LowerGlobalAddressDarwin(Op, DAG);
2784 
2785   // The first entry in the descriptor is a function pointer that we must call
2786   // to obtain the address of the variable.
2787   SDValue Chain = DAG.getEntryNode();
2788   SDValue FuncTLVGet = DAG.getLoad(
2789       MVT::i32, DL, Chain, DescAddr,
2790       MachinePointerInfo::getGOT(DAG.getMachineFunction()),
2791       /* Alignment = */ 4,
2792       MachineMemOperand::MONonTemporal | MachineMemOperand::MODereferenceable |
2793           MachineMemOperand::MOInvariant);
2794   Chain = FuncTLVGet.getValue(1);
2795 
2796   MachineFunction &F = DAG.getMachineFunction();
2797   MachineFrameInfo &MFI = F.getFrameInfo();
2798   MFI.setAdjustsStack(true);
2799 
2800   // TLS calls preserve all registers except those that absolutely must be
2801   // trashed: R0 (it takes an argument), LR (it's a call) and CPSR (let's not be
2802   // silly).
2803   auto TRI =
2804       getTargetMachine().getSubtargetImpl(F.getFunction())->getRegisterInfo();
2805   auto ARI = static_cast<const ARMRegisterInfo *>(TRI);
2806   const uint32_t *Mask = ARI->getTLSCallPreservedMask(DAG.getMachineFunction());
2807 
2808   // Finally, we can make the call. This is just a degenerate version of a
2809   // normal AArch64 call node: r0 takes the address of the descriptor, and
2810   // returns the address of the variable in this thread.
2811   Chain = DAG.getCopyToReg(Chain, DL, ARM::R0, DescAddr, SDValue());
2812   Chain =
2813       DAG.getNode(ARMISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2814                   Chain, FuncTLVGet, DAG.getRegister(ARM::R0, MVT::i32),
2815                   DAG.getRegisterMask(Mask), Chain.getValue(1));
2816   return DAG.getCopyFromReg(Chain, DL, ARM::R0, MVT::i32, Chain.getValue(1));
2817 }
2818 
2819 SDValue
2820 ARMTargetLowering::LowerGlobalTLSAddressWindows(SDValue Op,
2821                                                 SelectionDAG &DAG) const {
2822   assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
2823 
2824   SDValue Chain = DAG.getEntryNode();
2825   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2826   SDLoc DL(Op);
2827 
2828   // Load the current TEB (thread environment block)
2829   SDValue Ops[] = {Chain,
2830                    DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
2831                    DAG.getConstant(15, DL, MVT::i32),
2832                    DAG.getConstant(0, DL, MVT::i32),
2833                    DAG.getConstant(13, DL, MVT::i32),
2834                    DAG.getConstant(0, DL, MVT::i32),
2835                    DAG.getConstant(2, DL, MVT::i32)};
2836   SDValue CurrentTEB = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
2837                                    DAG.getVTList(MVT::i32, MVT::Other), Ops);
2838 
2839   SDValue TEB = CurrentTEB.getValue(0);
2840   Chain = CurrentTEB.getValue(1);
2841 
2842   // Load the ThreadLocalStoragePointer from the TEB
2843   // A pointer to the TLS array is located at offset 0x2c from the TEB.
2844   SDValue TLSArray =
2845       DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x2c, DL));
2846   TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
2847 
2848   // The pointer to the thread's TLS data area is at the TLS Index scaled by 4
2849   // offset into the TLSArray.
2850 
2851   // Load the TLS index from the C runtime
2852   SDValue TLSIndex =
2853       DAG.getTargetExternalSymbol("_tls_index", PtrVT, ARMII::MO_NO_FLAG);
2854   TLSIndex = DAG.getNode(ARMISD::Wrapper, DL, PtrVT, TLSIndex);
2855   TLSIndex = DAG.getLoad(PtrVT, DL, Chain, TLSIndex, MachinePointerInfo());
2856 
2857   SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
2858                               DAG.getConstant(2, DL, MVT::i32));
2859   SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
2860                             DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
2861                             MachinePointerInfo());
2862 
2863   // Get the offset of the start of the .tls section (section base)
2864   const auto *GA = cast<GlobalAddressSDNode>(Op);
2865   auto *CPV = ARMConstantPoolConstant::Create(GA->getGlobal(), ARMCP::SECREL);
2866   SDValue Offset = DAG.getLoad(
2867       PtrVT, DL, Chain, DAG.getNode(ARMISD::Wrapper, DL, MVT::i32,
2868                                     DAG.getTargetConstantPool(CPV, PtrVT, 4)),
2869       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2870 
2871   return DAG.getNode(ISD::ADD, DL, PtrVT, TLS, Offset);
2872 }
2873 
2874 // Lower ISD::GlobalTLSAddress using the "general dynamic" model
2875 SDValue
2876 ARMTargetLowering::LowerToTLSGeneralDynamicModel(GlobalAddressSDNode *GA,
2877                                                  SelectionDAG &DAG) const {
2878   SDLoc dl(GA);
2879   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2880   unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2881   MachineFunction &MF = DAG.getMachineFunction();
2882   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2883   unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2884   ARMConstantPoolValue *CPV =
2885     ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2886                                     ARMCP::CPValue, PCAdj, ARMCP::TLSGD, true);
2887   SDValue Argument = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2888   Argument = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Argument);
2889   Argument = DAG.getLoad(
2890       PtrVT, dl, DAG.getEntryNode(), Argument,
2891       MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2892   SDValue Chain = Argument.getValue(1);
2893 
2894   SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2895   Argument = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Argument, PICLabel);
2896 
2897   // call __tls_get_addr.
2898   ArgListTy Args;
2899   ArgListEntry Entry;
2900   Entry.Node = Argument;
2901   Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
2902   Args.push_back(Entry);
2903 
2904   // FIXME: is there useful debug info available here?
2905   TargetLowering::CallLoweringInfo CLI(DAG);
2906   CLI.setDebugLoc(dl).setChain(Chain).setLibCallee(
2907       CallingConv::C, Type::getInt32Ty(*DAG.getContext()),
2908       DAG.getExternalSymbol("__tls_get_addr", PtrVT), std::move(Args));
2909 
2910   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2911   return CallResult.first;
2912 }
2913 
2914 // Lower ISD::GlobalTLSAddress using the "initial exec" or
2915 // "local exec" model.
2916 SDValue
2917 ARMTargetLowering::LowerToTLSExecModels(GlobalAddressSDNode *GA,
2918                                         SelectionDAG &DAG,
2919                                         TLSModel::Model model) const {
2920   const GlobalValue *GV = GA->getGlobal();
2921   SDLoc dl(GA);
2922   SDValue Offset;
2923   SDValue Chain = DAG.getEntryNode();
2924   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2925   // Get the Thread Pointer
2926   SDValue ThreadPointer = DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
2927 
2928   if (model == TLSModel::InitialExec) {
2929     MachineFunction &MF = DAG.getMachineFunction();
2930     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
2931     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2932     // Initial exec model.
2933     unsigned char PCAdj = Subtarget->isThumb() ? 4 : 8;
2934     ARMConstantPoolValue *CPV =
2935       ARMConstantPoolConstant::Create(GA->getGlobal(), ARMPCLabelIndex,
2936                                       ARMCP::CPValue, PCAdj, ARMCP::GOTTPOFF,
2937                                       true);
2938     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2939     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2940     Offset = DAG.getLoad(
2941         PtrVT, dl, Chain, Offset,
2942         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2943     Chain = Offset.getValue(1);
2944 
2945     SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
2946     Offset = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Offset, PICLabel);
2947 
2948     Offset = DAG.getLoad(
2949         PtrVT, dl, Chain, Offset,
2950         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2951   } else {
2952     // local exec model
2953     assert(model == TLSModel::LocalExec);
2954     ARMConstantPoolValue *CPV =
2955       ARMConstantPoolConstant::Create(GV, ARMCP::TPOFF);
2956     Offset = DAG.getTargetConstantPool(CPV, PtrVT, 4);
2957     Offset = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, Offset);
2958     Offset = DAG.getLoad(
2959         PtrVT, dl, Chain, Offset,
2960         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
2961   }
2962 
2963   // The address of the thread local variable is the add of the thread
2964   // pointer with the offset of the variable.
2965   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2966 }
2967 
2968 SDValue
2969 ARMTargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
2970   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2971   if (DAG.getTarget().Options.EmulatedTLS)
2972     return LowerToTLSEmulatedModel(GA, DAG);
2973 
2974   if (Subtarget->isTargetDarwin())
2975     return LowerGlobalTLSAddressDarwin(Op, DAG);
2976 
2977   if (Subtarget->isTargetWindows())
2978     return LowerGlobalTLSAddressWindows(Op, DAG);
2979 
2980   // TODO: implement the "local dynamic" model
2981   assert(Subtarget->isTargetELF() && "Only ELF implemented here");
2982   TLSModel::Model model = getTargetMachine().getTLSModel(GA->getGlobal());
2983 
2984   switch (model) {
2985     case TLSModel::GeneralDynamic:
2986     case TLSModel::LocalDynamic:
2987       return LowerToTLSGeneralDynamicModel(GA, DAG);
2988     case TLSModel::InitialExec:
2989     case TLSModel::LocalExec:
2990       return LowerToTLSExecModels(GA, DAG, model);
2991   }
2992   llvm_unreachable("bogus TLS model");
2993 }
2994 
2995 /// Return true if all users of V are within function F, looking through
2996 /// ConstantExprs.
2997 static bool allUsersAreInFunction(const Value *V, const Function *F) {
2998   SmallVector<const User*,4> Worklist;
2999   for (auto *U : V->users())
3000     Worklist.push_back(U);
3001   while (!Worklist.empty()) {
3002     auto *U = Worklist.pop_back_val();
3003     if (isa<ConstantExpr>(U)) {
3004       for (auto *UU : U->users())
3005         Worklist.push_back(UU);
3006       continue;
3007     }
3008 
3009     auto *I = dyn_cast<Instruction>(U);
3010     if (!I || I->getParent()->getParent() != F)
3011       return false;
3012   }
3013   return true;
3014 }
3015 
3016 /// Return true if all users of V are within some (any) function, looking through
3017 /// ConstantExprs. In other words, are there any global constant users?
3018 static bool allUsersAreInFunctions(const Value *V) {
3019   SmallVector<const User*,4> Worklist;
3020   for (auto *U : V->users())
3021     Worklist.push_back(U);
3022   while (!Worklist.empty()) {
3023     auto *U = Worklist.pop_back_val();
3024     if (isa<ConstantExpr>(U)) {
3025       for (auto *UU : U->users())
3026         Worklist.push_back(UU);
3027       continue;
3028     }
3029 
3030     if (!isa<Instruction>(U))
3031       return false;
3032   }
3033   return true;
3034 }
3035 
3036 // Return true if T is an integer, float or an array/vector of either.
3037 static bool isSimpleType(Type *T) {
3038   if (T->isIntegerTy() || T->isFloatingPointTy())
3039     return true;
3040   Type *SubT = nullptr;
3041   if (T->isArrayTy())
3042     SubT = T->getArrayElementType();
3043   else if (T->isVectorTy())
3044     SubT = T->getVectorElementType();
3045   else
3046     return false;
3047   return SubT->isIntegerTy() || SubT->isFloatingPointTy();
3048 }
3049 
3050 static SDValue promoteToConstantPool(const GlobalValue *GV, SelectionDAG &DAG,
3051                                      EVT PtrVT, const SDLoc &dl) {
3052   // If we're creating a pool entry for a constant global with unnamed address,
3053   // and the global is small enough, we can emit it inline into the constant pool
3054   // to save ourselves an indirection.
3055   //
3056   // This is a win if the constant is only used in one function (so it doesn't
3057   // need to be duplicated) or duplicating the constant wouldn't increase code
3058   // size (implying the constant is no larger than 4 bytes).
3059   const Function &F = DAG.getMachineFunction().getFunction();
3060 
3061   // We rely on this decision to inline being idemopotent and unrelated to the
3062   // use-site. We know that if we inline a variable at one use site, we'll
3063   // inline it elsewhere too (and reuse the constant pool entry). Fast-isel
3064   // doesn't know about this optimization, so bail out if it's enabled else
3065   // we could decide to inline here (and thus never emit the GV) but require
3066   // the GV from fast-isel generated code.
3067   if (!EnableConstpoolPromotion ||
3068       DAG.getMachineFunction().getTarget().Options.EnableFastISel)
3069       return SDValue();
3070 
3071   auto *GVar = dyn_cast<GlobalVariable>(GV);
3072   if (!GVar || !GVar->hasInitializer() ||
3073       !GVar->isConstant() || !GVar->hasGlobalUnnamedAddr() ||
3074       !GVar->hasLocalLinkage())
3075     return SDValue();
3076 
3077   // Ensure that we don't try and inline any type that contains pointers. If
3078   // we inline a value that contains relocations, we move the relocations from
3079   // .data to .text which is not ideal.
3080   auto *Init = GVar->getInitializer();
3081   if (!isSimpleType(Init->getType()))
3082     return SDValue();
3083 
3084   // The constant islands pass can only really deal with alignment requests
3085   // <= 4 bytes and cannot pad constants itself. Therefore we cannot promote
3086   // any type wanting greater alignment requirements than 4 bytes. We also
3087   // can only promote constants that are multiples of 4 bytes in size or
3088   // are paddable to a multiple of 4. Currently we only try and pad constants
3089   // that are strings for simplicity.
3090   auto *CDAInit = dyn_cast<ConstantDataArray>(Init);
3091   unsigned Size = DAG.getDataLayout().getTypeAllocSize(Init->getType());
3092   unsigned Align = GVar->getAlignment();
3093   unsigned RequiredPadding = 4 - (Size % 4);
3094   bool PaddingPossible =
3095     RequiredPadding == 4 || (CDAInit && CDAInit->isString());
3096   if (!PaddingPossible || Align > 4 || Size > ConstpoolPromotionMaxSize ||
3097       Size == 0)
3098     return SDValue();
3099 
3100   unsigned PaddedSize = Size + ((RequiredPadding == 4) ? 0 : RequiredPadding);
3101   MachineFunction &MF = DAG.getMachineFunction();
3102   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3103 
3104   // We can't bloat the constant pool too much, else the ConstantIslands pass
3105   // may fail to converge. If we haven't promoted this global yet (it may have
3106   // multiple uses), and promoting it would increase the constant pool size (Sz
3107   // > 4), ensure we have space to do so up to MaxTotal.
3108   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar) && Size > 4)
3109     if (AFI->getPromotedConstpoolIncrease() + PaddedSize - 4 >=
3110         ConstpoolPromotionMaxTotal)
3111       return SDValue();
3112 
3113   // This is only valid if all users are in a single function OR it has users
3114   // in multiple functions but it no larger than a pointer. We also check if
3115   // GVar has constant (non-ConstantExpr) users. If so, it essentially has its
3116   // address taken.
3117   if (!allUsersAreInFunction(GVar, &F) &&
3118       !(Size <= 4 && allUsersAreInFunctions(GVar)))
3119     return SDValue();
3120 
3121   // We're going to inline this global. Pad it out if needed.
3122   if (RequiredPadding != 4) {
3123     StringRef S = CDAInit->getAsString();
3124 
3125     SmallVector<uint8_t,16> V(S.size());
3126     std::copy(S.bytes_begin(), S.bytes_end(), V.begin());
3127     while (RequiredPadding--)
3128       V.push_back(0);
3129     Init = ConstantDataArray::get(*DAG.getContext(), V);
3130   }
3131 
3132   auto CPVal = ARMConstantPoolConstant::Create(GVar, Init);
3133   SDValue CPAddr =
3134     DAG.getTargetConstantPool(CPVal, PtrVT, /*Align=*/4);
3135   if (!AFI->getGlobalsPromotedToConstantPool().count(GVar)) {
3136     AFI->markGlobalAsPromotedToConstantPool(GVar);
3137     AFI->setPromotedConstpoolIncrease(AFI->getPromotedConstpoolIncrease() +
3138                                       PaddedSize - 4);
3139   }
3140   ++NumConstpoolPromoted;
3141   return DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3142 }
3143 
3144 bool ARMTargetLowering::isReadOnly(const GlobalValue *GV) const {
3145   if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
3146     GV = GA->getBaseObject();
3147   return (isa<GlobalVariable>(GV) && cast<GlobalVariable>(GV)->isConstant()) ||
3148          isa<Function>(GV);
3149 }
3150 
3151 SDValue ARMTargetLowering::LowerGlobalAddress(SDValue Op,
3152                                               SelectionDAG &DAG) const {
3153   switch (Subtarget->getTargetTriple().getObjectFormat()) {
3154   default: llvm_unreachable("unknown object format");
3155   case Triple::COFF:
3156     return LowerGlobalAddressWindows(Op, DAG);
3157   case Triple::ELF:
3158     return LowerGlobalAddressELF(Op, DAG);
3159   case Triple::MachO:
3160     return LowerGlobalAddressDarwin(Op, DAG);
3161   }
3162 }
3163 
3164 SDValue ARMTargetLowering::LowerGlobalAddressELF(SDValue Op,
3165                                                  SelectionDAG &DAG) const {
3166   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3167   SDLoc dl(Op);
3168   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3169   const TargetMachine &TM = getTargetMachine();
3170   bool IsRO = isReadOnly(GV);
3171 
3172   // promoteToConstantPool only if not generating XO text section
3173   if (TM.shouldAssumeDSOLocal(*GV->getParent(), GV) && !Subtarget->genExecuteOnly())
3174     if (SDValue V = promoteToConstantPool(GV, DAG, PtrVT, dl))
3175       return V;
3176 
3177   if (isPositionIndependent()) {
3178     bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
3179     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
3180                                            UseGOT_PREL ? ARMII::MO_GOT : 0);
3181     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3182     if (UseGOT_PREL)
3183       Result =
3184           DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3185                       MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3186     return Result;
3187   } else if (Subtarget->isROPI() && IsRO) {
3188     // PC-relative.
3189     SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT);
3190     SDValue Result = DAG.getNode(ARMISD::WrapperPIC, dl, PtrVT, G);
3191     return Result;
3192   } else if (Subtarget->isRWPI() && !IsRO) {
3193     // SB-relative.
3194     SDValue RelAddr;
3195     if (Subtarget->useMovt(DAG.getMachineFunction())) {
3196       ++NumMovwMovt;
3197       SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_SBREL);
3198       RelAddr = DAG.getNode(ARMISD::Wrapper, dl, PtrVT, G);
3199     } else { // use literal pool for address constant
3200       ARMConstantPoolValue *CPV =
3201         ARMConstantPoolConstant::Create(GV, ARMCP::SBREL);
3202       SDValue CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3203       CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3204       RelAddr = DAG.getLoad(
3205           PtrVT, dl, DAG.getEntryNode(), CPAddr,
3206           MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3207     }
3208     SDValue SB = DAG.getCopyFromReg(DAG.getEntryNode(), dl, ARM::R9, PtrVT);
3209     SDValue Result = DAG.getNode(ISD::ADD, dl, PtrVT, SB, RelAddr);
3210     return Result;
3211   }
3212 
3213   // If we have T2 ops, we can materialize the address directly via movt/movw
3214   // pair. This is always cheaper.
3215   if (Subtarget->useMovt(DAG.getMachineFunction())) {
3216     ++NumMovwMovt;
3217     // FIXME: Once remat is capable of dealing with instructions with register
3218     // operands, expand this into two nodes.
3219     return DAG.getNode(ARMISD::Wrapper, dl, PtrVT,
3220                        DAG.getTargetGlobalAddress(GV, dl, PtrVT));
3221   } else {
3222     SDValue CPAddr = DAG.getTargetConstantPool(GV, PtrVT, 4);
3223     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3224     return DAG.getLoad(
3225         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3226         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3227   }
3228 }
3229 
3230 SDValue ARMTargetLowering::LowerGlobalAddressDarwin(SDValue Op,
3231                                                     SelectionDAG &DAG) const {
3232   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3233          "ROPI/RWPI not currently supported for Darwin");
3234   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3235   SDLoc dl(Op);
3236   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3237 
3238   if (Subtarget->useMovt(DAG.getMachineFunction()))
3239     ++NumMovwMovt;
3240 
3241   // FIXME: Once remat is capable of dealing with instructions with register
3242   // operands, expand this into multiple nodes
3243   unsigned Wrapper =
3244       isPositionIndependent() ? ARMISD::WrapperPIC : ARMISD::Wrapper;
3245 
3246   SDValue G = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, ARMII::MO_NONLAZY);
3247   SDValue Result = DAG.getNode(Wrapper, dl, PtrVT, G);
3248 
3249   if (Subtarget->isGVIndirectSymbol(GV))
3250     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
3251                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3252   return Result;
3253 }
3254 
3255 SDValue ARMTargetLowering::LowerGlobalAddressWindows(SDValue Op,
3256                                                      SelectionDAG &DAG) const {
3257   assert(Subtarget->isTargetWindows() && "non-Windows COFF is not supported");
3258   assert(Subtarget->useMovt(DAG.getMachineFunction()) &&
3259          "Windows on ARM expects to use movw/movt");
3260   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
3261          "ROPI/RWPI not currently supported for Windows");
3262 
3263   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
3264   const ARMII::TOF TargetFlags =
3265     (GV->hasDLLImportStorageClass() ? ARMII::MO_DLLIMPORT : ARMII::MO_NO_FLAG);
3266   EVT PtrVT = getPointerTy(DAG.getDataLayout());
3267   SDValue Result;
3268   SDLoc DL(Op);
3269 
3270   ++NumMovwMovt;
3271 
3272   // FIXME: Once remat is capable of dealing with instructions with register
3273   // operands, expand this into two nodes.
3274   Result = DAG.getNode(ARMISD::Wrapper, DL, PtrVT,
3275                        DAG.getTargetGlobalAddress(GV, DL, PtrVT, /*Offset=*/0,
3276                                                   TargetFlags));
3277   if (GV->hasDLLImportStorageClass())
3278     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
3279                          MachinePointerInfo::getGOT(DAG.getMachineFunction()));
3280   return Result;
3281 }
3282 
3283 SDValue
3284 ARMTargetLowering::LowerEH_SJLJ_SETJMP(SDValue Op, SelectionDAG &DAG) const {
3285   SDLoc dl(Op);
3286   SDValue Val = DAG.getConstant(0, dl, MVT::i32);
3287   return DAG.getNode(ARMISD::EH_SJLJ_SETJMP, dl,
3288                      DAG.getVTList(MVT::i32, MVT::Other), Op.getOperand(0),
3289                      Op.getOperand(1), Val);
3290 }
3291 
3292 SDValue
3293 ARMTargetLowering::LowerEH_SJLJ_LONGJMP(SDValue Op, SelectionDAG &DAG) const {
3294   SDLoc dl(Op);
3295   return DAG.getNode(ARMISD::EH_SJLJ_LONGJMP, dl, MVT::Other, Op.getOperand(0),
3296                      Op.getOperand(1), DAG.getConstant(0, dl, MVT::i32));
3297 }
3298 
3299 SDValue ARMTargetLowering::LowerEH_SJLJ_SETUP_DISPATCH(SDValue Op,
3300                                                       SelectionDAG &DAG) const {
3301   SDLoc dl(Op);
3302   return DAG.getNode(ARMISD::EH_SJLJ_SETUP_DISPATCH, dl, MVT::Other,
3303                      Op.getOperand(0));
3304 }
3305 
3306 SDValue
3307 ARMTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG,
3308                                           const ARMSubtarget *Subtarget) const {
3309   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
3310   SDLoc dl(Op);
3311   switch (IntNo) {
3312   default: return SDValue();    // Don't custom lower most intrinsics.
3313   case Intrinsic::thread_pointer: {
3314     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3315     return DAG.getNode(ARMISD::THREAD_POINTER, dl, PtrVT);
3316   }
3317   case Intrinsic::eh_sjlj_lsda: {
3318     MachineFunction &MF = DAG.getMachineFunction();
3319     ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3320     unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
3321     EVT PtrVT = getPointerTy(DAG.getDataLayout());
3322     SDValue CPAddr;
3323     bool IsPositionIndependent = isPositionIndependent();
3324     unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
3325     ARMConstantPoolValue *CPV =
3326       ARMConstantPoolConstant::Create(&MF.getFunction(), ARMPCLabelIndex,
3327                                       ARMCP::CPLSDA, PCAdj);
3328     CPAddr = DAG.getTargetConstantPool(CPV, PtrVT, 4);
3329     CPAddr = DAG.getNode(ARMISD::Wrapper, dl, MVT::i32, CPAddr);
3330     SDValue Result = DAG.getLoad(
3331         PtrVT, dl, DAG.getEntryNode(), CPAddr,
3332         MachinePointerInfo::getConstantPool(DAG.getMachineFunction()));
3333 
3334     if (IsPositionIndependent) {
3335       SDValue PICLabel = DAG.getConstant(ARMPCLabelIndex, dl, MVT::i32);
3336       Result = DAG.getNode(ARMISD::PIC_ADD, dl, PtrVT, Result, PICLabel);
3337     }
3338     return Result;
3339   }
3340   case Intrinsic::arm_neon_vabs:
3341     return DAG.getNode(ISD::ABS, SDLoc(Op), Op.getValueType(),
3342                         Op.getOperand(1));
3343   case Intrinsic::arm_neon_vmulls:
3344   case Intrinsic::arm_neon_vmullu: {
3345     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmulls)
3346       ? ARMISD::VMULLs : ARMISD::VMULLu;
3347     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3348                        Op.getOperand(1), Op.getOperand(2));
3349   }
3350   case Intrinsic::arm_neon_vminnm:
3351   case Intrinsic::arm_neon_vmaxnm: {
3352     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminnm)
3353       ? ISD::FMINNUM : ISD::FMAXNUM;
3354     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3355                        Op.getOperand(1), Op.getOperand(2));
3356   }
3357   case Intrinsic::arm_neon_vminu:
3358   case Intrinsic::arm_neon_vmaxu: {
3359     if (Op.getValueType().isFloatingPoint())
3360       return SDValue();
3361     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vminu)
3362       ? ISD::UMIN : ISD::UMAX;
3363     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3364                          Op.getOperand(1), Op.getOperand(2));
3365   }
3366   case Intrinsic::arm_neon_vmins:
3367   case Intrinsic::arm_neon_vmaxs: {
3368     // v{min,max}s is overloaded between signed integers and floats.
3369     if (!Op.getValueType().isFloatingPoint()) {
3370       unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3371         ? ISD::SMIN : ISD::SMAX;
3372       return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3373                          Op.getOperand(1), Op.getOperand(2));
3374     }
3375     unsigned NewOpc = (IntNo == Intrinsic::arm_neon_vmins)
3376       ? ISD::FMINNAN : ISD::FMAXNAN;
3377     return DAG.getNode(NewOpc, SDLoc(Op), Op.getValueType(),
3378                        Op.getOperand(1), Op.getOperand(2));
3379   }
3380   case Intrinsic::arm_neon_vtbl1:
3381     return DAG.getNode(ARMISD::VTBL1, SDLoc(Op), Op.getValueType(),
3382                        Op.getOperand(1), Op.getOperand(2));
3383   case Intrinsic::arm_neon_vtbl2:
3384     return DAG.getNode(ARMISD::VTBL2, SDLoc(Op), Op.getValueType(),
3385                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
3386   }
3387 }
3388 
3389 static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG,
3390                                  const ARMSubtarget *Subtarget) {
3391   SDLoc dl(Op);
3392   ConstantSDNode *SSIDNode = cast<ConstantSDNode>(Op.getOperand(2));
3393   auto SSID = static_cast<SyncScope::ID>(SSIDNode->getZExtValue());
3394   if (SSID == SyncScope::SingleThread)
3395     return Op;
3396 
3397   if (!Subtarget->hasDataBarrier()) {
3398     // Some ARMv6 cpus can support data barriers with an mcr instruction.
3399     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
3400     // here.
3401     assert(Subtarget->hasV6Ops() && !Subtarget->isThumb() &&
3402            "Unexpected ISD::ATOMIC_FENCE encountered. Should be libcall!");
3403     return DAG.getNode(ARMISD::MEMBARRIER_MCR, dl, MVT::Other, Op.getOperand(0),
3404                        DAG.getConstant(0, dl, MVT::i32));
3405   }
3406 
3407   ConstantSDNode *OrdN = cast<ConstantSDNode>(Op.getOperand(1));
3408   AtomicOrdering Ord = static_cast<AtomicOrdering>(OrdN->getZExtValue());
3409   ARM_MB::MemBOpt Domain = ARM_MB::ISH;
3410   if (Subtarget->isMClass()) {
3411     // Only a full system barrier exists in the M-class architectures.
3412     Domain = ARM_MB::SY;
3413   } else if (Subtarget->preferISHSTBarriers() &&
3414              Ord == AtomicOrdering::Release) {
3415     // Swift happens to implement ISHST barriers in a way that's compatible with
3416     // Release semantics but weaker than ISH so we'd be fools not to use
3417     // it. Beware: other processors probably don't!
3418     Domain = ARM_MB::ISHST;
3419   }
3420 
3421   return DAG.getNode(ISD::INTRINSIC_VOID, dl, MVT::Other, Op.getOperand(0),
3422                      DAG.getConstant(Intrinsic::arm_dmb, dl, MVT::i32),
3423                      DAG.getConstant(Domain, dl, MVT::i32));
3424 }
3425 
3426 static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG,
3427                              const ARMSubtarget *Subtarget) {
3428   // ARM pre v5TE and Thumb1 does not have preload instructions.
3429   if (!(Subtarget->isThumb2() ||
3430         (!Subtarget->isThumb1Only() && Subtarget->hasV5TEOps())))
3431     // Just preserve the chain.
3432     return Op.getOperand(0);
3433 
3434   SDLoc dl(Op);
3435   unsigned isRead = ~cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue() & 1;
3436   if (!isRead &&
3437       (!Subtarget->hasV7Ops() || !Subtarget->hasMPExtension()))
3438     // ARMv7 with MP extension has PLDW.
3439     return Op.getOperand(0);
3440 
3441   unsigned isData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
3442   if (Subtarget->isThumb()) {
3443     // Invert the bits.
3444     isRead = ~isRead & 1;
3445     isData = ~isData & 1;
3446   }
3447 
3448   return DAG.getNode(ARMISD::PRELOAD, dl, MVT::Other, Op.getOperand(0),
3449                      Op.getOperand(1), DAG.getConstant(isRead, dl, MVT::i32),
3450                      DAG.getConstant(isData, dl, MVT::i32));
3451 }
3452 
3453 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG) {
3454   MachineFunction &MF = DAG.getMachineFunction();
3455   ARMFunctionInfo *FuncInfo = MF.getInfo<ARMFunctionInfo>();
3456 
3457   // vastart just stores the address of the VarArgsFrameIndex slot into the
3458   // memory location argument.
3459   SDLoc dl(Op);
3460   EVT PtrVT = DAG.getTargetLoweringInfo().getPointerTy(DAG.getDataLayout());
3461   SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
3462   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
3463   return DAG.getStore(Op.getOperand(0), dl, FR, Op.getOperand(1),
3464                       MachinePointerInfo(SV));
3465 }
3466 
3467 SDValue ARMTargetLowering::GetF64FormalArgument(CCValAssign &VA,
3468                                                 CCValAssign &NextVA,
3469                                                 SDValue &Root,
3470                                                 SelectionDAG &DAG,
3471                                                 const SDLoc &dl) const {
3472   MachineFunction &MF = DAG.getMachineFunction();
3473   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3474 
3475   const TargetRegisterClass *RC;
3476   if (AFI->isThumb1OnlyFunction())
3477     RC = &ARM::tGPRRegClass;
3478   else
3479     RC = &ARM::GPRRegClass;
3480 
3481   // Transform the arguments stored in physical registers into virtual ones.
3482   unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3483   SDValue ArgValue = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3484 
3485   SDValue ArgValue2;
3486   if (NextVA.isMemLoc()) {
3487     MachineFrameInfo &MFI = MF.getFrameInfo();
3488     int FI = MFI.CreateFixedObject(4, NextVA.getLocMemOffset(), true);
3489 
3490     // Create load node to retrieve arguments from the stack.
3491     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3492     ArgValue2 = DAG.getLoad(
3493         MVT::i32, dl, Root, FIN,
3494         MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3495   } else {
3496     Reg = MF.addLiveIn(NextVA.getLocReg(), RC);
3497     ArgValue2 = DAG.getCopyFromReg(Root, dl, Reg, MVT::i32);
3498   }
3499   if (!Subtarget->isLittle())
3500     std::swap (ArgValue, ArgValue2);
3501   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, ArgValue, ArgValue2);
3502 }
3503 
3504 // The remaining GPRs hold either the beginning of variable-argument
3505 // data, or the beginning of an aggregate passed by value (usually
3506 // byval).  Either way, we allocate stack slots adjacent to the data
3507 // provided by our caller, and store the unallocated registers there.
3508 // If this is a variadic function, the va_list pointer will begin with
3509 // these values; otherwise, this reassembles a (byval) structure that
3510 // was split between registers and memory.
3511 // Return: The frame index registers were stored into.
3512 int ARMTargetLowering::StoreByValRegs(CCState &CCInfo, SelectionDAG &DAG,
3513                                       const SDLoc &dl, SDValue &Chain,
3514                                       const Value *OrigArg,
3515                                       unsigned InRegsParamRecordIdx,
3516                                       int ArgOffset, unsigned ArgSize) const {
3517   // Currently, two use-cases possible:
3518   // Case #1. Non-var-args function, and we meet first byval parameter.
3519   //          Setup first unallocated register as first byval register;
3520   //          eat all remained registers
3521   //          (these two actions are performed by HandleByVal method).
3522   //          Then, here, we initialize stack frame with
3523   //          "store-reg" instructions.
3524   // Case #2. Var-args function, that doesn't contain byval parameters.
3525   //          The same: eat all remained unallocated registers,
3526   //          initialize stack frame.
3527 
3528   MachineFunction &MF = DAG.getMachineFunction();
3529   MachineFrameInfo &MFI = MF.getFrameInfo();
3530   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3531   unsigned RBegin, REnd;
3532   if (InRegsParamRecordIdx < CCInfo.getInRegsParamsCount()) {
3533     CCInfo.getInRegsParamInfo(InRegsParamRecordIdx, RBegin, REnd);
3534   } else {
3535     unsigned RBeginIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3536     RBegin = RBeginIdx == 4 ? (unsigned)ARM::R4 : GPRArgRegs[RBeginIdx];
3537     REnd = ARM::R4;
3538   }
3539 
3540   if (REnd != RBegin)
3541     ArgOffset = -4 * (ARM::R4 - RBegin);
3542 
3543   auto PtrVT = getPointerTy(DAG.getDataLayout());
3544   int FrameIndex = MFI.CreateFixedObject(ArgSize, ArgOffset, false);
3545   SDValue FIN = DAG.getFrameIndex(FrameIndex, PtrVT);
3546 
3547   SmallVector<SDValue, 4> MemOps;
3548   const TargetRegisterClass *RC =
3549       AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
3550 
3551   for (unsigned Reg = RBegin, i = 0; Reg < REnd; ++Reg, ++i) {
3552     unsigned VReg = MF.addLiveIn(Reg, RC);
3553     SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
3554     SDValue Store = DAG.getStore(Val.getValue(1), dl, Val, FIN,
3555                                  MachinePointerInfo(OrigArg, 4 * i));
3556     MemOps.push_back(Store);
3557     FIN = DAG.getNode(ISD::ADD, dl, PtrVT, FIN, DAG.getConstant(4, dl, PtrVT));
3558   }
3559 
3560   if (!MemOps.empty())
3561     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
3562   return FrameIndex;
3563 }
3564 
3565 // Setup stack frame, the va_list pointer will start from.
3566 void ARMTargetLowering::VarArgStyleRegisters(CCState &CCInfo, SelectionDAG &DAG,
3567                                              const SDLoc &dl, SDValue &Chain,
3568                                              unsigned ArgOffset,
3569                                              unsigned TotalArgRegsSaveSize,
3570                                              bool ForceMutable) const {
3571   MachineFunction &MF = DAG.getMachineFunction();
3572   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3573 
3574   // Try to store any remaining integer argument regs
3575   // to their spots on the stack so that they may be loaded by dereferencing
3576   // the result of va_next.
3577   // If there is no regs to be stored, just point address after last
3578   // argument passed via stack.
3579   int FrameIndex = StoreByValRegs(CCInfo, DAG, dl, Chain, nullptr,
3580                                   CCInfo.getInRegsParamsCount(),
3581                                   CCInfo.getNextStackOffset(), 4);
3582   AFI->setVarArgsFrameIndex(FrameIndex);
3583 }
3584 
3585 SDValue ARMTargetLowering::LowerFormalArguments(
3586     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
3587     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &dl,
3588     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3589   MachineFunction &MF = DAG.getMachineFunction();
3590   MachineFrameInfo &MFI = MF.getFrameInfo();
3591 
3592   ARMFunctionInfo *AFI = MF.getInfo<ARMFunctionInfo>();
3593 
3594   // Assign locations to all of the incoming arguments.
3595   SmallVector<CCValAssign, 16> ArgLocs;
3596   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
3597                  *DAG.getContext());
3598   CCInfo.AnalyzeFormalArguments(Ins, CCAssignFnForCall(CallConv, isVarArg));
3599 
3600   SmallVector<SDValue, 16> ArgValues;
3601   SDValue ArgValue;
3602   Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
3603   unsigned CurArgIdx = 0;
3604 
3605   // Initially ArgRegsSaveSize is zero.
3606   // Then we increase this value each time we meet byval parameter.
3607   // We also increase this value in case of varargs function.
3608   AFI->setArgRegsSaveSize(0);
3609 
3610   // Calculate the amount of stack space that we need to allocate to store
3611   // byval and variadic arguments that are passed in registers.
3612   // We need to know this before we allocate the first byval or variadic
3613   // argument, as they will be allocated a stack slot below the CFA (Canonical
3614   // Frame Address, the stack pointer at entry to the function).
3615   unsigned ArgRegBegin = ARM::R4;
3616   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3617     if (CCInfo.getInRegsParamsProcessed() >= CCInfo.getInRegsParamsCount())
3618       break;
3619 
3620     CCValAssign &VA = ArgLocs[i];
3621     unsigned Index = VA.getValNo();
3622     ISD::ArgFlagsTy Flags = Ins[Index].Flags;
3623     if (!Flags.isByVal())
3624       continue;
3625 
3626     assert(VA.isMemLoc() && "unexpected byval pointer in reg");
3627     unsigned RBegin, REnd;
3628     CCInfo.getInRegsParamInfo(CCInfo.getInRegsParamsProcessed(), RBegin, REnd);
3629     ArgRegBegin = std::min(ArgRegBegin, RBegin);
3630 
3631     CCInfo.nextInRegsParam();
3632   }
3633   CCInfo.rewindByValRegsInfo();
3634 
3635   int lastInsIndex = -1;
3636   if (isVarArg && MFI.hasVAStart()) {
3637     unsigned RegIdx = CCInfo.getFirstUnallocated(GPRArgRegs);
3638     if (RegIdx != array_lengthof(GPRArgRegs))
3639       ArgRegBegin = std::min(ArgRegBegin, (unsigned)GPRArgRegs[RegIdx]);
3640   }
3641 
3642   unsigned TotalArgRegsSaveSize = 4 * (ARM::R4 - ArgRegBegin);
3643   AFI->setArgRegsSaveSize(TotalArgRegsSaveSize);
3644   auto PtrVT = getPointerTy(DAG.getDataLayout());
3645 
3646   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3647     CCValAssign &VA = ArgLocs[i];
3648     if (Ins[VA.getValNo()].isOrigArg()) {
3649       std::advance(CurOrigArg,
3650                    Ins[VA.getValNo()].getOrigArgIndex() - CurArgIdx);
3651       CurArgIdx = Ins[VA.getValNo()].getOrigArgIndex();
3652     }
3653     // Arguments stored in registers.
3654     if (VA.isRegLoc()) {
3655       EVT RegVT = VA.getLocVT();
3656 
3657       if (VA.needsCustom()) {
3658         // f64 and vector types are split up into multiple registers or
3659         // combinations of registers and stack slots.
3660         if (VA.getLocVT() == MVT::v2f64) {
3661           SDValue ArgValue1 = GetF64FormalArgument(VA, ArgLocs[++i],
3662                                                    Chain, DAG, dl);
3663           VA = ArgLocs[++i]; // skip ahead to next loc
3664           SDValue ArgValue2;
3665           if (VA.isMemLoc()) {
3666             int FI = MFI.CreateFixedObject(8, VA.getLocMemOffset(), true);
3667             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3668             ArgValue2 = DAG.getLoad(MVT::f64, dl, Chain, FIN,
3669                                     MachinePointerInfo::getFixedStack(
3670                                         DAG.getMachineFunction(), FI));
3671           } else {
3672             ArgValue2 = GetF64FormalArgument(VA, ArgLocs[++i],
3673                                              Chain, DAG, dl);
3674           }
3675           ArgValue = DAG.getNode(ISD::UNDEF, dl, MVT::v2f64);
3676           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3677                                  ArgValue, ArgValue1,
3678                                  DAG.getIntPtrConstant(0, dl));
3679           ArgValue = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64,
3680                                  ArgValue, ArgValue2,
3681                                  DAG.getIntPtrConstant(1, dl));
3682         } else
3683           ArgValue = GetF64FormalArgument(VA, ArgLocs[++i], Chain, DAG, dl);
3684       } else {
3685         const TargetRegisterClass *RC;
3686 
3687         if (RegVT == MVT::f32)
3688           RC = &ARM::SPRRegClass;
3689         else if (RegVT == MVT::f64)
3690           RC = &ARM::DPRRegClass;
3691         else if (RegVT == MVT::v2f64)
3692           RC = &ARM::QPRRegClass;
3693         else if (RegVT == MVT::i32)
3694           RC = AFI->isThumb1OnlyFunction() ? &ARM::tGPRRegClass
3695                                            : &ARM::GPRRegClass;
3696         else
3697           llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
3698 
3699         // Transform the arguments in physical registers into virtual ones.
3700         unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
3701         ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3702       }
3703 
3704       // If this is an 8 or 16-bit value, it is really passed promoted
3705       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3706       // truncate to the right size.
3707       switch (VA.getLocInfo()) {
3708       default: llvm_unreachable("Unknown loc info!");
3709       case CCValAssign::Full: break;
3710       case CCValAssign::BCvt:
3711         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
3712         break;
3713       case CCValAssign::SExt:
3714         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
3715                                DAG.getValueType(VA.getValVT()));
3716         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3717         break;
3718       case CCValAssign::ZExt:
3719         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
3720                                DAG.getValueType(VA.getValVT()));
3721         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
3722         break;
3723       }
3724 
3725       InVals.push_back(ArgValue);
3726     } else { // VA.isRegLoc()
3727       // sanity check
3728       assert(VA.isMemLoc());
3729       assert(VA.getValVT() != MVT::i64 && "i64 should already be lowered");
3730 
3731       int index = VA.getValNo();
3732 
3733       // Some Ins[] entries become multiple ArgLoc[] entries.
3734       // Process them only once.
3735       if (index != lastInsIndex)
3736         {
3737           ISD::ArgFlagsTy Flags = Ins[index].Flags;
3738           // FIXME: For now, all byval parameter objects are marked mutable.
3739           // This can be changed with more analysis.
3740           // In case of tail call optimization mark all arguments mutable.
3741           // Since they could be overwritten by lowering of arguments in case of
3742           // a tail call.
3743           if (Flags.isByVal()) {
3744             assert(Ins[index].isOrigArg() &&
3745                    "Byval arguments cannot be implicit");
3746             unsigned CurByValIndex = CCInfo.getInRegsParamsProcessed();
3747 
3748             int FrameIndex = StoreByValRegs(
3749                 CCInfo, DAG, dl, Chain, &*CurOrigArg, CurByValIndex,
3750                 VA.getLocMemOffset(), Flags.getByValSize());
3751             InVals.push_back(DAG.getFrameIndex(FrameIndex, PtrVT));
3752             CCInfo.nextInRegsParam();
3753           } else {
3754             unsigned FIOffset = VA.getLocMemOffset();
3755             int FI = MFI.CreateFixedObject(VA.getLocVT().getSizeInBits()/8,
3756                                            FIOffset, true);
3757 
3758             // Create load nodes to retrieve arguments from the stack.
3759             SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
3760             InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
3761                                          MachinePointerInfo::getFixedStack(
3762                                              DAG.getMachineFunction(), FI)));
3763           }
3764           lastInsIndex = index;
3765         }
3766     }
3767   }
3768 
3769   // varargs
3770   if (isVarArg && MFI.hasVAStart())
3771     VarArgStyleRegisters(CCInfo, DAG, dl, Chain,
3772                          CCInfo.getNextStackOffset(),
3773                          TotalArgRegsSaveSize);
3774 
3775   AFI->setArgumentStackSize(CCInfo.getNextStackOffset());
3776 
3777   return Chain;
3778 }
3779 
3780 /// isFloatingPointZero - Return true if this is +0.0.
3781 static bool isFloatingPointZero(SDValue Op) {
3782   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
3783     return CFP->getValueAPF().isPosZero();
3784   else if (ISD::isEXTLoad(Op.getNode()) || ISD::isNON_EXTLoad(Op.getNode())) {
3785     // Maybe this has already been legalized into the constant pool?
3786     if (Op.getOperand(1).getOpcode() == ARMISD::Wrapper) {
3787       SDValue WrapperOp = Op.getOperand(1).getOperand(0);
3788       if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(WrapperOp))
3789         if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CP->getConstVal()))
3790           return CFP->getValueAPF().isPosZero();
3791     }
3792   } else if (Op->getOpcode() == ISD::BITCAST &&
3793              Op->getValueType(0) == MVT::f64) {
3794     // Handle (ISD::BITCAST (ARMISD::VMOVIMM (ISD::TargetConstant 0)) MVT::f64)
3795     // created by LowerConstantFP().
3796     SDValue BitcastOp = Op->getOperand(0);
3797     if (BitcastOp->getOpcode() == ARMISD::VMOVIMM &&
3798         isNullConstant(BitcastOp->getOperand(0)))
3799       return true;
3800   }
3801   return false;
3802 }
3803 
3804 /// Returns appropriate ARM CMP (cmp) and corresponding condition code for
3805 /// the given operands.
3806 SDValue ARMTargetLowering::getARMCmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
3807                                      SDValue &ARMcc, SelectionDAG &DAG,
3808                                      const SDLoc &dl) const {
3809   if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
3810     unsigned C = RHSC->getZExtValue();
3811     if (!isLegalICmpImmediate(C)) {
3812       // Constant does not fit, try adjusting it by one?
3813       switch (CC) {
3814       default: break;
3815       case ISD::SETLT:
3816       case ISD::SETGE:
3817         if (C != 0x80000000 && isLegalICmpImmediate(C-1)) {
3818           CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
3819           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3820         }
3821         break;
3822       case ISD::SETULT:
3823       case ISD::SETUGE:
3824         if (C != 0 && isLegalICmpImmediate(C-1)) {
3825           CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
3826           RHS = DAG.getConstant(C - 1, dl, MVT::i32);
3827         }
3828         break;
3829       case ISD::SETLE:
3830       case ISD::SETGT:
3831         if (C != 0x7fffffff && isLegalICmpImmediate(C+1)) {
3832           CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
3833           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3834         }
3835         break;
3836       case ISD::SETULE:
3837       case ISD::SETUGT:
3838         if (C != 0xffffffff && isLegalICmpImmediate(C+1)) {
3839           CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
3840           RHS = DAG.getConstant(C + 1, dl, MVT::i32);
3841         }
3842         break;
3843       }
3844     }
3845   } else if ((ARM_AM::getShiftOpcForNode(LHS.getOpcode()) != ARM_AM::no_shift) &&
3846              (ARM_AM::getShiftOpcForNode(RHS.getOpcode()) == ARM_AM::no_shift)) {
3847     // In ARM and Thumb-2, the compare instructions can shift their second
3848     // operand.
3849     CC = ISD::getSetCCSwappedOperands(CC);
3850     std::swap(LHS, RHS);
3851   }
3852 
3853   ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
3854   ARMISD::NodeType CompareType;
3855   switch (CondCode) {
3856   default:
3857     CompareType = ARMISD::CMP;
3858     break;
3859   case ARMCC::EQ:
3860   case ARMCC::NE:
3861     // Uses only Z Flag
3862     CompareType = ARMISD::CMPZ;
3863     break;
3864   }
3865   ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
3866   return DAG.getNode(CompareType, dl, MVT::Glue, LHS, RHS);
3867 }
3868 
3869 /// Returns a appropriate VFP CMP (fcmp{s|d}+fmstat) for the given operands.
3870 SDValue ARMTargetLowering::getVFPCmp(SDValue LHS, SDValue RHS,
3871                                      SelectionDAG &DAG, const SDLoc &dl,
3872                                      bool InvalidOnQNaN) const {
3873   assert(!Subtarget->isFPOnlySP() || RHS.getValueType() != MVT::f64);
3874   SDValue Cmp;
3875   SDValue C = DAG.getConstant(InvalidOnQNaN, dl, MVT::i32);
3876   if (!isFloatingPointZero(RHS))
3877     Cmp = DAG.getNode(ARMISD::CMPFP, dl, MVT::Glue, LHS, RHS, C);
3878   else
3879     Cmp = DAG.getNode(ARMISD::CMPFPw0, dl, MVT::Glue, LHS, C);
3880   return DAG.getNode(ARMISD::FMSTAT, dl, MVT::Glue, Cmp);
3881 }
3882 
3883 /// duplicateCmp - Glue values can have only one use, so this function
3884 /// duplicates a comparison node.
3885 SDValue
3886 ARMTargetLowering::duplicateCmp(SDValue Cmp, SelectionDAG &DAG) const {
3887   unsigned Opc = Cmp.getOpcode();
3888   SDLoc DL(Cmp);
3889   if (Opc == ARMISD::CMP || Opc == ARMISD::CMPZ)
3890     return DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),Cmp.getOperand(1));
3891 
3892   assert(Opc == ARMISD::FMSTAT && "unexpected comparison operation");
3893   Cmp = Cmp.getOperand(0);
3894   Opc = Cmp.getOpcode();
3895   if (Opc == ARMISD::CMPFP)
3896     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3897                       Cmp.getOperand(1), Cmp.getOperand(2));
3898   else {
3899     assert(Opc == ARMISD::CMPFPw0 && "unexpected operand of FMSTAT");
3900     Cmp = DAG.getNode(Opc, DL, MVT::Glue, Cmp.getOperand(0),
3901                       Cmp.getOperand(1));
3902   }
3903   return DAG.getNode(ARMISD::FMSTAT, DL, MVT::Glue, Cmp);
3904 }
3905 
3906 // This function returns three things: the arithmetic computation itself
3907 // (Value), a comparison (OverflowCmp), and a condition code (ARMcc).  The
3908 // comparison and the condition code define the case in which the arithmetic
3909 // computation *does not* overflow.
3910 std::pair<SDValue, SDValue>
3911 ARMTargetLowering::getARMXALUOOp(SDValue Op, SelectionDAG &DAG,
3912                                  SDValue &ARMcc) const {
3913   assert(Op.getValueType() == MVT::i32 &&  "Unsupported value type");
3914 
3915   SDValue Value, OverflowCmp;
3916   SDValue LHS = Op.getOperand(0);
3917   SDValue RHS = Op.getOperand(1);
3918   SDLoc dl(Op);
3919 
3920   // FIXME: We are currently always generating CMPs because we don't support
3921   // generating CMN through the backend. This is not as good as the natural
3922   // CMP case because it causes a register dependency and cannot be folded
3923   // later.
3924 
3925   switch (Op.getOpcode()) {
3926   default:
3927     llvm_unreachable("Unknown overflow instruction!");
3928   case ISD::SADDO:
3929     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3930     Value = DAG.getNode(ISD::ADD, dl, Op.getValueType(), LHS, RHS);
3931     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3932     break;
3933   case ISD::UADDO:
3934     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3935     // We use ADDC here to correspond to its use in LowerUnsignedALUO.
3936     // We do not use it in the USUBO case as Value may not be used.
3937     Value = DAG.getNode(ARMISD::ADDC, dl,
3938                         DAG.getVTList(Op.getValueType(), MVT::i32), LHS, RHS)
3939                 .getValue(0);
3940     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value, LHS);
3941     break;
3942   case ISD::SSUBO:
3943     ARMcc = DAG.getConstant(ARMCC::VC, dl, MVT::i32);
3944     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3945     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3946     break;
3947   case ISD::USUBO:
3948     ARMcc = DAG.getConstant(ARMCC::HS, dl, MVT::i32);
3949     Value = DAG.getNode(ISD::SUB, dl, Op.getValueType(), LHS, RHS);
3950     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, LHS, RHS);
3951     break;
3952   case ISD::UMULO:
3953     // We generate a UMUL_LOHI and then check if the high word is 0.
3954     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
3955     Value = DAG.getNode(ISD::UMUL_LOHI, dl,
3956                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
3957                         LHS, RHS);
3958     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
3959                               DAG.getConstant(0, dl, MVT::i32));
3960     Value = Value.getValue(0); // We only want the low 32 bits for the result.
3961     break;
3962   case ISD::SMULO:
3963     // We generate a SMUL_LOHI and then check if all the bits of the high word
3964     // are the same as the sign bit of the low word.
3965     ARMcc = DAG.getConstant(ARMCC::EQ, dl, MVT::i32);
3966     Value = DAG.getNode(ISD::SMUL_LOHI, dl,
3967                         DAG.getVTList(Op.getValueType(), Op.getValueType()),
3968                         LHS, RHS);
3969     OverflowCmp = DAG.getNode(ARMISD::CMP, dl, MVT::Glue, Value.getValue(1),
3970                               DAG.getNode(ISD::SRA, dl, Op.getValueType(),
3971                                           Value.getValue(0),
3972                                           DAG.getConstant(31, dl, MVT::i32)));
3973     Value = Value.getValue(0); // We only want the low 32 bits for the result.
3974     break;
3975   } // switch (...)
3976 
3977   return std::make_pair(Value, OverflowCmp);
3978 }
3979 
3980 SDValue
3981 ARMTargetLowering::LowerSignedALUO(SDValue Op, SelectionDAG &DAG) const {
3982   // Let legalize expand this if it isn't a legal type yet.
3983   if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
3984     return SDValue();
3985 
3986   SDValue Value, OverflowCmp;
3987   SDValue ARMcc;
3988   std::tie(Value, OverflowCmp) = getARMXALUOOp(Op, DAG, ARMcc);
3989   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
3990   SDLoc dl(Op);
3991   // We use 0 and 1 as false and true values.
3992   SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
3993   SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
3994   EVT VT = Op.getValueType();
3995 
3996   SDValue Overflow = DAG.getNode(ARMISD::CMOV, dl, VT, TVal, FVal,
3997                                  ARMcc, CCR, OverflowCmp);
3998 
3999   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
4000   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4001 }
4002 
4003 static SDValue ConvertBooleanCarryToCarryFlag(SDValue BoolCarry,
4004                                               SelectionDAG &DAG) {
4005   SDLoc DL(BoolCarry);
4006   EVT CarryVT = BoolCarry.getValueType();
4007 
4008   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
4009   // This converts the boolean value carry into the carry flag by doing
4010   // ARMISD::ADDC Carry, ~0
4011   return DAG.getNode(ARMISD::ADDC, DL, DAG.getVTList(CarryVT, MVT::i32),
4012                      BoolCarry, DAG.getConstant(NegOne, DL, CarryVT));
4013 }
4014 
4015 static SDValue ConvertCarryFlagToBooleanCarry(SDValue Flags, EVT VT,
4016                                               SelectionDAG &DAG) {
4017   SDLoc DL(Flags);
4018 
4019   // Now convert the carry flag into a boolean carry. We do this
4020   // using ARMISD:ADDE 0, 0, Carry
4021   return DAG.getNode(ARMISD::ADDE, DL, DAG.getVTList(VT, MVT::i32),
4022                      DAG.getConstant(0, DL, MVT::i32),
4023                      DAG.getConstant(0, DL, MVT::i32), Flags);
4024 }
4025 
4026 SDValue ARMTargetLowering::LowerUnsignedALUO(SDValue Op,
4027                                              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 LHS = Op.getOperand(0);
4033   SDValue RHS = Op.getOperand(1);
4034   SDLoc dl(Op);
4035 
4036   EVT VT = Op.getValueType();
4037   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
4038   SDValue Value;
4039   SDValue Overflow;
4040   switch (Op.getOpcode()) {
4041   default:
4042     llvm_unreachable("Unknown overflow instruction!");
4043   case ISD::UADDO:
4044     Value = DAG.getNode(ARMISD::ADDC, dl, VTs, LHS, RHS);
4045     // Convert the carry flag into a boolean value.
4046     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4047     break;
4048   case ISD::USUBO: {
4049     Value = DAG.getNode(ARMISD::SUBC, dl, VTs, LHS, RHS);
4050     // Convert the carry flag into a boolean value.
4051     Overflow = ConvertCarryFlagToBooleanCarry(Value.getValue(1), VT, DAG);
4052     // ARMISD::SUBC returns 0 when we have to borrow, so make it an overflow
4053     // value. So compute 1 - C.
4054     Overflow = DAG.getNode(ISD::SUB, dl, MVT::i32,
4055                            DAG.getConstant(1, dl, MVT::i32), Overflow);
4056     break;
4057   }
4058   }
4059 
4060   return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
4061 }
4062 
4063 SDValue ARMTargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
4064   SDValue Cond = Op.getOperand(0);
4065   SDValue SelectTrue = Op.getOperand(1);
4066   SDValue SelectFalse = Op.getOperand(2);
4067   SDLoc dl(Op);
4068   unsigned Opc = Cond.getOpcode();
4069 
4070   if (Cond.getResNo() == 1 &&
4071       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4072        Opc == ISD::USUBO)) {
4073     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4074       return SDValue();
4075 
4076     SDValue Value, OverflowCmp;
4077     SDValue ARMcc;
4078     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4079     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4080     EVT VT = Op.getValueType();
4081 
4082     return getCMOV(dl, VT, SelectTrue, SelectFalse, ARMcc, CCR,
4083                    OverflowCmp, DAG);
4084   }
4085 
4086   // Convert:
4087   //
4088   //   (select (cmov 1, 0, cond), t, f) -> (cmov t, f, cond)
4089   //   (select (cmov 0, 1, cond), t, f) -> (cmov f, t, cond)
4090   //
4091   if (Cond.getOpcode() == ARMISD::CMOV && Cond.hasOneUse()) {
4092     const ConstantSDNode *CMOVTrue =
4093       dyn_cast<ConstantSDNode>(Cond.getOperand(0));
4094     const ConstantSDNode *CMOVFalse =
4095       dyn_cast<ConstantSDNode>(Cond.getOperand(1));
4096 
4097     if (CMOVTrue && CMOVFalse) {
4098       unsigned CMOVTrueVal = CMOVTrue->getZExtValue();
4099       unsigned CMOVFalseVal = CMOVFalse->getZExtValue();
4100 
4101       SDValue True;
4102       SDValue False;
4103       if (CMOVTrueVal == 1 && CMOVFalseVal == 0) {
4104         True = SelectTrue;
4105         False = SelectFalse;
4106       } else if (CMOVTrueVal == 0 && CMOVFalseVal == 1) {
4107         True = SelectFalse;
4108         False = SelectTrue;
4109       }
4110 
4111       if (True.getNode() && False.getNode()) {
4112         EVT VT = Op.getValueType();
4113         SDValue ARMcc = Cond.getOperand(2);
4114         SDValue CCR = Cond.getOperand(3);
4115         SDValue Cmp = duplicateCmp(Cond.getOperand(4), DAG);
4116         assert(True.getValueType() == VT);
4117         return getCMOV(dl, VT, True, False, ARMcc, CCR, Cmp, DAG);
4118       }
4119     }
4120   }
4121 
4122   // ARM's BooleanContents value is UndefinedBooleanContent. Mask out the
4123   // undefined bits before doing a full-word comparison with zero.
4124   Cond = DAG.getNode(ISD::AND, dl, Cond.getValueType(), Cond,
4125                      DAG.getConstant(1, dl, Cond.getValueType()));
4126 
4127   return DAG.getSelectCC(dl, Cond,
4128                          DAG.getConstant(0, dl, Cond.getValueType()),
4129                          SelectTrue, SelectFalse, ISD::SETNE);
4130 }
4131 
4132 static void checkVSELConstraints(ISD::CondCode CC, ARMCC::CondCodes &CondCode,
4133                                  bool &swpCmpOps, bool &swpVselOps) {
4134   // Start by selecting the GE condition code for opcodes that return true for
4135   // 'equality'
4136   if (CC == ISD::SETUGE || CC == ISD::SETOGE || CC == ISD::SETOLE ||
4137       CC == ISD::SETULE)
4138     CondCode = ARMCC::GE;
4139 
4140   // and GT for opcodes that return false for 'equality'.
4141   else if (CC == ISD::SETUGT || CC == ISD::SETOGT || CC == ISD::SETOLT ||
4142            CC == ISD::SETULT)
4143     CondCode = ARMCC::GT;
4144 
4145   // Since we are constrained to GE/GT, if the opcode contains 'less', we need
4146   // to swap the compare operands.
4147   if (CC == ISD::SETOLE || CC == ISD::SETULE || CC == ISD::SETOLT ||
4148       CC == ISD::SETULT)
4149     swpCmpOps = true;
4150 
4151   // Both GT and GE are ordered comparisons, and return false for 'unordered'.
4152   // If we have an unordered opcode, we need to swap the operands to the VSEL
4153   // instruction (effectively negating the condition).
4154   //
4155   // This also has the effect of swapping which one of 'less' or 'greater'
4156   // returns true, so we also swap the compare operands. It also switches
4157   // whether we return true for 'equality', so we compensate by picking the
4158   // opposite condition code to our original choice.
4159   if (CC == ISD::SETULE || CC == ISD::SETULT || CC == ISD::SETUGE ||
4160       CC == ISD::SETUGT) {
4161     swpCmpOps = !swpCmpOps;
4162     swpVselOps = !swpVselOps;
4163     CondCode = CondCode == ARMCC::GT ? ARMCC::GE : ARMCC::GT;
4164   }
4165 
4166   // 'ordered' is 'anything but unordered', so use the VS condition code and
4167   // swap the VSEL operands.
4168   if (CC == ISD::SETO) {
4169     CondCode = ARMCC::VS;
4170     swpVselOps = true;
4171   }
4172 
4173   // 'unordered or not equal' is 'anything but equal', so use the EQ condition
4174   // code and swap the VSEL operands.
4175   if (CC == ISD::SETUNE) {
4176     CondCode = ARMCC::EQ;
4177     swpVselOps = true;
4178   }
4179 }
4180 
4181 SDValue ARMTargetLowering::getCMOV(const SDLoc &dl, EVT VT, SDValue FalseVal,
4182                                    SDValue TrueVal, SDValue ARMcc, SDValue CCR,
4183                                    SDValue Cmp, SelectionDAG &DAG) const {
4184   if (Subtarget->isFPOnlySP() && VT == MVT::f64) {
4185     FalseVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4186                            DAG.getVTList(MVT::i32, MVT::i32), FalseVal);
4187     TrueVal = DAG.getNode(ARMISD::VMOVRRD, dl,
4188                           DAG.getVTList(MVT::i32, MVT::i32), TrueVal);
4189 
4190     SDValue TrueLow = TrueVal.getValue(0);
4191     SDValue TrueHigh = TrueVal.getValue(1);
4192     SDValue FalseLow = FalseVal.getValue(0);
4193     SDValue FalseHigh = FalseVal.getValue(1);
4194 
4195     SDValue Low = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseLow, TrueLow,
4196                               ARMcc, CCR, Cmp);
4197     SDValue High = DAG.getNode(ARMISD::CMOV, dl, MVT::i32, FalseHigh, TrueHigh,
4198                                ARMcc, CCR, duplicateCmp(Cmp, DAG));
4199 
4200     return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Low, High);
4201   } else {
4202     return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal, ARMcc, CCR,
4203                        Cmp);
4204   }
4205 }
4206 
4207 static bool isGTorGE(ISD::CondCode CC) {
4208   return CC == ISD::SETGT || CC == ISD::SETGE;
4209 }
4210 
4211 static bool isLTorLE(ISD::CondCode CC) {
4212   return CC == ISD::SETLT || CC == ISD::SETLE;
4213 }
4214 
4215 // See if a conditional (LHS CC RHS ? TrueVal : FalseVal) is lower-saturating.
4216 // All of these conditions (and their <= and >= counterparts) will do:
4217 //          x < k ? k : x
4218 //          x > k ? x : k
4219 //          k < x ? x : k
4220 //          k > x ? k : x
4221 static bool isLowerSaturate(const SDValue LHS, const SDValue RHS,
4222                             const SDValue TrueVal, const SDValue FalseVal,
4223                             const ISD::CondCode CC, const SDValue K) {
4224   return (isGTorGE(CC) &&
4225           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal))) ||
4226          (isLTorLE(CC) &&
4227           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal)));
4228 }
4229 
4230 // Similar to isLowerSaturate(), but checks for upper-saturating conditions.
4231 static bool isUpperSaturate(const SDValue LHS, const SDValue RHS,
4232                             const SDValue TrueVal, const SDValue FalseVal,
4233                             const ISD::CondCode CC, const SDValue K) {
4234   return (isGTorGE(CC) &&
4235           ((K == RHS && K == TrueVal) || (K == LHS && K == FalseVal))) ||
4236          (isLTorLE(CC) &&
4237           ((K == LHS && K == TrueVal) || (K == RHS && K == FalseVal)));
4238 }
4239 
4240 // Check if two chained conditionals could be converted into SSAT or USAT.
4241 //
4242 // SSAT can replace a set of two conditional selectors that bound a number to an
4243 // interval of type [k, ~k] when k + 1 is a power of 2. Here are some examples:
4244 //
4245 //     x < -k ? -k : (x > k ? k : x)
4246 //     x < -k ? -k : (x < k ? x : k)
4247 //     x > -k ? (x > k ? k : x) : -k
4248 //     x < k ? (x < -k ? -k : x) : k
4249 //     etc.
4250 //
4251 // USAT works similarily to SSAT but bounds on the interval [0, k] where k + 1 is
4252 // a power of 2.
4253 //
4254 // It returns true if the conversion can be done, false otherwise.
4255 // Additionally, the variable is returned in parameter V, the constant in K and
4256 // usat is set to true if the conditional represents an unsigned saturation
4257 static bool isSaturatingConditional(const SDValue &Op, SDValue &V,
4258                                     uint64_t &K, bool &usat) {
4259   SDValue LHS1 = Op.getOperand(0);
4260   SDValue RHS1 = Op.getOperand(1);
4261   SDValue TrueVal1 = Op.getOperand(2);
4262   SDValue FalseVal1 = Op.getOperand(3);
4263   ISD::CondCode CC1 = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4264 
4265   const SDValue Op2 = isa<ConstantSDNode>(TrueVal1) ? FalseVal1 : TrueVal1;
4266   if (Op2.getOpcode() != ISD::SELECT_CC)
4267     return false;
4268 
4269   SDValue LHS2 = Op2.getOperand(0);
4270   SDValue RHS2 = Op2.getOperand(1);
4271   SDValue TrueVal2 = Op2.getOperand(2);
4272   SDValue FalseVal2 = Op2.getOperand(3);
4273   ISD::CondCode CC2 = cast<CondCodeSDNode>(Op2.getOperand(4))->get();
4274 
4275   // Find out which are the constants and which are the variables
4276   // in each conditional
4277   SDValue *K1 = isa<ConstantSDNode>(LHS1) ? &LHS1 : isa<ConstantSDNode>(RHS1)
4278                                                         ? &RHS1
4279                                                         : nullptr;
4280   SDValue *K2 = isa<ConstantSDNode>(LHS2) ? &LHS2 : isa<ConstantSDNode>(RHS2)
4281                                                         ? &RHS2
4282                                                         : nullptr;
4283   SDValue K2Tmp = isa<ConstantSDNode>(TrueVal2) ? TrueVal2 : FalseVal2;
4284   SDValue V1Tmp = (K1 && *K1 == LHS1) ? RHS1 : LHS1;
4285   SDValue V2Tmp = (K2 && *K2 == LHS2) ? RHS2 : LHS2;
4286   SDValue V2 = (K2Tmp == TrueVal2) ? FalseVal2 : TrueVal2;
4287 
4288   // We must detect cases where the original operations worked with 16- or
4289   // 8-bit values. In such case, V2Tmp != V2 because the comparison operations
4290   // must work with sign-extended values but the select operations return
4291   // the original non-extended value.
4292   SDValue V2TmpReg = V2Tmp;
4293   if (V2Tmp->getOpcode() == ISD::SIGN_EXTEND_INREG)
4294     V2TmpReg = V2Tmp->getOperand(0);
4295 
4296   // Check that the registers and the constants have the correct values
4297   // in both conditionals
4298   if (!K1 || !K2 || *K1 == Op2 || *K2 != K2Tmp || V1Tmp != V2Tmp ||
4299       V2TmpReg != V2)
4300     return false;
4301 
4302   // Figure out which conditional is saturating the lower/upper bound.
4303   const SDValue *LowerCheckOp =
4304       isLowerSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4305           ? &Op
4306           : isLowerSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4307                 ? &Op2
4308                 : nullptr;
4309   const SDValue *UpperCheckOp =
4310       isUpperSaturate(LHS1, RHS1, TrueVal1, FalseVal1, CC1, *K1)
4311           ? &Op
4312           : isUpperSaturate(LHS2, RHS2, TrueVal2, FalseVal2, CC2, *K2)
4313                 ? &Op2
4314                 : nullptr;
4315 
4316   if (!UpperCheckOp || !LowerCheckOp || LowerCheckOp == UpperCheckOp)
4317     return false;
4318 
4319   // Check that the constant in the lower-bound check is
4320   // the opposite of the constant in the upper-bound check
4321   // in 1's complement.
4322   int64_t Val1 = cast<ConstantSDNode>(*K1)->getSExtValue();
4323   int64_t Val2 = cast<ConstantSDNode>(*K2)->getSExtValue();
4324   int64_t PosVal = std::max(Val1, Val2);
4325   int64_t NegVal = std::min(Val1, Val2);
4326 
4327   if (((Val1 > Val2 && UpperCheckOp == &Op) ||
4328        (Val1 < Val2 && UpperCheckOp == &Op2)) &&
4329       isPowerOf2_64(PosVal + 1)) {
4330 
4331     // Handle the difference between USAT (unsigned) and SSAT (signed) saturation
4332     if (Val1 == ~Val2)
4333       usat = false;
4334     else if (NegVal == 0)
4335       usat = true;
4336     else
4337       return false;
4338 
4339     V = V2;
4340     K = (uint64_t)PosVal; // At this point, PosVal is guaranteed to be positive
4341 
4342     return true;
4343   }
4344 
4345   return false;
4346 }
4347 
4348 SDValue ARMTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
4349   EVT VT = Op.getValueType();
4350   SDLoc dl(Op);
4351 
4352   // Try to convert two saturating conditional selects into a single SSAT
4353   SDValue SatValue;
4354   uint64_t SatConstant;
4355   bool SatUSat;
4356   if (((!Subtarget->isThumb() && Subtarget->hasV6Ops()) || Subtarget->isThumb2()) &&
4357       isSaturatingConditional(Op, SatValue, SatConstant, SatUSat)) {
4358     if (SatUSat)
4359       return DAG.getNode(ARMISD::USAT, dl, VT, SatValue,
4360                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4361     else
4362       return DAG.getNode(ARMISD::SSAT, dl, VT, SatValue,
4363                          DAG.getConstant(countTrailingOnes(SatConstant), dl, VT));
4364   }
4365 
4366   SDValue LHS = Op.getOperand(0);
4367   SDValue RHS = Op.getOperand(1);
4368   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
4369   SDValue TrueVal = Op.getOperand(2);
4370   SDValue FalseVal = Op.getOperand(3);
4371 
4372   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4373     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4374                                                     dl);
4375 
4376     // If softenSetCCOperands only returned one value, we should compare it to
4377     // zero.
4378     if (!RHS.getNode()) {
4379       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4380       CC = ISD::SETNE;
4381     }
4382   }
4383 
4384   if (LHS.getValueType() == MVT::i32) {
4385     // Try to generate VSEL on ARMv8.
4386     // The VSEL instruction can't use all the usual ARM condition
4387     // codes: it only has two bits to select the condition code, so it's
4388     // constrained to use only GE, GT, VS and EQ.
4389     //
4390     // To implement all the various ISD::SETXXX opcodes, we sometimes need to
4391     // swap the operands of the previous compare instruction (effectively
4392     // inverting the compare condition, swapping 'less' and 'greater') and
4393     // sometimes need to swap the operands to the VSEL (which inverts the
4394     // condition in the sense of firing whenever the previous condition didn't)
4395     if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4396                                     TrueVal.getValueType() == MVT::f64)) {
4397       ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4398       if (CondCode == ARMCC::LT || CondCode == ARMCC::LE ||
4399           CondCode == ARMCC::VC || CondCode == ARMCC::NE) {
4400         CC = ISD::getSetCCInverse(CC, true);
4401         std::swap(TrueVal, FalseVal);
4402       }
4403     }
4404 
4405     SDValue ARMcc;
4406     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4407     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4408     return getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4409   }
4410 
4411   ARMCC::CondCodes CondCode, CondCode2;
4412   bool InvalidOnQNaN;
4413   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4414 
4415   // Try to generate VMAXNM/VMINNM on ARMv8.
4416   if (Subtarget->hasFPARMv8() && (TrueVal.getValueType() == MVT::f32 ||
4417                                   TrueVal.getValueType() == MVT::f64)) {
4418     bool swpCmpOps = false;
4419     bool swpVselOps = false;
4420     checkVSELConstraints(CC, CondCode, swpCmpOps, swpVselOps);
4421 
4422     if (CondCode == ARMCC::GT || CondCode == ARMCC::GE ||
4423         CondCode == ARMCC::VS || CondCode == ARMCC::EQ) {
4424       if (swpCmpOps)
4425         std::swap(LHS, RHS);
4426       if (swpVselOps)
4427         std::swap(TrueVal, FalseVal);
4428     }
4429   }
4430 
4431   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4432   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4433   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4434   SDValue Result = getCMOV(dl, VT, FalseVal, TrueVal, ARMcc, CCR, Cmp, DAG);
4435   if (CondCode2 != ARMCC::AL) {
4436     SDValue ARMcc2 = DAG.getConstant(CondCode2, dl, MVT::i32);
4437     // FIXME: Needs another CMP because flag can have but one use.
4438     SDValue Cmp2 = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4439     Result = getCMOV(dl, VT, Result, TrueVal, ARMcc2, CCR, Cmp2, DAG);
4440   }
4441   return Result;
4442 }
4443 
4444 /// canChangeToInt - Given the fp compare operand, return true if it is suitable
4445 /// to morph to an integer compare sequence.
4446 static bool canChangeToInt(SDValue Op, bool &SeenZero,
4447                            const ARMSubtarget *Subtarget) {
4448   SDNode *N = Op.getNode();
4449   if (!N->hasOneUse())
4450     // Otherwise it requires moving the value from fp to integer registers.
4451     return false;
4452   if (!N->getNumValues())
4453     return false;
4454   EVT VT = Op.getValueType();
4455   if (VT != MVT::f32 && !Subtarget->isFPBrccSlow())
4456     // f32 case is generally profitable. f64 case only makes sense when vcmpe +
4457     // vmrs are very slow, e.g. cortex-a8.
4458     return false;
4459 
4460   if (isFloatingPointZero(Op)) {
4461     SeenZero = true;
4462     return true;
4463   }
4464   return ISD::isNormalLoad(N);
4465 }
4466 
4467 static SDValue bitcastf32Toi32(SDValue Op, SelectionDAG &DAG) {
4468   if (isFloatingPointZero(Op))
4469     return DAG.getConstant(0, SDLoc(Op), MVT::i32);
4470 
4471   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op))
4472     return DAG.getLoad(MVT::i32, SDLoc(Op), Ld->getChain(), Ld->getBasePtr(),
4473                        Ld->getPointerInfo(), Ld->getAlignment(),
4474                        Ld->getMemOperand()->getFlags());
4475 
4476   llvm_unreachable("Unknown VFP cmp argument!");
4477 }
4478 
4479 static void expandf64Toi32(SDValue Op, SelectionDAG &DAG,
4480                            SDValue &RetVal1, SDValue &RetVal2) {
4481   SDLoc dl(Op);
4482 
4483   if (isFloatingPointZero(Op)) {
4484     RetVal1 = DAG.getConstant(0, dl, MVT::i32);
4485     RetVal2 = DAG.getConstant(0, dl, MVT::i32);
4486     return;
4487   }
4488 
4489   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Op)) {
4490     SDValue Ptr = Ld->getBasePtr();
4491     RetVal1 =
4492         DAG.getLoad(MVT::i32, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
4493                     Ld->getAlignment(), Ld->getMemOperand()->getFlags());
4494 
4495     EVT PtrType = Ptr.getValueType();
4496     unsigned NewAlign = MinAlign(Ld->getAlignment(), 4);
4497     SDValue NewPtr = DAG.getNode(ISD::ADD, dl,
4498                                  PtrType, Ptr, DAG.getConstant(4, dl, PtrType));
4499     RetVal2 = DAG.getLoad(MVT::i32, dl, Ld->getChain(), NewPtr,
4500                           Ld->getPointerInfo().getWithOffset(4), NewAlign,
4501                           Ld->getMemOperand()->getFlags());
4502     return;
4503   }
4504 
4505   llvm_unreachable("Unknown VFP cmp argument!");
4506 }
4507 
4508 /// OptimizeVFPBrcond - With -enable-unsafe-fp-math, it's legal to optimize some
4509 /// f32 and even f64 comparisons to integer ones.
4510 SDValue
4511 ARMTargetLowering::OptimizeVFPBrcond(SDValue Op, SelectionDAG &DAG) const {
4512   SDValue Chain = Op.getOperand(0);
4513   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4514   SDValue LHS = Op.getOperand(2);
4515   SDValue RHS = Op.getOperand(3);
4516   SDValue Dest = Op.getOperand(4);
4517   SDLoc dl(Op);
4518 
4519   bool LHSSeenZero = false;
4520   bool LHSOk = canChangeToInt(LHS, LHSSeenZero, Subtarget);
4521   bool RHSSeenZero = false;
4522   bool RHSOk = canChangeToInt(RHS, RHSSeenZero, Subtarget);
4523   if (LHSOk && RHSOk && (LHSSeenZero || RHSSeenZero)) {
4524     // If unsafe fp math optimization is enabled and there are no other uses of
4525     // the CMP operands, and the condition code is EQ or NE, we can optimize it
4526     // to an integer comparison.
4527     if (CC == ISD::SETOEQ)
4528       CC = ISD::SETEQ;
4529     else if (CC == ISD::SETUNE)
4530       CC = ISD::SETNE;
4531 
4532     SDValue Mask = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4533     SDValue ARMcc;
4534     if (LHS.getValueType() == MVT::f32) {
4535       LHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4536                         bitcastf32Toi32(LHS, DAG), Mask);
4537       RHS = DAG.getNode(ISD::AND, dl, MVT::i32,
4538                         bitcastf32Toi32(RHS, DAG), Mask);
4539       SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4540       SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4541       return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4542                          Chain, Dest, ARMcc, CCR, Cmp);
4543     }
4544 
4545     SDValue LHS1, LHS2;
4546     SDValue RHS1, RHS2;
4547     expandf64Toi32(LHS, DAG, LHS1, LHS2);
4548     expandf64Toi32(RHS, DAG, RHS1, RHS2);
4549     LHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, LHS2, Mask);
4550     RHS2 = DAG.getNode(ISD::AND, dl, MVT::i32, RHS2, Mask);
4551     ARMCC::CondCodes CondCode = IntCCToARMCC(CC);
4552     ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4553     SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4554     SDValue Ops[] = { Chain, ARMcc, LHS1, LHS2, RHS1, RHS2, Dest };
4555     return DAG.getNode(ARMISD::BCC_i64, dl, VTList, Ops);
4556   }
4557 
4558   return SDValue();
4559 }
4560 
4561 SDValue ARMTargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
4562   SDValue Chain = Op.getOperand(0);
4563   SDValue Cond = Op.getOperand(1);
4564   SDValue Dest = Op.getOperand(2);
4565   SDLoc dl(Op);
4566 
4567   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4568   // instruction.
4569   unsigned Opc = Cond.getOpcode();
4570   if (Cond.getResNo() == 1 &&
4571       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4572        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO)) {
4573     // Only lower legal XALUO ops.
4574     if (!DAG.getTargetLoweringInfo().isTypeLegal(Cond->getValueType(0)))
4575       return SDValue();
4576 
4577     // The actual operation with overflow check.
4578     SDValue Value, OverflowCmp;
4579     SDValue ARMcc;
4580     std::tie(Value, OverflowCmp) = getARMXALUOOp(Cond, DAG, ARMcc);
4581 
4582     // Reverse the condition code.
4583     ARMCC::CondCodes CondCode =
4584         (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4585     CondCode = ARMCC::getOppositeCondition(CondCode);
4586     ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4587     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4588 
4589     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4590                        OverflowCmp);
4591   }
4592 
4593   return SDValue();
4594 }
4595 
4596 SDValue ARMTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
4597   SDValue Chain = Op.getOperand(0);
4598   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
4599   SDValue LHS = Op.getOperand(2);
4600   SDValue RHS = Op.getOperand(3);
4601   SDValue Dest = Op.getOperand(4);
4602   SDLoc dl(Op);
4603 
4604   if (Subtarget->isFPOnlySP() && LHS.getValueType() == MVT::f64) {
4605     DAG.getTargetLoweringInfo().softenSetCCOperands(DAG, MVT::f64, LHS, RHS, CC,
4606                                                     dl);
4607 
4608     // If softenSetCCOperands only returned one value, we should compare it to
4609     // zero.
4610     if (!RHS.getNode()) {
4611       RHS = DAG.getConstant(0, dl, LHS.getValueType());
4612       CC = ISD::SETNE;
4613     }
4614   }
4615 
4616   // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
4617   // instruction.
4618   unsigned Opc = LHS.getOpcode();
4619   if (LHS.getResNo() == 1 && (isOneConstant(RHS) || isNullConstant(RHS)) &&
4620       (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
4621        Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO) &&
4622       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
4623     // Only lower legal XALUO ops.
4624     if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
4625       return SDValue();
4626 
4627     // The actual operation with overflow check.
4628     SDValue Value, OverflowCmp;
4629     SDValue ARMcc;
4630     std::tie(Value, OverflowCmp) = getARMXALUOOp(LHS.getValue(0), DAG, ARMcc);
4631 
4632     if ((CC == ISD::SETNE) != isOneConstant(RHS)) {
4633       // Reverse the condition code.
4634       ARMCC::CondCodes CondCode =
4635           (ARMCC::CondCodes)cast<const ConstantSDNode>(ARMcc)->getZExtValue();
4636       CondCode = ARMCC::getOppositeCondition(CondCode);
4637       ARMcc = DAG.getConstant(CondCode, SDLoc(ARMcc), MVT::i32);
4638     }
4639     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4640 
4641     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other, Chain, Dest, ARMcc, CCR,
4642                        OverflowCmp);
4643   }
4644 
4645   if (LHS.getValueType() == MVT::i32) {
4646     SDValue ARMcc;
4647     SDValue Cmp = getARMCmp(LHS, RHS, CC, ARMcc, DAG, dl);
4648     SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4649     return DAG.getNode(ARMISD::BRCOND, dl, MVT::Other,
4650                        Chain, Dest, ARMcc, CCR, Cmp);
4651   }
4652 
4653   assert(LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
4654 
4655   if (getTargetMachine().Options.UnsafeFPMath &&
4656       (CC == ISD::SETEQ || CC == ISD::SETOEQ ||
4657        CC == ISD::SETNE || CC == ISD::SETUNE)) {
4658     if (SDValue Result = OptimizeVFPBrcond(Op, DAG))
4659       return Result;
4660   }
4661 
4662   ARMCC::CondCodes CondCode, CondCode2;
4663   bool InvalidOnQNaN;
4664   FPCCToARMCC(CC, CondCode, CondCode2, InvalidOnQNaN);
4665 
4666   SDValue ARMcc = DAG.getConstant(CondCode, dl, MVT::i32);
4667   SDValue Cmp = getVFPCmp(LHS, RHS, DAG, dl, InvalidOnQNaN);
4668   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
4669   SDVTList VTList = DAG.getVTList(MVT::Other, MVT::Glue);
4670   SDValue Ops[] = { Chain, Dest, ARMcc, CCR, Cmp };
4671   SDValue Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4672   if (CondCode2 != ARMCC::AL) {
4673     ARMcc = DAG.getConstant(CondCode2, dl, MVT::i32);
4674     SDValue Ops[] = { Res, Dest, ARMcc, CCR, Res.getValue(1) };
4675     Res = DAG.getNode(ARMISD::BRCOND, dl, VTList, Ops);
4676   }
4677   return Res;
4678 }
4679 
4680 SDValue ARMTargetLowering::LowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
4681   SDValue Chain = Op.getOperand(0);
4682   SDValue Table = Op.getOperand(1);
4683   SDValue Index = Op.getOperand(2);
4684   SDLoc dl(Op);
4685 
4686   EVT PTy = getPointerTy(DAG.getDataLayout());
4687   JumpTableSDNode *JT = cast<JumpTableSDNode>(Table);
4688   SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PTy);
4689   Table = DAG.getNode(ARMISD::WrapperJT, dl, MVT::i32, JTI);
4690   Index = DAG.getNode(ISD::MUL, dl, PTy, Index, DAG.getConstant(4, dl, PTy));
4691   SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Index);
4692   if (Subtarget->isThumb2() || (Subtarget->hasV8MBaselineOps() && Subtarget->isThumb())) {
4693     // Thumb2 and ARMv8-M use a two-level jump. That is, it jumps into the jump table
4694     // which does another jump to the destination. This also makes it easier
4695     // to translate it to TBB / TBH later (Thumb2 only).
4696     // FIXME: This might not work if the function is extremely large.
4697     return DAG.getNode(ARMISD::BR2_JT, dl, MVT::Other, Chain,
4698                        Addr, Op.getOperand(2), JTI);
4699   }
4700   if (isPositionIndependent() || Subtarget->isROPI()) {
4701     Addr =
4702         DAG.getLoad((EVT)MVT::i32, dl, Chain, Addr,
4703                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4704     Chain = Addr.getValue(1);
4705     Addr = DAG.getNode(ISD::ADD, dl, PTy, Table, Addr);
4706     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4707   } else {
4708     Addr =
4709         DAG.getLoad(PTy, dl, Chain, Addr,
4710                     MachinePointerInfo::getJumpTable(DAG.getMachineFunction()));
4711     Chain = Addr.getValue(1);
4712     return DAG.getNode(ARMISD::BR_JT, dl, MVT::Other, Chain, Addr, JTI);
4713   }
4714 }
4715 
4716 static SDValue LowerVectorFP_TO_INT(SDValue Op, SelectionDAG &DAG) {
4717   EVT VT = Op.getValueType();
4718   SDLoc dl(Op);
4719 
4720   if (Op.getValueType().getVectorElementType() == MVT::i32) {
4721     if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::f32)
4722       return Op;
4723     return DAG.UnrollVectorOp(Op.getNode());
4724   }
4725 
4726   assert(Op.getOperand(0).getValueType() == MVT::v4f32 &&
4727          "Invalid type for custom lowering!");
4728   if (VT != MVT::v4i16)
4729     return DAG.UnrollVectorOp(Op.getNode());
4730 
4731   Op = DAG.getNode(Op.getOpcode(), dl, MVT::v4i32, Op.getOperand(0));
4732   return DAG.getNode(ISD::TRUNCATE, dl, VT, Op);
4733 }
4734 
4735 SDValue ARMTargetLowering::LowerFP_TO_INT(SDValue Op, SelectionDAG &DAG) const {
4736   EVT VT = Op.getValueType();
4737   if (VT.isVector())
4738     return LowerVectorFP_TO_INT(Op, DAG);
4739   if (Subtarget->isFPOnlySP() && Op.getOperand(0).getValueType() == MVT::f64) {
4740     RTLIB::Libcall LC;
4741     if (Op.getOpcode() == ISD::FP_TO_SINT)
4742       LC = RTLIB::getFPTOSINT(Op.getOperand(0).getValueType(),
4743                               Op.getValueType());
4744     else
4745       LC = RTLIB::getFPTOUINT(Op.getOperand(0).getValueType(),
4746                               Op.getValueType());
4747     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4748                        /*isSigned*/ false, SDLoc(Op)).first;
4749   }
4750 
4751   return Op;
4752 }
4753 
4754 static SDValue LowerVectorINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
4755   EVT VT = Op.getValueType();
4756   SDLoc dl(Op);
4757 
4758   if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i32) {
4759     if (VT.getVectorElementType() == MVT::f32)
4760       return Op;
4761     return DAG.UnrollVectorOp(Op.getNode());
4762   }
4763 
4764   assert(Op.getOperand(0).getValueType() == MVT::v4i16 &&
4765          "Invalid type for custom lowering!");
4766   if (VT != MVT::v4f32)
4767     return DAG.UnrollVectorOp(Op.getNode());
4768 
4769   unsigned CastOpc;
4770   unsigned Opc;
4771   switch (Op.getOpcode()) {
4772   default: llvm_unreachable("Invalid opcode!");
4773   case ISD::SINT_TO_FP:
4774     CastOpc = ISD::SIGN_EXTEND;
4775     Opc = ISD::SINT_TO_FP;
4776     break;
4777   case ISD::UINT_TO_FP:
4778     CastOpc = ISD::ZERO_EXTEND;
4779     Opc = ISD::UINT_TO_FP;
4780     break;
4781   }
4782 
4783   Op = DAG.getNode(CastOpc, dl, MVT::v4i32, Op.getOperand(0));
4784   return DAG.getNode(Opc, dl, VT, Op);
4785 }
4786 
4787 SDValue ARMTargetLowering::LowerINT_TO_FP(SDValue Op, SelectionDAG &DAG) const {
4788   EVT VT = Op.getValueType();
4789   if (VT.isVector())
4790     return LowerVectorINT_TO_FP(Op, DAG);
4791   if (Subtarget->isFPOnlySP() && Op.getValueType() == MVT::f64) {
4792     RTLIB::Libcall LC;
4793     if (Op.getOpcode() == ISD::SINT_TO_FP)
4794       LC = RTLIB::getSINTTOFP(Op.getOperand(0).getValueType(),
4795                               Op.getValueType());
4796     else
4797       LC = RTLIB::getUINTTOFP(Op.getOperand(0).getValueType(),
4798                               Op.getValueType());
4799     return makeLibCall(DAG, LC, Op.getValueType(), Op.getOperand(0),
4800                        /*isSigned*/ false, SDLoc(Op)).first;
4801   }
4802 
4803   return Op;
4804 }
4805 
4806 SDValue ARMTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
4807   // Implement fcopysign with a fabs and a conditional fneg.
4808   SDValue Tmp0 = Op.getOperand(0);
4809   SDValue Tmp1 = Op.getOperand(1);
4810   SDLoc dl(Op);
4811   EVT VT = Op.getValueType();
4812   EVT SrcVT = Tmp1.getValueType();
4813   bool InGPR = Tmp0.getOpcode() == ISD::BITCAST ||
4814     Tmp0.getOpcode() == ARMISD::VMOVDRR;
4815   bool UseNEON = !InGPR && Subtarget->hasNEON();
4816 
4817   if (UseNEON) {
4818     // Use VBSL to copy the sign bit.
4819     unsigned EncodedVal = ARM_AM::createNEONModImm(0x6, 0x80);
4820     SDValue Mask = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v2i32,
4821                                DAG.getTargetConstant(EncodedVal, dl, MVT::i32));
4822     EVT OpVT = (VT == MVT::f32) ? MVT::v2i32 : MVT::v1i64;
4823     if (VT == MVT::f64)
4824       Mask = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4825                          DAG.getNode(ISD::BITCAST, dl, OpVT, Mask),
4826                          DAG.getConstant(32, dl, MVT::i32));
4827     else /*if (VT == MVT::f32)*/
4828       Tmp0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp0);
4829     if (SrcVT == MVT::f32) {
4830       Tmp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f32, Tmp1);
4831       if (VT == MVT::f64)
4832         Tmp1 = DAG.getNode(ARMISD::VSHL, dl, OpVT,
4833                            DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1),
4834                            DAG.getConstant(32, dl, MVT::i32));
4835     } else if (VT == MVT::f32)
4836       Tmp1 = DAG.getNode(ARMISD::VSHRu, dl, MVT::v1i64,
4837                          DAG.getNode(ISD::BITCAST, dl, MVT::v1i64, Tmp1),
4838                          DAG.getConstant(32, dl, MVT::i32));
4839     Tmp0 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp0);
4840     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OpVT, Tmp1);
4841 
4842     SDValue AllOnes = DAG.getTargetConstant(ARM_AM::createNEONModImm(0xe, 0xff),
4843                                             dl, MVT::i32);
4844     AllOnes = DAG.getNode(ARMISD::VMOVIMM, dl, MVT::v8i8, AllOnes);
4845     SDValue MaskNot = DAG.getNode(ISD::XOR, dl, OpVT, Mask,
4846                                   DAG.getNode(ISD::BITCAST, dl, OpVT, AllOnes));
4847 
4848     SDValue Res = DAG.getNode(ISD::OR, dl, OpVT,
4849                               DAG.getNode(ISD::AND, dl, OpVT, Tmp1, Mask),
4850                               DAG.getNode(ISD::AND, dl, OpVT, Tmp0, MaskNot));
4851     if (VT == MVT::f32) {
4852       Res = DAG.getNode(ISD::BITCAST, dl, MVT::v2f32, Res);
4853       Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, Res,
4854                         DAG.getConstant(0, dl, MVT::i32));
4855     } else {
4856       Res = DAG.getNode(ISD::BITCAST, dl, MVT::f64, Res);
4857     }
4858 
4859     return Res;
4860   }
4861 
4862   // Bitcast operand 1 to i32.
4863   if (SrcVT == MVT::f64)
4864     Tmp1 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4865                        Tmp1).getValue(1);
4866   Tmp1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp1);
4867 
4868   // Or in the signbit with integer operations.
4869   SDValue Mask1 = DAG.getConstant(0x80000000, dl, MVT::i32);
4870   SDValue Mask2 = DAG.getConstant(0x7fffffff, dl, MVT::i32);
4871   Tmp1 = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp1, Mask1);
4872   if (VT == MVT::f32) {
4873     Tmp0 = DAG.getNode(ISD::AND, dl, MVT::i32,
4874                        DAG.getNode(ISD::BITCAST, dl, MVT::i32, Tmp0), Mask2);
4875     return DAG.getNode(ISD::BITCAST, dl, MVT::f32,
4876                        DAG.getNode(ISD::OR, dl, MVT::i32, Tmp0, Tmp1));
4877   }
4878 
4879   // f64: Or the high part with signbit and then combine two parts.
4880   Tmp0 = DAG.getNode(ARMISD::VMOVRRD, dl, DAG.getVTList(MVT::i32, MVT::i32),
4881                      Tmp0);
4882   SDValue Lo = Tmp0.getValue(0);
4883   SDValue Hi = DAG.getNode(ISD::AND, dl, MVT::i32, Tmp0.getValue(1), Mask2);
4884   Hi = DAG.getNode(ISD::OR, dl, MVT::i32, Hi, Tmp1);
4885   return DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi);
4886 }
4887 
4888 SDValue ARMTargetLowering::LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) const{
4889   MachineFunction &MF = DAG.getMachineFunction();
4890   MachineFrameInfo &MFI = MF.getFrameInfo();
4891   MFI.setReturnAddressIsTaken(true);
4892 
4893   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
4894     return SDValue();
4895 
4896   EVT VT = Op.getValueType();
4897   SDLoc dl(Op);
4898   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4899   if (Depth) {
4900     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
4901     SDValue Offset = DAG.getConstant(4, dl, MVT::i32);
4902     return DAG.getLoad(VT, dl, DAG.getEntryNode(),
4903                        DAG.getNode(ISD::ADD, dl, VT, FrameAddr, Offset),
4904                        MachinePointerInfo());
4905   }
4906 
4907   // Return LR, which contains the return address. Mark it an implicit live-in.
4908   unsigned Reg = MF.addLiveIn(ARM::LR, getRegClassFor(MVT::i32));
4909   return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
4910 }
4911 
4912 SDValue ARMTargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
4913   const ARMBaseRegisterInfo &ARI =
4914     *static_cast<const ARMBaseRegisterInfo*>(RegInfo);
4915   MachineFunction &MF = DAG.getMachineFunction();
4916   MachineFrameInfo &MFI = MF.getFrameInfo();
4917   MFI.setFrameAddressIsTaken(true);
4918 
4919   EVT VT = Op.getValueType();
4920   SDLoc dl(Op);  // FIXME probably not meaningful
4921   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4922   unsigned FrameReg = ARI.getFrameRegister(MF);
4923   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
4924   while (Depth--)
4925     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
4926                             MachinePointerInfo());
4927   return FrameAddr;
4928 }
4929 
4930 // FIXME? Maybe this could be a TableGen attribute on some registers and
4931 // this table could be generated automatically from RegInfo.
4932 unsigned ARMTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4933                                               SelectionDAG &DAG) const {
4934   unsigned Reg = StringSwitch<unsigned>(RegName)
4935                        .Case("sp", ARM::SP)
4936                        .Default(0);
4937   if (Reg)
4938     return Reg;
4939   report_fatal_error(Twine("Invalid register name \""
4940                               + StringRef(RegName)  + "\"."));
4941 }
4942 
4943 // Result is 64 bit value so split into two 32 bit values and return as a
4944 // pair of values.
4945 static void ExpandREAD_REGISTER(SDNode *N, SmallVectorImpl<SDValue> &Results,
4946                                 SelectionDAG &DAG) {
4947   SDLoc DL(N);
4948 
4949   // This function is only supposed to be called for i64 type destination.
4950   assert(N->getValueType(0) == MVT::i64
4951           && "ExpandREAD_REGISTER called for non-i64 type result.");
4952 
4953   SDValue Read = DAG.getNode(ISD::READ_REGISTER, DL,
4954                              DAG.getVTList(MVT::i32, MVT::i32, MVT::Other),
4955                              N->getOperand(0),
4956                              N->getOperand(1));
4957 
4958   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Read.getValue(0),
4959                     Read.getValue(1)));
4960   Results.push_back(Read.getOperand(0));
4961 }
4962 
4963 /// \p BC is a bitcast that is about to be turned into a VMOVDRR.
4964 /// When \p DstVT, the destination type of \p BC, is on the vector
4965 /// register bank and the source of bitcast, \p Op, operates on the same bank,
4966 /// it might be possible to combine them, such that everything stays on the
4967 /// vector register bank.
4968 /// \p return The node that would replace \p BT, if the combine
4969 /// is possible.
4970 static SDValue CombineVMOVDRRCandidateWithVecOp(const SDNode *BC,
4971                                                 SelectionDAG &DAG) {
4972   SDValue Op = BC->getOperand(0);
4973   EVT DstVT = BC->getValueType(0);
4974 
4975   // The only vector instruction that can produce a scalar (remember,
4976   // since the bitcast was about to be turned into VMOVDRR, the source
4977   // type is i64) from a vector is EXTRACT_VECTOR_ELT.
4978   // Moreover, we can do this combine only if there is one use.
4979   // Finally, if the destination type is not a vector, there is not
4980   // much point on forcing everything on the vector bank.
4981   if (!DstVT.isVector() || Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4982       !Op.hasOneUse())
4983     return SDValue();
4984 
4985   // If the index is not constant, we will introduce an additional
4986   // multiply that will stick.
4987   // Give up in that case.
4988   ConstantSDNode *Index = dyn_cast<ConstantSDNode>(Op.getOperand(1));
4989   if (!Index)
4990     return SDValue();
4991   unsigned DstNumElt = DstVT.getVectorNumElements();
4992 
4993   // Compute the new index.
4994   const APInt &APIntIndex = Index->getAPIntValue();
4995   APInt NewIndex(APIntIndex.getBitWidth(), DstNumElt);
4996   NewIndex *= APIntIndex;
4997   // Check if the new constant index fits into i32.
4998   if (NewIndex.getBitWidth() > 32)
4999     return SDValue();
5000 
5001   // vMTy bitcast(i64 extractelt vNi64 src, i32 index) ->
5002   // vMTy extractsubvector vNxMTy (bitcast vNi64 src), i32 index*M)
5003   SDLoc dl(Op);
5004   SDValue ExtractSrc = Op.getOperand(0);
5005   EVT VecVT = EVT::getVectorVT(
5006       *DAG.getContext(), DstVT.getScalarType(),
5007       ExtractSrc.getValueType().getVectorNumElements() * DstNumElt);
5008   SDValue BitCast = DAG.getNode(ISD::BITCAST, dl, VecVT, ExtractSrc);
5009   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DstVT, BitCast,
5010                      DAG.getConstant(NewIndex.getZExtValue(), dl, MVT::i32));
5011 }
5012 
5013 /// ExpandBITCAST - If the target supports VFP, this function is called to
5014 /// expand a bit convert where either the source or destination type is i64 to
5015 /// use a VMOVDRR or VMOVRRD node.  This should not be done when the non-i64
5016 /// operand type is illegal (e.g., v2f32 for a target that doesn't support
5017 /// vectors), since the legalizer won't know what to do with that.
5018 static SDValue ExpandBITCAST(SDNode *N, SelectionDAG &DAG) {
5019   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5020   SDLoc dl(N);
5021   SDValue Op = N->getOperand(0);
5022 
5023   // This function is only supposed to be called for i64 types, either as the
5024   // source or destination of the bit convert.
5025   EVT SrcVT = Op.getValueType();
5026   EVT DstVT = N->getValueType(0);
5027   assert((SrcVT == MVT::i64 || DstVT == MVT::i64) &&
5028          "ExpandBITCAST called for non-i64 type");
5029 
5030   // Turn i64->f64 into VMOVDRR.
5031   if (SrcVT == MVT::i64 && TLI.isTypeLegal(DstVT)) {
5032     // Do not force values to GPRs (this is what VMOVDRR does for the inputs)
5033     // if we can combine the bitcast with its source.
5034     if (SDValue Val = CombineVMOVDRRCandidateWithVecOp(N, DAG))
5035       return Val;
5036 
5037     SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5038                              DAG.getConstant(0, dl, MVT::i32));
5039     SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Op,
5040                              DAG.getConstant(1, dl, MVT::i32));
5041     return DAG.getNode(ISD::BITCAST, dl, DstVT,
5042                        DAG.getNode(ARMISD::VMOVDRR, dl, MVT::f64, Lo, Hi));
5043   }
5044 
5045   // Turn f64->i64 into VMOVRRD.
5046   if (DstVT == MVT::i64 && TLI.isTypeLegal(SrcVT)) {
5047     SDValue Cvt;
5048     if (DAG.getDataLayout().isBigEndian() && SrcVT.isVector() &&
5049         SrcVT.getVectorNumElements() > 1)
5050       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5051                         DAG.getVTList(MVT::i32, MVT::i32),
5052                         DAG.getNode(ARMISD::VREV64, dl, SrcVT, Op));
5053     else
5054       Cvt = DAG.getNode(ARMISD::VMOVRRD, dl,
5055                         DAG.getVTList(MVT::i32, MVT::i32), Op);
5056     // Merge the pieces into a single i64 value.
5057     return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Cvt, Cvt.getValue(1));
5058   }
5059 
5060   return SDValue();
5061 }
5062 
5063 /// getZeroVector - Returns a vector of specified type with all zero elements.
5064 /// Zero vectors are used to represent vector negation and in those cases
5065 /// will be implemented with the NEON VNEG instruction.  However, VNEG does
5066 /// not support i64 elements, so sometimes the zero vectors will need to be
5067 /// explicitly constructed.  Regardless, use a canonical VMOV to create the
5068 /// zero vector.
5069 static SDValue getZeroVector(EVT VT, SelectionDAG &DAG, const SDLoc &dl) {
5070   assert(VT.isVector() && "Expected a vector type");
5071   // The canonical modified immediate encoding of a zero vector is....0!
5072   SDValue EncodedVal = DAG.getTargetConstant(0, dl, MVT::i32);
5073   EVT VmovVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
5074   SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, EncodedVal);
5075   return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
5076 }
5077 
5078 /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
5079 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5080 SDValue ARMTargetLowering::LowerShiftRightParts(SDValue Op,
5081                                                 SelectionDAG &DAG) const {
5082   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5083   EVT VT = Op.getValueType();
5084   unsigned VTBits = VT.getSizeInBits();
5085   SDLoc dl(Op);
5086   SDValue ShOpLo = Op.getOperand(0);
5087   SDValue ShOpHi = Op.getOperand(1);
5088   SDValue ShAmt  = Op.getOperand(2);
5089   SDValue ARMcc;
5090   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5091   unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
5092 
5093   assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
5094 
5095   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5096                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5097   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
5098   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5099                                    DAG.getConstant(VTBits, dl, MVT::i32));
5100   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
5101   SDValue LoSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5102   SDValue LoBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
5103   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5104                             ISD::SETGE, ARMcc, DAG, dl);
5105   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift, LoBigShift,
5106                            ARMcc, CCR, CmpLo);
5107 
5108   SDValue HiSmallShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
5109   SDValue HiBigShift = Opc == ISD::SRA
5110                            ? DAG.getNode(Opc, dl, VT, ShOpHi,
5111                                          DAG.getConstant(VTBits - 1, dl, VT))
5112                            : DAG.getConstant(0, dl, VT);
5113   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5114                             ISD::SETGE, ARMcc, DAG, dl);
5115   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5116                            ARMcc, CCR, CmpHi);
5117 
5118   SDValue Ops[2] = { Lo, Hi };
5119   return DAG.getMergeValues(Ops, dl);
5120 }
5121 
5122 /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
5123 /// i32 values and take a 2 x i32 value to shift plus a shift amount.
5124 SDValue ARMTargetLowering::LowerShiftLeftParts(SDValue Op,
5125                                                SelectionDAG &DAG) const {
5126   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
5127   EVT VT = Op.getValueType();
5128   unsigned VTBits = VT.getSizeInBits();
5129   SDLoc dl(Op);
5130   SDValue ShOpLo = Op.getOperand(0);
5131   SDValue ShOpHi = Op.getOperand(1);
5132   SDValue ShAmt  = Op.getOperand(2);
5133   SDValue ARMcc;
5134   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5135 
5136   assert(Op.getOpcode() == ISD::SHL_PARTS);
5137   SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32,
5138                                  DAG.getConstant(VTBits, dl, MVT::i32), ShAmt);
5139   SDValue Tmp1 = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
5140   SDValue Tmp2 = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
5141   SDValue HiSmallShift = DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
5142 
5143   SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i32, ShAmt,
5144                                    DAG.getConstant(VTBits, dl, MVT::i32));
5145   SDValue HiBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
5146   SDValue CmpHi = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5147                             ISD::SETGE, ARMcc, DAG, dl);
5148   SDValue Hi = DAG.getNode(ARMISD::CMOV, dl, VT, HiSmallShift, HiBigShift,
5149                            ARMcc, CCR, CmpHi);
5150 
5151   SDValue CmpLo = getARMCmp(ExtraShAmt, DAG.getConstant(0, dl, MVT::i32),
5152                           ISD::SETGE, ARMcc, DAG, dl);
5153   SDValue LoSmallShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
5154   SDValue Lo = DAG.getNode(ARMISD::CMOV, dl, VT, LoSmallShift,
5155                            DAG.getConstant(0, dl, VT), ARMcc, CCR, CmpLo);
5156 
5157   SDValue Ops[2] = { Lo, Hi };
5158   return DAG.getMergeValues(Ops, dl);
5159 }
5160 
5161 SDValue ARMTargetLowering::LowerFLT_ROUNDS_(SDValue Op,
5162                                             SelectionDAG &DAG) const {
5163   // The rounding mode is in bits 23:22 of the FPSCR.
5164   // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
5165   // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
5166   // so that the shift + and get folded into a bitfield extract.
5167   SDLoc dl(Op);
5168   SDValue Ops[] = { DAG.getEntryNode(),
5169                     DAG.getConstant(Intrinsic::arm_get_fpscr, dl, MVT::i32) };
5170 
5171   SDValue FPSCR = DAG.getNode(ISD::INTRINSIC_W_CHAIN, dl, MVT::i32, Ops);
5172   SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPSCR,
5173                                   DAG.getConstant(1U << 22, dl, MVT::i32));
5174   SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
5175                               DAG.getConstant(22, dl, MVT::i32));
5176   return DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
5177                      DAG.getConstant(3, dl, MVT::i32));
5178 }
5179 
5180 static SDValue LowerCTTZ(SDNode *N, SelectionDAG &DAG,
5181                          const ARMSubtarget *ST) {
5182   SDLoc dl(N);
5183   EVT VT = N->getValueType(0);
5184   if (VT.isVector()) {
5185     assert(ST->hasNEON());
5186 
5187     // Compute the least significant set bit: LSB = X & -X
5188     SDValue X = N->getOperand(0);
5189     SDValue NX = DAG.getNode(ISD::SUB, dl, VT, getZeroVector(VT, DAG, dl), X);
5190     SDValue LSB = DAG.getNode(ISD::AND, dl, VT, X, NX);
5191 
5192     EVT ElemTy = VT.getVectorElementType();
5193 
5194     if (ElemTy == MVT::i8) {
5195       // Compute with: cttz(x) = ctpop(lsb - 1)
5196       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5197                                 DAG.getTargetConstant(1, dl, ElemTy));
5198       SDValue Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5199       return DAG.getNode(ISD::CTPOP, dl, VT, Bits);
5200     }
5201 
5202     if ((ElemTy == MVT::i16 || ElemTy == MVT::i32) &&
5203         (N->getOpcode() == ISD::CTTZ_ZERO_UNDEF)) {
5204       // Compute with: cttz(x) = (width - 1) - ctlz(lsb), if x != 0
5205       unsigned NumBits = ElemTy.getSizeInBits();
5206       SDValue WidthMinus1 =
5207           DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5208                       DAG.getTargetConstant(NumBits - 1, dl, ElemTy));
5209       SDValue CTLZ = DAG.getNode(ISD::CTLZ, dl, VT, LSB);
5210       return DAG.getNode(ISD::SUB, dl, VT, WidthMinus1, CTLZ);
5211     }
5212 
5213     // Compute with: cttz(x) = ctpop(lsb - 1)
5214 
5215     // Since we can only compute the number of bits in a byte with vcnt.8, we
5216     // have to gather the result with pairwise addition (vpaddl) for i16, i32,
5217     // and i64.
5218 
5219     // Compute LSB - 1.
5220     SDValue Bits;
5221     if (ElemTy == MVT::i64) {
5222       // Load constant 0xffff'ffff'ffff'ffff to register.
5223       SDValue FF = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5224                                DAG.getTargetConstant(0x1eff, dl, MVT::i32));
5225       Bits = DAG.getNode(ISD::ADD, dl, VT, LSB, FF);
5226     } else {
5227       SDValue One = DAG.getNode(ARMISD::VMOVIMM, dl, VT,
5228                                 DAG.getTargetConstant(1, dl, ElemTy));
5229       Bits = DAG.getNode(ISD::SUB, dl, VT, LSB, One);
5230     }
5231 
5232     // Count #bits with vcnt.8.
5233     EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5234     SDValue BitsVT8 = DAG.getNode(ISD::BITCAST, dl, VT8Bit, Bits);
5235     SDValue Cnt8 = DAG.getNode(ISD::CTPOP, dl, VT8Bit, BitsVT8);
5236 
5237     // Gather the #bits with vpaddl (pairwise add.)
5238     EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5239     SDValue Cnt16 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT16Bit,
5240         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5241         Cnt8);
5242     if (ElemTy == MVT::i16)
5243       return Cnt16;
5244 
5245     EVT VT32Bit = VT.is64BitVector() ? MVT::v2i32 : MVT::v4i32;
5246     SDValue Cnt32 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT32Bit,
5247         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5248         Cnt16);
5249     if (ElemTy == MVT::i32)
5250       return Cnt32;
5251 
5252     assert(ElemTy == MVT::i64);
5253     SDValue Cnt64 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5254         DAG.getTargetConstant(Intrinsic::arm_neon_vpaddlu, dl, MVT::i32),
5255         Cnt32);
5256     return Cnt64;
5257   }
5258 
5259   if (!ST->hasV6T2Ops())
5260     return SDValue();
5261 
5262   SDValue rbit = DAG.getNode(ISD::BITREVERSE, dl, VT, N->getOperand(0));
5263   return DAG.getNode(ISD::CTLZ, dl, VT, rbit);
5264 }
5265 
5266 /// getCTPOP16BitCounts - Returns a v8i8/v16i8 vector containing the bit-count
5267 /// for each 16-bit element from operand, repeated.  The basic idea is to
5268 /// leverage vcnt to get the 8-bit counts, gather and add the results.
5269 ///
5270 /// Trace for v4i16:
5271 /// input    = [v0    v1    v2    v3   ] (vi 16-bit element)
5272 /// cast: N0 = [w0 w1 w2 w3 w4 w5 w6 w7] (v0 = [w0 w1], wi 8-bit element)
5273 /// vcnt: N1 = [b0 b1 b2 b3 b4 b5 b6 b7] (bi = bit-count of 8-bit element wi)
5274 /// vrev: N2 = [b1 b0 b3 b2 b5 b4 b7 b6]
5275 ///            [b0 b1 b2 b3 b4 b5 b6 b7]
5276 ///           +[b1 b0 b3 b2 b5 b4 b7 b6]
5277 /// N3=N1+N2 = [k0 k0 k1 k1 k2 k2 k3 k3] (k0 = b0+b1 = bit-count of 16-bit v0,
5278 /// vuzp:    = [k0 k1 k2 k3 k0 k1 k2 k3]  each ki is 8-bits)
5279 static SDValue getCTPOP16BitCounts(SDNode *N, SelectionDAG &DAG) {
5280   EVT VT = N->getValueType(0);
5281   SDLoc DL(N);
5282 
5283   EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
5284   SDValue N0 = DAG.getNode(ISD::BITCAST, DL, VT8Bit, N->getOperand(0));
5285   SDValue N1 = DAG.getNode(ISD::CTPOP, DL, VT8Bit, N0);
5286   SDValue N2 = DAG.getNode(ARMISD::VREV16, DL, VT8Bit, N1);
5287   SDValue N3 = DAG.getNode(ISD::ADD, DL, VT8Bit, N1, N2);
5288   return DAG.getNode(ARMISD::VUZP, DL, VT8Bit, N3, N3);
5289 }
5290 
5291 /// lowerCTPOP16BitElements - Returns a v4i16/v8i16 vector containing the
5292 /// bit-count for each 16-bit element from the operand.  We need slightly
5293 /// different sequencing for v4i16 and v8i16 to stay within NEON's available
5294 /// 64/128-bit registers.
5295 ///
5296 /// Trace for v4i16:
5297 /// input           = [v0    v1    v2    v3    ] (vi 16-bit element)
5298 /// v8i8: BitCounts = [k0 k1 k2 k3 k0 k1 k2 k3 ] (ki is the bit-count of vi)
5299 /// v8i16:Extended  = [k0    k1    k2    k3    k0    k1    k2    k3    ]
5300 /// v4i16:Extracted = [k0    k1    k2    k3    ]
5301 static SDValue lowerCTPOP16BitElements(SDNode *N, SelectionDAG &DAG) {
5302   EVT VT = N->getValueType(0);
5303   SDLoc DL(N);
5304 
5305   SDValue BitCounts = getCTPOP16BitCounts(N, DAG);
5306   if (VT.is64BitVector()) {
5307     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, BitCounts);
5308     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Extended,
5309                        DAG.getIntPtrConstant(0, DL));
5310   } else {
5311     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8,
5312                                     BitCounts, DAG.getIntPtrConstant(0, DL));
5313     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, Extracted);
5314   }
5315 }
5316 
5317 /// lowerCTPOP32BitElements - Returns a v2i32/v4i32 vector containing the
5318 /// bit-count for each 32-bit element from the operand.  The idea here is
5319 /// to split the vector into 16-bit elements, leverage the 16-bit count
5320 /// routine, and then combine the results.
5321 ///
5322 /// Trace for v2i32 (v4i32 similar with Extracted/Extended exchanged):
5323 /// input    = [v0    v1    ] (vi: 32-bit elements)
5324 /// Bitcast  = [w0 w1 w2 w3 ] (wi: 16-bit elements, v0 = [w0 w1])
5325 /// Counts16 = [k0 k1 k2 k3 ] (ki: 16-bit elements, bit-count of wi)
5326 /// vrev: N0 = [k1 k0 k3 k2 ]
5327 ///            [k0 k1 k2 k3 ]
5328 ///       N1 =+[k1 k0 k3 k2 ]
5329 ///            [k0 k2 k1 k3 ]
5330 ///       N2 =+[k1 k3 k0 k2 ]
5331 ///            [k0    k2    k1    k3    ]
5332 /// Extended =+[k1    k3    k0    k2    ]
5333 ///            [k0    k2    ]
5334 /// Extracted=+[k1    k3    ]
5335 ///
5336 static SDValue lowerCTPOP32BitElements(SDNode *N, SelectionDAG &DAG) {
5337   EVT VT = N->getValueType(0);
5338   SDLoc DL(N);
5339 
5340   EVT VT16Bit = VT.is64BitVector() ? MVT::v4i16 : MVT::v8i16;
5341 
5342   SDValue Bitcast = DAG.getNode(ISD::BITCAST, DL, VT16Bit, N->getOperand(0));
5343   SDValue Counts16 = lowerCTPOP16BitElements(Bitcast.getNode(), DAG);
5344   SDValue N0 = DAG.getNode(ARMISD::VREV32, DL, VT16Bit, Counts16);
5345   SDValue N1 = DAG.getNode(ISD::ADD, DL, VT16Bit, Counts16, N0);
5346   SDValue N2 = DAG.getNode(ARMISD::VUZP, DL, VT16Bit, N1, N1);
5347 
5348   if (VT.is64BitVector()) {
5349     SDValue Extended = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, N2);
5350     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i32, Extended,
5351                        DAG.getIntPtrConstant(0, DL));
5352   } else {
5353     SDValue Extracted = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, N2,
5354                                     DAG.getIntPtrConstant(0, DL));
5355     return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v4i32, Extracted);
5356   }
5357 }
5358 
5359 static SDValue LowerCTPOP(SDNode *N, SelectionDAG &DAG,
5360                           const ARMSubtarget *ST) {
5361   EVT VT = N->getValueType(0);
5362 
5363   assert(ST->hasNEON() && "Custom ctpop lowering requires NEON.");
5364   assert((VT == MVT::v2i32 || VT == MVT::v4i32 ||
5365           VT == MVT::v4i16 || VT == MVT::v8i16) &&
5366          "Unexpected type for custom ctpop lowering");
5367 
5368   if (VT.getVectorElementType() == MVT::i32)
5369     return lowerCTPOP32BitElements(N, DAG);
5370   else
5371     return lowerCTPOP16BitElements(N, DAG);
5372 }
5373 
5374 static SDValue LowerShift(SDNode *N, SelectionDAG &DAG,
5375                           const ARMSubtarget *ST) {
5376   EVT VT = N->getValueType(0);
5377   SDLoc dl(N);
5378 
5379   if (!VT.isVector())
5380     return SDValue();
5381 
5382   // Lower vector shifts on NEON to use VSHL.
5383   assert(ST->hasNEON() && "unexpected vector shift");
5384 
5385   // Left shifts translate directly to the vshiftu intrinsic.
5386   if (N->getOpcode() == ISD::SHL)
5387     return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5388                        DAG.getConstant(Intrinsic::arm_neon_vshiftu, dl,
5389                                        MVT::i32),
5390                        N->getOperand(0), N->getOperand(1));
5391 
5392   assert((N->getOpcode() == ISD::SRA ||
5393           N->getOpcode() == ISD::SRL) && "unexpected vector shift opcode");
5394 
5395   // NEON uses the same intrinsics for both left and right shifts.  For
5396   // right shifts, the shift amounts are negative, so negate the vector of
5397   // shift amounts.
5398   EVT ShiftVT = N->getOperand(1).getValueType();
5399   SDValue NegatedCount = DAG.getNode(ISD::SUB, dl, ShiftVT,
5400                                      getZeroVector(ShiftVT, DAG, dl),
5401                                      N->getOperand(1));
5402   Intrinsic::ID vshiftInt = (N->getOpcode() == ISD::SRA ?
5403                              Intrinsic::arm_neon_vshifts :
5404                              Intrinsic::arm_neon_vshiftu);
5405   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT,
5406                      DAG.getConstant(vshiftInt, dl, MVT::i32),
5407                      N->getOperand(0), NegatedCount);
5408 }
5409 
5410 static SDValue Expand64BitShift(SDNode *N, SelectionDAG &DAG,
5411                                 const ARMSubtarget *ST) {
5412   EVT VT = N->getValueType(0);
5413   SDLoc dl(N);
5414 
5415   // We can get here for a node like i32 = ISD::SHL i32, i64
5416   if (VT != MVT::i64)
5417     return SDValue();
5418 
5419   assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
5420          "Unknown shift to lower!");
5421 
5422   // We only lower SRA, SRL of 1 here, all others use generic lowering.
5423   if (!isOneConstant(N->getOperand(1)))
5424     return SDValue();
5425 
5426   // If we are in thumb mode, we don't have RRX.
5427   if (ST->isThumb1Only()) return SDValue();
5428 
5429   // Okay, we have a 64-bit SRA or SRL of 1.  Lower this to an RRX expr.
5430   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5431                            DAG.getConstant(0, dl, MVT::i32));
5432   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, N->getOperand(0),
5433                            DAG.getConstant(1, dl, MVT::i32));
5434 
5435   // First, build a SRA_FLAG/SRL_FLAG op, which shifts the top part by one and
5436   // captures the result into a carry flag.
5437   unsigned Opc = N->getOpcode() == ISD::SRL ? ARMISD::SRL_FLAG:ARMISD::SRA_FLAG;
5438   Hi = DAG.getNode(Opc, dl, DAG.getVTList(MVT::i32, MVT::Glue), Hi);
5439 
5440   // The low part is an ARMISD::RRX operand, which shifts the carry in.
5441   Lo = DAG.getNode(ARMISD::RRX, dl, MVT::i32, Lo, Hi.getValue(1));
5442 
5443   // Merge the pieces into a single i64 value.
5444  return DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, Lo, Hi);
5445 }
5446 
5447 static SDValue LowerVSETCC(SDValue Op, SelectionDAG &DAG) {
5448   SDValue TmpOp0, TmpOp1;
5449   bool Invert = false;
5450   bool Swap = false;
5451   unsigned Opc = 0;
5452 
5453   SDValue Op0 = Op.getOperand(0);
5454   SDValue Op1 = Op.getOperand(1);
5455   SDValue CC = Op.getOperand(2);
5456   EVT CmpVT = Op0.getValueType().changeVectorElementTypeToInteger();
5457   EVT VT = Op.getValueType();
5458   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
5459   SDLoc dl(Op);
5460 
5461   if (Op0.getValueType().getVectorElementType() == MVT::i64 &&
5462       (SetCCOpcode == ISD::SETEQ || SetCCOpcode == ISD::SETNE)) {
5463     // Special-case integer 64-bit equality comparisons. They aren't legal,
5464     // but they can be lowered with a few vector instructions.
5465     unsigned CmpElements = CmpVT.getVectorNumElements() * 2;
5466     EVT SplitVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, CmpElements);
5467     SDValue CastOp0 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op0);
5468     SDValue CastOp1 = DAG.getNode(ISD::BITCAST, dl, SplitVT, Op1);
5469     SDValue Cmp = DAG.getNode(ISD::SETCC, dl, SplitVT, CastOp0, CastOp1,
5470                               DAG.getCondCode(ISD::SETEQ));
5471     SDValue Reversed = DAG.getNode(ARMISD::VREV64, dl, SplitVT, Cmp);
5472     SDValue Merged = DAG.getNode(ISD::AND, dl, SplitVT, Cmp, Reversed);
5473     Merged = DAG.getNode(ISD::BITCAST, dl, CmpVT, Merged);
5474     if (SetCCOpcode == ISD::SETNE)
5475       Merged = DAG.getNOT(dl, Merged, CmpVT);
5476     Merged = DAG.getSExtOrTrunc(Merged, dl, VT);
5477     return Merged;
5478   }
5479 
5480   if (CmpVT.getVectorElementType() == MVT::i64)
5481     // 64-bit comparisons are not legal in general.
5482     return SDValue();
5483 
5484   if (Op1.getValueType().isFloatingPoint()) {
5485     switch (SetCCOpcode) {
5486     default: llvm_unreachable("Illegal FP comparison");
5487     case ISD::SETUNE:
5488     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5489     case ISD::SETOEQ:
5490     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5491     case ISD::SETOLT:
5492     case ISD::SETLT: Swap = true; LLVM_FALLTHROUGH;
5493     case ISD::SETOGT:
5494     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5495     case ISD::SETOLE:
5496     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5497     case ISD::SETOGE:
5498     case ISD::SETGE: Opc = ARMISD::VCGE; break;
5499     case ISD::SETUGE: Swap = true; LLVM_FALLTHROUGH;
5500     case ISD::SETULE: Invert = true; Opc = ARMISD::VCGT; break;
5501     case ISD::SETUGT: Swap = true; LLVM_FALLTHROUGH;
5502     case ISD::SETULT: Invert = true; Opc = ARMISD::VCGE; break;
5503     case ISD::SETUEQ: Invert = true; LLVM_FALLTHROUGH;
5504     case ISD::SETONE:
5505       // Expand this to (OLT | OGT).
5506       TmpOp0 = Op0;
5507       TmpOp1 = Op1;
5508       Opc = ISD::OR;
5509       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5510       Op1 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp0, TmpOp1);
5511       break;
5512     case ISD::SETUO:
5513       Invert = true;
5514       LLVM_FALLTHROUGH;
5515     case ISD::SETO:
5516       // Expand this to (OLT | OGE).
5517       TmpOp0 = Op0;
5518       TmpOp1 = Op1;
5519       Opc = ISD::OR;
5520       Op0 = DAG.getNode(ARMISD::VCGT, dl, CmpVT, TmpOp1, TmpOp0);
5521       Op1 = DAG.getNode(ARMISD::VCGE, dl, CmpVT, TmpOp0, TmpOp1);
5522       break;
5523     }
5524   } else {
5525     // Integer comparisons.
5526     switch (SetCCOpcode) {
5527     default: llvm_unreachable("Illegal integer comparison");
5528     case ISD::SETNE:  Invert = true; LLVM_FALLTHROUGH;
5529     case ISD::SETEQ:  Opc = ARMISD::VCEQ; break;
5530     case ISD::SETLT:  Swap = true; LLVM_FALLTHROUGH;
5531     case ISD::SETGT:  Opc = ARMISD::VCGT; break;
5532     case ISD::SETLE:  Swap = true; LLVM_FALLTHROUGH;
5533     case ISD::SETGE:  Opc = ARMISD::VCGE; break;
5534     case ISD::SETULT: Swap = true; LLVM_FALLTHROUGH;
5535     case ISD::SETUGT: Opc = ARMISD::VCGTU; break;
5536     case ISD::SETULE: Swap = true; LLVM_FALLTHROUGH;
5537     case ISD::SETUGE: Opc = ARMISD::VCGEU; break;
5538     }
5539 
5540     // Detect VTST (Vector Test Bits) = icmp ne (and (op0, op1), zero).
5541     if (Opc == ARMISD::VCEQ) {
5542       SDValue AndOp;
5543       if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5544         AndOp = Op0;
5545       else if (ISD::isBuildVectorAllZeros(Op0.getNode()))
5546         AndOp = Op1;
5547 
5548       // Ignore bitconvert.
5549       if (AndOp.getNode() && AndOp.getOpcode() == ISD::BITCAST)
5550         AndOp = AndOp.getOperand(0);
5551 
5552       if (AndOp.getNode() && AndOp.getOpcode() == ISD::AND) {
5553         Opc = ARMISD::VTST;
5554         Op0 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(0));
5555         Op1 = DAG.getNode(ISD::BITCAST, dl, CmpVT, AndOp.getOperand(1));
5556         Invert = !Invert;
5557       }
5558     }
5559   }
5560 
5561   if (Swap)
5562     std::swap(Op0, Op1);
5563 
5564   // If one of the operands is a constant vector zero, attempt to fold the
5565   // comparison to a specialized compare-against-zero form.
5566   SDValue SingleOp;
5567   if (ISD::isBuildVectorAllZeros(Op1.getNode()))
5568     SingleOp = Op0;
5569   else if (ISD::isBuildVectorAllZeros(Op0.getNode())) {
5570     if (Opc == ARMISD::VCGE)
5571       Opc = ARMISD::VCLEZ;
5572     else if (Opc == ARMISD::VCGT)
5573       Opc = ARMISD::VCLTZ;
5574     SingleOp = Op1;
5575   }
5576 
5577   SDValue Result;
5578   if (SingleOp.getNode()) {
5579     switch (Opc) {
5580     case ARMISD::VCEQ:
5581       Result = DAG.getNode(ARMISD::VCEQZ, dl, CmpVT, SingleOp); break;
5582     case ARMISD::VCGE:
5583       Result = DAG.getNode(ARMISD::VCGEZ, dl, CmpVT, SingleOp); break;
5584     case ARMISD::VCLEZ:
5585       Result = DAG.getNode(ARMISD::VCLEZ, dl, CmpVT, SingleOp); break;
5586     case ARMISD::VCGT:
5587       Result = DAG.getNode(ARMISD::VCGTZ, dl, CmpVT, SingleOp); break;
5588     case ARMISD::VCLTZ:
5589       Result = DAG.getNode(ARMISD::VCLTZ, dl, CmpVT, SingleOp); break;
5590     default:
5591       Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5592     }
5593   } else {
5594      Result = DAG.getNode(Opc, dl, CmpVT, Op0, Op1);
5595   }
5596 
5597   Result = DAG.getSExtOrTrunc(Result, dl, VT);
5598 
5599   if (Invert)
5600     Result = DAG.getNOT(dl, Result, VT);
5601 
5602   return Result;
5603 }
5604 
5605 static SDValue LowerSETCCE(SDValue Op, SelectionDAG &DAG) {
5606   SDValue LHS = Op.getOperand(0);
5607   SDValue RHS = Op.getOperand(1);
5608   SDValue Carry = Op.getOperand(2);
5609   SDValue Cond = Op.getOperand(3);
5610   SDLoc DL(Op);
5611 
5612   assert(LHS.getSimpleValueType().isInteger() && "SETCCE is integer only.");
5613 
5614   assert(Carry.getOpcode() != ISD::CARRY_FALSE);
5615   SDVTList VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
5616   SDValue Cmp = DAG.getNode(ARMISD::SUBE, DL, VTs, LHS, RHS, Carry);
5617 
5618   SDValue FVal = DAG.getConstant(0, DL, MVT::i32);
5619   SDValue TVal = DAG.getConstant(1, DL, MVT::i32);
5620   SDValue ARMcc = DAG.getConstant(
5621       IntCCToARMCC(cast<CondCodeSDNode>(Cond)->get()), DL, MVT::i32);
5622   SDValue CCR = DAG.getRegister(ARM::CPSR, MVT::i32);
5623   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), DL, ARM::CPSR,
5624                                    Cmp.getValue(1), SDValue());
5625   return DAG.getNode(ARMISD::CMOV, DL, Op.getValueType(), FVal, TVal, ARMcc,
5626                      CCR, Chain.getValue(1));
5627 }
5628 
5629 /// isNEONModifiedImm - Check if the specified splat value corresponds to a
5630 /// valid vector constant for a NEON instruction with a "modified immediate"
5631 /// operand (e.g., VMOV).  If so, return the encoded value.
5632 static SDValue isNEONModifiedImm(uint64_t SplatBits, uint64_t SplatUndef,
5633                                  unsigned SplatBitSize, SelectionDAG &DAG,
5634                                  const SDLoc &dl, EVT &VT, bool is128Bits,
5635                                  NEONModImmType type) {
5636   unsigned OpCmode, Imm;
5637 
5638   // SplatBitSize is set to the smallest size that splats the vector, so a
5639   // zero vector will always have SplatBitSize == 8.  However, NEON modified
5640   // immediate instructions others than VMOV do not support the 8-bit encoding
5641   // of a zero vector, and the default encoding of zero is supposed to be the
5642   // 32-bit version.
5643   if (SplatBits == 0)
5644     SplatBitSize = 32;
5645 
5646   switch (SplatBitSize) {
5647   case 8:
5648     if (type != VMOVModImm)
5649       return SDValue();
5650     // Any 1-byte value is OK.  Op=0, Cmode=1110.
5651     assert((SplatBits & ~0xff) == 0 && "one byte splat value is too big");
5652     OpCmode = 0xe;
5653     Imm = SplatBits;
5654     VT = is128Bits ? MVT::v16i8 : MVT::v8i8;
5655     break;
5656 
5657   case 16:
5658     // NEON's 16-bit VMOV supports splat values where only one byte is nonzero.
5659     VT = is128Bits ? MVT::v8i16 : MVT::v4i16;
5660     if ((SplatBits & ~0xff) == 0) {
5661       // Value = 0x00nn: Op=x, Cmode=100x.
5662       OpCmode = 0x8;
5663       Imm = SplatBits;
5664       break;
5665     }
5666     if ((SplatBits & ~0xff00) == 0) {
5667       // Value = 0xnn00: Op=x, Cmode=101x.
5668       OpCmode = 0xa;
5669       Imm = SplatBits >> 8;
5670       break;
5671     }
5672     return SDValue();
5673 
5674   case 32:
5675     // NEON's 32-bit VMOV supports splat values where:
5676     // * only one byte is nonzero, or
5677     // * the least significant byte is 0xff and the second byte is nonzero, or
5678     // * the least significant 2 bytes are 0xff and the third is nonzero.
5679     VT = is128Bits ? MVT::v4i32 : MVT::v2i32;
5680     if ((SplatBits & ~0xff) == 0) {
5681       // Value = 0x000000nn: Op=x, Cmode=000x.
5682       OpCmode = 0;
5683       Imm = SplatBits;
5684       break;
5685     }
5686     if ((SplatBits & ~0xff00) == 0) {
5687       // Value = 0x0000nn00: Op=x, Cmode=001x.
5688       OpCmode = 0x2;
5689       Imm = SplatBits >> 8;
5690       break;
5691     }
5692     if ((SplatBits & ~0xff0000) == 0) {
5693       // Value = 0x00nn0000: Op=x, Cmode=010x.
5694       OpCmode = 0x4;
5695       Imm = SplatBits >> 16;
5696       break;
5697     }
5698     if ((SplatBits & ~0xff000000) == 0) {
5699       // Value = 0xnn000000: Op=x, Cmode=011x.
5700       OpCmode = 0x6;
5701       Imm = SplatBits >> 24;
5702       break;
5703     }
5704 
5705     // cmode == 0b1100 and cmode == 0b1101 are not supported for VORR or VBIC
5706     if (type == OtherModImm) return SDValue();
5707 
5708     if ((SplatBits & ~0xffff) == 0 &&
5709         ((SplatBits | SplatUndef) & 0xff) == 0xff) {
5710       // Value = 0x0000nnff: Op=x, Cmode=1100.
5711       OpCmode = 0xc;
5712       Imm = SplatBits >> 8;
5713       break;
5714     }
5715 
5716     if ((SplatBits & ~0xffffff) == 0 &&
5717         ((SplatBits | SplatUndef) & 0xffff) == 0xffff) {
5718       // Value = 0x00nnffff: Op=x, Cmode=1101.
5719       OpCmode = 0xd;
5720       Imm = SplatBits >> 16;
5721       break;
5722     }
5723 
5724     // Note: there are a few 32-bit splat values (specifically: 00ffff00,
5725     // ff000000, ff0000ff, and ffff00ff) that are valid for VMOV.I64 but not
5726     // VMOV.I32.  A (very) minor optimization would be to replicate the value
5727     // and fall through here to test for a valid 64-bit splat.  But, then the
5728     // caller would also need to check and handle the change in size.
5729     return SDValue();
5730 
5731   case 64: {
5732     if (type != VMOVModImm)
5733       return SDValue();
5734     // NEON has a 64-bit VMOV splat where each byte is either 0 or 0xff.
5735     uint64_t BitMask = 0xff;
5736     uint64_t Val = 0;
5737     unsigned ImmMask = 1;
5738     Imm = 0;
5739     for (int ByteNum = 0; ByteNum < 8; ++ByteNum) {
5740       if (((SplatBits | SplatUndef) & BitMask) == BitMask) {
5741         Val |= BitMask;
5742         Imm |= ImmMask;
5743       } else if ((SplatBits & BitMask) != 0) {
5744         return SDValue();
5745       }
5746       BitMask <<= 8;
5747       ImmMask <<= 1;
5748     }
5749 
5750     if (DAG.getDataLayout().isBigEndian())
5751       // swap higher and lower 32 bit word
5752       Imm = ((Imm & 0xf) << 4) | ((Imm & 0xf0) >> 4);
5753 
5754     // Op=1, Cmode=1110.
5755     OpCmode = 0x1e;
5756     VT = is128Bits ? MVT::v2i64 : MVT::v1i64;
5757     break;
5758   }
5759 
5760   default:
5761     llvm_unreachable("unexpected size for isNEONModifiedImm");
5762   }
5763 
5764   unsigned EncodedVal = ARM_AM::createNEONModImm(OpCmode, Imm);
5765   return DAG.getTargetConstant(EncodedVal, dl, MVT::i32);
5766 }
5767 
5768 SDValue ARMTargetLowering::LowerConstantFP(SDValue Op, SelectionDAG &DAG,
5769                                            const ARMSubtarget *ST) const {
5770   bool IsDouble = Op.getValueType() == MVT::f64;
5771   ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Op);
5772   const APFloat &FPVal = CFP->getValueAPF();
5773 
5774   // Prevent floating-point constants from using literal loads
5775   // when execute-only is enabled.
5776   if (ST->genExecuteOnly()) {
5777     APInt INTVal = FPVal.bitcastToAPInt();
5778     SDLoc DL(CFP);
5779     if (IsDouble) {
5780       SDValue Lo = DAG.getConstant(INTVal.trunc(32), DL, MVT::i32);
5781       SDValue Hi = DAG.getConstant(INTVal.lshr(32).trunc(32), DL, MVT::i32);
5782       if (!ST->isLittle())
5783         std::swap(Lo, Hi);
5784       return DAG.getNode(ARMISD::VMOVDRR, DL, MVT::f64, Lo, Hi);
5785     } else {
5786       return DAG.getConstant(INTVal, DL, MVT::i32);
5787     }
5788   }
5789 
5790   if (!ST->hasVFP3())
5791     return SDValue();
5792 
5793   // Use the default (constant pool) lowering for double constants when we have
5794   // an SP-only FPU
5795   if (IsDouble && Subtarget->isFPOnlySP())
5796     return SDValue();
5797 
5798   // Try splatting with a VMOV.f32...
5799   int ImmVal = IsDouble ? ARM_AM::getFP64Imm(FPVal) : ARM_AM::getFP32Imm(FPVal);
5800 
5801   if (ImmVal != -1) {
5802     if (IsDouble || !ST->useNEONForSinglePrecisionFP()) {
5803       // We have code in place to select a valid ConstantFP already, no need to
5804       // do any mangling.
5805       return Op;
5806     }
5807 
5808     // It's a float and we are trying to use NEON operations where
5809     // possible. Lower it to a splat followed by an extract.
5810     SDLoc DL(Op);
5811     SDValue NewVal = DAG.getTargetConstant(ImmVal, DL, MVT::i32);
5812     SDValue VecConstant = DAG.getNode(ARMISD::VMOVFPIMM, DL, MVT::v2f32,
5813                                       NewVal);
5814     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecConstant,
5815                        DAG.getConstant(0, DL, MVT::i32));
5816   }
5817 
5818   // The rest of our options are NEON only, make sure that's allowed before
5819   // proceeding..
5820   if (!ST->hasNEON() || (!IsDouble && !ST->useNEONForSinglePrecisionFP()))
5821     return SDValue();
5822 
5823   EVT VMovVT;
5824   uint64_t iVal = FPVal.bitcastToAPInt().getZExtValue();
5825 
5826   // It wouldn't really be worth bothering for doubles except for one very
5827   // important value, which does happen to match: 0.0. So make sure we don't do
5828   // anything stupid.
5829   if (IsDouble && (iVal & 0xffffffff) != (iVal >> 32))
5830     return SDValue();
5831 
5832   // Try a VMOV.i32 (FIXME: i8, i16, or i64 could work too).
5833   SDValue NewVal = isNEONModifiedImm(iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op),
5834                                      VMovVT, false, VMOVModImm);
5835   if (NewVal != SDValue()) {
5836     SDLoc DL(Op);
5837     SDValue VecConstant = DAG.getNode(ARMISD::VMOVIMM, DL, VMovVT,
5838                                       NewVal);
5839     if (IsDouble)
5840       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5841 
5842     // It's a float: cast and extract a vector element.
5843     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5844                                        VecConstant);
5845     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5846                        DAG.getConstant(0, DL, MVT::i32));
5847   }
5848 
5849   // Finally, try a VMVN.i32
5850   NewVal = isNEONModifiedImm(~iVal & 0xffffffffU, 0, 32, DAG, SDLoc(Op), VMovVT,
5851                              false, VMVNModImm);
5852   if (NewVal != SDValue()) {
5853     SDLoc DL(Op);
5854     SDValue VecConstant = DAG.getNode(ARMISD::VMVNIMM, DL, VMovVT, NewVal);
5855 
5856     if (IsDouble)
5857       return DAG.getNode(ISD::BITCAST, DL, MVT::f64, VecConstant);
5858 
5859     // It's a float: cast and extract a vector element.
5860     SDValue VecFConstant = DAG.getNode(ISD::BITCAST, DL, MVT::v2f32,
5861                                        VecConstant);
5862     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32, VecFConstant,
5863                        DAG.getConstant(0, DL, MVT::i32));
5864   }
5865 
5866   return SDValue();
5867 }
5868 
5869 // check if an VEXT instruction can handle the shuffle mask when the
5870 // vector sources of the shuffle are the same.
5871 static bool isSingletonVEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
5872   unsigned NumElts = VT.getVectorNumElements();
5873 
5874   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5875   if (M[0] < 0)
5876     return false;
5877 
5878   Imm = M[0];
5879 
5880   // If this is a VEXT shuffle, the immediate value is the index of the first
5881   // element.  The other shuffle indices must be the successive elements after
5882   // the first one.
5883   unsigned ExpectedElt = Imm;
5884   for (unsigned i = 1; i < NumElts; ++i) {
5885     // Increment the expected index.  If it wraps around, just follow it
5886     // back to index zero and keep going.
5887     ++ExpectedElt;
5888     if (ExpectedElt == NumElts)
5889       ExpectedElt = 0;
5890 
5891     if (M[i] < 0) continue; // ignore UNDEF indices
5892     if (ExpectedElt != static_cast<unsigned>(M[i]))
5893       return false;
5894   }
5895 
5896   return true;
5897 }
5898 
5899 static bool isVEXTMask(ArrayRef<int> M, EVT VT,
5900                        bool &ReverseVEXT, unsigned &Imm) {
5901   unsigned NumElts = VT.getVectorNumElements();
5902   ReverseVEXT = false;
5903 
5904   // Assume that the first shuffle index is not UNDEF.  Fail if it is.
5905   if (M[0] < 0)
5906     return false;
5907 
5908   Imm = M[0];
5909 
5910   // If this is a VEXT shuffle, the immediate value is the index of the first
5911   // element.  The other shuffle indices must be the successive elements after
5912   // the first one.
5913   unsigned ExpectedElt = Imm;
5914   for (unsigned i = 1; i < NumElts; ++i) {
5915     // Increment the expected index.  If it wraps around, it may still be
5916     // a VEXT but the source vectors must be swapped.
5917     ExpectedElt += 1;
5918     if (ExpectedElt == NumElts * 2) {
5919       ExpectedElt = 0;
5920       ReverseVEXT = true;
5921     }
5922 
5923     if (M[i] < 0) continue; // ignore UNDEF indices
5924     if (ExpectedElt != static_cast<unsigned>(M[i]))
5925       return false;
5926   }
5927 
5928   // Adjust the index value if the source operands will be swapped.
5929   if (ReverseVEXT)
5930     Imm -= NumElts;
5931 
5932   return true;
5933 }
5934 
5935 /// isVREVMask - Check if a vector shuffle corresponds to a VREV
5936 /// instruction with the specified blocksize.  (The order of the elements
5937 /// within each block of the vector is reversed.)
5938 static bool isVREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
5939   assert((BlockSize==16 || BlockSize==32 || BlockSize==64) &&
5940          "Only possible block sizes for VREV are: 16, 32, 64");
5941 
5942   unsigned EltSz = VT.getScalarSizeInBits();
5943   if (EltSz == 64)
5944     return false;
5945 
5946   unsigned NumElts = VT.getVectorNumElements();
5947   unsigned BlockElts = M[0] + 1;
5948   // If the first shuffle index is UNDEF, be optimistic.
5949   if (M[0] < 0)
5950     BlockElts = BlockSize / EltSz;
5951 
5952   if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
5953     return false;
5954 
5955   for (unsigned i = 0; i < NumElts; ++i) {
5956     if (M[i] < 0) continue; // ignore UNDEF indices
5957     if ((unsigned) M[i] != (i - i%BlockElts) + (BlockElts - 1 - i%BlockElts))
5958       return false;
5959   }
5960 
5961   return true;
5962 }
5963 
5964 static bool isVTBLMask(ArrayRef<int> M, EVT VT) {
5965   // We can handle <8 x i8> vector shuffles. If the index in the mask is out of
5966   // range, then 0 is placed into the resulting vector. So pretty much any mask
5967   // of 8 elements can work here.
5968   return VT == MVT::v8i8 && M.size() == 8;
5969 }
5970 
5971 static unsigned SelectPairHalf(unsigned Elements, ArrayRef<int> Mask,
5972                                unsigned Index) {
5973   if (Mask.size() == Elements * 2)
5974     return Index / Elements;
5975   return Mask[Index] == 0 ? 0 : 1;
5976 }
5977 
5978 // Checks whether the shuffle mask represents a vector transpose (VTRN) by
5979 // checking that pairs of elements in the shuffle mask represent the same index
5980 // in each vector, incrementing the expected index by 2 at each step.
5981 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 2, 6]
5982 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,c,g}
5983 //  v2={e,f,g,h}
5984 // WhichResult gives the offset for each element in the mask based on which
5985 // of the two results it belongs to.
5986 //
5987 // The transpose can be represented either as:
5988 // result1 = shufflevector v1, v2, result1_shuffle_mask
5989 // result2 = shufflevector v1, v2, result2_shuffle_mask
5990 // where v1/v2 and the shuffle masks have the same number of elements
5991 // (here WhichResult (see below) indicates which result is being checked)
5992 //
5993 // or as:
5994 // results = shufflevector v1, v2, shuffle_mask
5995 // where both results are returned in one vector and the shuffle mask has twice
5996 // as many elements as v1/v2 (here WhichResult will always be 0 if true) here we
5997 // want to check the low half and high half of the shuffle mask as if it were
5998 // the other case
5999 static bool isVTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6000   unsigned EltSz = VT.getScalarSizeInBits();
6001   if (EltSz == 64)
6002     return false;
6003 
6004   unsigned NumElts = VT.getVectorNumElements();
6005   if (M.size() != NumElts && M.size() != NumElts*2)
6006     return false;
6007 
6008   // If the mask is twice as long as the input vector then we need to check the
6009   // upper and lower parts of the mask with a matching value for WhichResult
6010   // FIXME: A mask with only even values will be rejected in case the first
6011   // element is undefined, e.g. [-1, 4, 2, 6] will be rejected, because only
6012   // M[0] is used to determine WhichResult
6013   for (unsigned i = 0; i < M.size(); i += NumElts) {
6014     WhichResult = SelectPairHalf(NumElts, M, i);
6015     for (unsigned j = 0; j < NumElts; j += 2) {
6016       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6017           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + NumElts + WhichResult))
6018         return false;
6019     }
6020   }
6021 
6022   if (M.size() == NumElts*2)
6023     WhichResult = 0;
6024 
6025   return true;
6026 }
6027 
6028 /// isVTRN_v_undef_Mask - Special case of isVTRNMask for canonical form of
6029 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6030 /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
6031 static bool isVTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6032   unsigned EltSz = VT.getScalarSizeInBits();
6033   if (EltSz == 64)
6034     return false;
6035 
6036   unsigned NumElts = VT.getVectorNumElements();
6037   if (M.size() != NumElts && M.size() != NumElts*2)
6038     return false;
6039 
6040   for (unsigned i = 0; i < M.size(); i += NumElts) {
6041     WhichResult = SelectPairHalf(NumElts, M, i);
6042     for (unsigned j = 0; j < NumElts; j += 2) {
6043       if ((M[i+j] >= 0 && (unsigned) M[i+j] != j + WhichResult) ||
6044           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != j + WhichResult))
6045         return false;
6046     }
6047   }
6048 
6049   if (M.size() == NumElts*2)
6050     WhichResult = 0;
6051 
6052   return true;
6053 }
6054 
6055 // Checks whether the shuffle mask represents a vector unzip (VUZP) by checking
6056 // that the mask elements are either all even and in steps of size 2 or all odd
6057 // and in steps of size 2.
6058 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 2, 4, 6]
6059 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,c,e,g}
6060 //  v2={e,f,g,h}
6061 // Requires similar checks to that of isVTRNMask with
6062 // respect the how results are returned.
6063 static bool isVUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6064   unsigned EltSz = VT.getScalarSizeInBits();
6065   if (EltSz == 64)
6066     return false;
6067 
6068   unsigned NumElts = VT.getVectorNumElements();
6069   if (M.size() != NumElts && M.size() != NumElts*2)
6070     return false;
6071 
6072   for (unsigned i = 0; i < M.size(); i += NumElts) {
6073     WhichResult = SelectPairHalf(NumElts, M, i);
6074     for (unsigned j = 0; j < NumElts; ++j) {
6075       if (M[i+j] >= 0 && (unsigned) M[i+j] != 2 * j + WhichResult)
6076         return false;
6077     }
6078   }
6079 
6080   if (M.size() == NumElts*2)
6081     WhichResult = 0;
6082 
6083   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6084   if (VT.is64BitVector() && EltSz == 32)
6085     return false;
6086 
6087   return true;
6088 }
6089 
6090 /// isVUZP_v_undef_Mask - Special case of isVUZPMask for canonical form of
6091 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6092 /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
6093 static bool isVUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6094   unsigned EltSz = VT.getScalarSizeInBits();
6095   if (EltSz == 64)
6096     return false;
6097 
6098   unsigned NumElts = VT.getVectorNumElements();
6099   if (M.size() != NumElts && M.size() != NumElts*2)
6100     return false;
6101 
6102   unsigned Half = NumElts / 2;
6103   for (unsigned i = 0; i < M.size(); i += NumElts) {
6104     WhichResult = SelectPairHalf(NumElts, M, i);
6105     for (unsigned j = 0; j < NumElts; j += Half) {
6106       unsigned Idx = WhichResult;
6107       for (unsigned k = 0; k < Half; ++k) {
6108         int MIdx = M[i + j + k];
6109         if (MIdx >= 0 && (unsigned) MIdx != Idx)
6110           return false;
6111         Idx += 2;
6112       }
6113     }
6114   }
6115 
6116   if (M.size() == NumElts*2)
6117     WhichResult = 0;
6118 
6119   // VUZP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6120   if (VT.is64BitVector() && EltSz == 32)
6121     return false;
6122 
6123   return true;
6124 }
6125 
6126 // Checks whether the shuffle mask represents a vector zip (VZIP) by checking
6127 // that pairs of elements of the shufflemask represent the same index in each
6128 // vector incrementing sequentially through the vectors.
6129 // e.g. For v1,v2 of type v4i32 a valid shuffle mask is: [0, 4, 1, 5]
6130 //  v1={a,b,c,d} => x=shufflevector v1, v2 shufflemask => x={a,e,b,f}
6131 //  v2={e,f,g,h}
6132 // Requires similar checks to that of isVTRNMask with respect the how results
6133 // are returned.
6134 static bool isVZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
6135   unsigned EltSz = VT.getScalarSizeInBits();
6136   if (EltSz == 64)
6137     return false;
6138 
6139   unsigned NumElts = VT.getVectorNumElements();
6140   if (M.size() != NumElts && M.size() != NumElts*2)
6141     return false;
6142 
6143   for (unsigned i = 0; i < M.size(); i += NumElts) {
6144     WhichResult = SelectPairHalf(NumElts, M, i);
6145     unsigned Idx = WhichResult * NumElts / 2;
6146     for (unsigned j = 0; j < NumElts; j += 2) {
6147       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6148           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx + NumElts))
6149         return false;
6150       Idx += 1;
6151     }
6152   }
6153 
6154   if (M.size() == NumElts*2)
6155     WhichResult = 0;
6156 
6157   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6158   if (VT.is64BitVector() && EltSz == 32)
6159     return false;
6160 
6161   return true;
6162 }
6163 
6164 /// isVZIP_v_undef_Mask - Special case of isVZIPMask for canonical form of
6165 /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
6166 /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
6167 static bool isVZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult){
6168   unsigned EltSz = VT.getScalarSizeInBits();
6169   if (EltSz == 64)
6170     return false;
6171 
6172   unsigned NumElts = VT.getVectorNumElements();
6173   if (M.size() != NumElts && M.size() != NumElts*2)
6174     return false;
6175 
6176   for (unsigned i = 0; i < M.size(); i += NumElts) {
6177     WhichResult = SelectPairHalf(NumElts, M, i);
6178     unsigned Idx = WhichResult * NumElts / 2;
6179     for (unsigned j = 0; j < NumElts; j += 2) {
6180       if ((M[i+j] >= 0 && (unsigned) M[i+j] != Idx) ||
6181           (M[i+j+1] >= 0 && (unsigned) M[i+j+1] != Idx))
6182         return false;
6183       Idx += 1;
6184     }
6185   }
6186 
6187   if (M.size() == NumElts*2)
6188     WhichResult = 0;
6189 
6190   // VZIP.32 for 64-bit vectors is a pseudo-instruction alias for VTRN.32.
6191   if (VT.is64BitVector() && EltSz == 32)
6192     return false;
6193 
6194   return true;
6195 }
6196 
6197 /// Check if \p ShuffleMask is a NEON two-result shuffle (VZIP, VUZP, VTRN),
6198 /// and return the corresponding ARMISD opcode if it is, or 0 if it isn't.
6199 static unsigned isNEONTwoResultShuffleMask(ArrayRef<int> ShuffleMask, EVT VT,
6200                                            unsigned &WhichResult,
6201                                            bool &isV_UNDEF) {
6202   isV_UNDEF = false;
6203   if (isVTRNMask(ShuffleMask, VT, WhichResult))
6204     return ARMISD::VTRN;
6205   if (isVUZPMask(ShuffleMask, VT, WhichResult))
6206     return ARMISD::VUZP;
6207   if (isVZIPMask(ShuffleMask, VT, WhichResult))
6208     return ARMISD::VZIP;
6209 
6210   isV_UNDEF = true;
6211   if (isVTRN_v_undef_Mask(ShuffleMask, VT, WhichResult))
6212     return ARMISD::VTRN;
6213   if (isVUZP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6214     return ARMISD::VUZP;
6215   if (isVZIP_v_undef_Mask(ShuffleMask, VT, WhichResult))
6216     return ARMISD::VZIP;
6217 
6218   return 0;
6219 }
6220 
6221 /// \return true if this is a reverse operation on an vector.
6222 static bool isReverseMask(ArrayRef<int> M, EVT VT) {
6223   unsigned NumElts = VT.getVectorNumElements();
6224   // Make sure the mask has the right size.
6225   if (NumElts != M.size())
6226       return false;
6227 
6228   // Look for <15, ..., 3, -1, 1, 0>.
6229   for (unsigned i = 0; i != NumElts; ++i)
6230     if (M[i] >= 0 && M[i] != (int) (NumElts - 1 - i))
6231       return false;
6232 
6233   return true;
6234 }
6235 
6236 // If N is an integer constant that can be moved into a register in one
6237 // instruction, return an SDValue of such a constant (will become a MOV
6238 // instruction).  Otherwise return null.
6239 static SDValue IsSingleInstrConstant(SDValue N, SelectionDAG &DAG,
6240                                      const ARMSubtarget *ST, const SDLoc &dl) {
6241   uint64_t Val;
6242   if (!isa<ConstantSDNode>(N))
6243     return SDValue();
6244   Val = cast<ConstantSDNode>(N)->getZExtValue();
6245 
6246   if (ST->isThumb1Only()) {
6247     if (Val <= 255 || ~Val <= 255)
6248       return DAG.getConstant(Val, dl, MVT::i32);
6249   } else {
6250     if (ARM_AM::getSOImmVal(Val) != -1 || ARM_AM::getSOImmVal(~Val) != -1)
6251       return DAG.getConstant(Val, dl, MVT::i32);
6252   }
6253   return SDValue();
6254 }
6255 
6256 // If this is a case we can't handle, return null and let the default
6257 // expansion code take care of it.
6258 SDValue ARMTargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
6259                                              const ARMSubtarget *ST) const {
6260   BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
6261   SDLoc dl(Op);
6262   EVT VT = Op.getValueType();
6263 
6264   APInt SplatBits, SplatUndef;
6265   unsigned SplatBitSize;
6266   bool HasAnyUndefs;
6267   if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
6268     if (SplatUndef.isAllOnesValue())
6269       return DAG.getUNDEF(VT);
6270 
6271     if (SplatBitSize <= 64) {
6272       // Check if an immediate VMOV works.
6273       EVT VmovVT;
6274       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
6275                                       SplatUndef.getZExtValue(), SplatBitSize,
6276                                       DAG, dl, VmovVT, VT.is128BitVector(),
6277                                       VMOVModImm);
6278       if (Val.getNode()) {
6279         SDValue Vmov = DAG.getNode(ARMISD::VMOVIMM, dl, VmovVT, Val);
6280         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6281       }
6282 
6283       // Try an immediate VMVN.
6284       uint64_t NegatedImm = (~SplatBits).getZExtValue();
6285       Val = isNEONModifiedImm(NegatedImm,
6286                                       SplatUndef.getZExtValue(), SplatBitSize,
6287                                       DAG, dl, VmovVT, VT.is128BitVector(),
6288                                       VMVNModImm);
6289       if (Val.getNode()) {
6290         SDValue Vmov = DAG.getNode(ARMISD::VMVNIMM, dl, VmovVT, Val);
6291         return DAG.getNode(ISD::BITCAST, dl, VT, Vmov);
6292       }
6293 
6294       // Use vmov.f32 to materialize other v2f32 and v4f32 splats.
6295       if ((VT == MVT::v2f32 || VT == MVT::v4f32) && SplatBitSize == 32) {
6296         int ImmVal = ARM_AM::getFP32Imm(SplatBits);
6297         if (ImmVal != -1) {
6298           SDValue Val = DAG.getTargetConstant(ImmVal, dl, MVT::i32);
6299           return DAG.getNode(ARMISD::VMOVFPIMM, dl, VT, Val);
6300         }
6301       }
6302     }
6303   }
6304 
6305   // Scan through the operands to see if only one value is used.
6306   //
6307   // As an optimisation, even if more than one value is used it may be more
6308   // profitable to splat with one value then change some lanes.
6309   //
6310   // Heuristically we decide to do this if the vector has a "dominant" value,
6311   // defined as splatted to more than half of the lanes.
6312   unsigned NumElts = VT.getVectorNumElements();
6313   bool isOnlyLowElement = true;
6314   bool usesOnlyOneValue = true;
6315   bool hasDominantValue = false;
6316   bool isConstant = true;
6317 
6318   // Map of the number of times a particular SDValue appears in the
6319   // element list.
6320   DenseMap<SDValue, unsigned> ValueCounts;
6321   SDValue Value;
6322   for (unsigned i = 0; i < NumElts; ++i) {
6323     SDValue V = Op.getOperand(i);
6324     if (V.isUndef())
6325       continue;
6326     if (i > 0)
6327       isOnlyLowElement = false;
6328     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
6329       isConstant = false;
6330 
6331     ValueCounts.insert(std::make_pair(V, 0));
6332     unsigned &Count = ValueCounts[V];
6333 
6334     // Is this value dominant? (takes up more than half of the lanes)
6335     if (++Count > (NumElts / 2)) {
6336       hasDominantValue = true;
6337       Value = V;
6338     }
6339   }
6340   if (ValueCounts.size() != 1)
6341     usesOnlyOneValue = false;
6342   if (!Value.getNode() && !ValueCounts.empty())
6343     Value = ValueCounts.begin()->first;
6344 
6345   if (ValueCounts.empty())
6346     return DAG.getUNDEF(VT);
6347 
6348   // Loads are better lowered with insert_vector_elt/ARMISD::BUILD_VECTOR.
6349   // Keep going if we are hitting this case.
6350   if (isOnlyLowElement && !ISD::isNormalLoad(Value.getNode()))
6351     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
6352 
6353   unsigned EltSize = VT.getScalarSizeInBits();
6354 
6355   // Use VDUP for non-constant splats.  For f32 constant splats, reduce to
6356   // i32 and try again.
6357   if (hasDominantValue && EltSize <= 32) {
6358     if (!isConstant) {
6359       SDValue N;
6360 
6361       // If we are VDUPing a value that comes directly from a vector, that will
6362       // cause an unnecessary move to and from a GPR, where instead we could
6363       // just use VDUPLANE. We can only do this if the lane being extracted
6364       // is at a constant index, as the VDUP from lane instructions only have
6365       // constant-index forms.
6366       ConstantSDNode *constIndex;
6367       if (Value->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6368           (constIndex = dyn_cast<ConstantSDNode>(Value->getOperand(1)))) {
6369         // We need to create a new undef vector to use for the VDUPLANE if the
6370         // size of the vector from which we get the value is different than the
6371         // size of the vector that we need to create. We will insert the element
6372         // such that the register coalescer will remove unnecessary copies.
6373         if (VT != Value->getOperand(0).getValueType()) {
6374           unsigned index = constIndex->getAPIntValue().getLimitedValue() %
6375                              VT.getVectorNumElements();
6376           N =  DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6377                  DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DAG.getUNDEF(VT),
6378                         Value, DAG.getConstant(index, dl, MVT::i32)),
6379                            DAG.getConstant(index, dl, MVT::i32));
6380         } else
6381           N = DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6382                         Value->getOperand(0), Value->getOperand(1));
6383       } else
6384         N = DAG.getNode(ARMISD::VDUP, dl, VT, Value);
6385 
6386       if (!usesOnlyOneValue) {
6387         // The dominant value was splatted as 'N', but we now have to insert
6388         // all differing elements.
6389         for (unsigned I = 0; I < NumElts; ++I) {
6390           if (Op.getOperand(I) == Value)
6391             continue;
6392           SmallVector<SDValue, 3> Ops;
6393           Ops.push_back(N);
6394           Ops.push_back(Op.getOperand(I));
6395           Ops.push_back(DAG.getConstant(I, dl, MVT::i32));
6396           N = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Ops);
6397         }
6398       }
6399       return N;
6400     }
6401     if (VT.getVectorElementType().isFloatingPoint()) {
6402       SmallVector<SDValue, 8> Ops;
6403       for (unsigned i = 0; i < NumElts; ++i)
6404         Ops.push_back(DAG.getNode(ISD::BITCAST, dl, MVT::i32,
6405                                   Op.getOperand(i)));
6406       EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
6407       SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
6408       Val = LowerBUILD_VECTOR(Val, DAG, ST);
6409       if (Val.getNode())
6410         return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6411     }
6412     if (usesOnlyOneValue) {
6413       SDValue Val = IsSingleInstrConstant(Value, DAG, ST, dl);
6414       if (isConstant && Val.getNode())
6415         return DAG.getNode(ARMISD::VDUP, dl, VT, Val);
6416     }
6417   }
6418 
6419   // If all elements are constants and the case above didn't get hit, fall back
6420   // to the default expansion, which will generate a load from the constant
6421   // pool.
6422   if (isConstant)
6423     return SDValue();
6424 
6425   // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
6426   if (NumElts >= 4) {
6427     SDValue shuffle = ReconstructShuffle(Op, DAG);
6428     if (shuffle != SDValue())
6429       return shuffle;
6430   }
6431 
6432   if (VT.is128BitVector() && VT != MVT::v2f64 && VT != MVT::v4f32) {
6433     // If we haven't found an efficient lowering, try splitting a 128-bit vector
6434     // into two 64-bit vectors; we might discover a better way to lower it.
6435     SmallVector<SDValue, 64> Ops(Op->op_begin(), Op->op_begin() + NumElts);
6436     EVT ExtVT = VT.getVectorElementType();
6437     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElts / 2);
6438     SDValue Lower =
6439         DAG.getBuildVector(HVT, dl, makeArrayRef(&Ops[0], NumElts / 2));
6440     if (Lower.getOpcode() == ISD::BUILD_VECTOR)
6441       Lower = LowerBUILD_VECTOR(Lower, DAG, ST);
6442     SDValue Upper = DAG.getBuildVector(
6443         HVT, dl, makeArrayRef(&Ops[NumElts / 2], NumElts / 2));
6444     if (Upper.getOpcode() == ISD::BUILD_VECTOR)
6445       Upper = LowerBUILD_VECTOR(Upper, DAG, ST);
6446     if (Lower && Upper)
6447       return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Lower, Upper);
6448   }
6449 
6450   // Vectors with 32- or 64-bit elements can be built by directly assigning
6451   // the subregisters.  Lower it to an ARMISD::BUILD_VECTOR so the operands
6452   // will be legalized.
6453   if (EltSize >= 32) {
6454     // Do the expansion with floating-point types, since that is what the VFP
6455     // registers are defined to use, and since i64 is not legal.
6456     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6457     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6458     SmallVector<SDValue, 8> Ops;
6459     for (unsigned i = 0; i < NumElts; ++i)
6460       Ops.push_back(DAG.getNode(ISD::BITCAST, dl, EltVT, Op.getOperand(i)));
6461     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
6462     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
6463   }
6464 
6465   // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
6466   // know the default expansion would otherwise fall back on something even
6467   // worse. For a vector with one or two non-undef values, that's
6468   // scalar_to_vector for the elements followed by a shuffle (provided the
6469   // shuffle is valid for the target) and materialization element by element
6470   // on the stack followed by a load for everything else.
6471   if (!isConstant && !usesOnlyOneValue) {
6472     SDValue Vec = DAG.getUNDEF(VT);
6473     for (unsigned i = 0 ; i < NumElts; ++i) {
6474       SDValue V = Op.getOperand(i);
6475       if (V.isUndef())
6476         continue;
6477       SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i32);
6478       Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
6479     }
6480     return Vec;
6481   }
6482 
6483   return SDValue();
6484 }
6485 
6486 // Gather data to see if the operation can be modelled as a
6487 // shuffle in combination with VEXTs.
6488 SDValue ARMTargetLowering::ReconstructShuffle(SDValue Op,
6489                                               SelectionDAG &DAG) const {
6490   assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
6491   SDLoc dl(Op);
6492   EVT VT = Op.getValueType();
6493   unsigned NumElts = VT.getVectorNumElements();
6494 
6495   struct ShuffleSourceInfo {
6496     SDValue Vec;
6497     unsigned MinElt = std::numeric_limits<unsigned>::max();
6498     unsigned MaxElt = 0;
6499 
6500     // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
6501     // be compatible with the shuffle we intend to construct. As a result
6502     // ShuffleVec will be some sliding window into the original Vec.
6503     SDValue ShuffleVec;
6504 
6505     // Code should guarantee that element i in Vec starts at element "WindowBase
6506     // + i * WindowScale in ShuffleVec".
6507     int WindowBase = 0;
6508     int WindowScale = 1;
6509 
6510     ShuffleSourceInfo(SDValue Vec) : Vec(Vec), ShuffleVec(Vec) {}
6511 
6512     bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
6513   };
6514 
6515   // First gather all vectors used as an immediate source for this BUILD_VECTOR
6516   // node.
6517   SmallVector<ShuffleSourceInfo, 2> Sources;
6518   for (unsigned i = 0; i < NumElts; ++i) {
6519     SDValue V = Op.getOperand(i);
6520     if (V.isUndef())
6521       continue;
6522     else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT) {
6523       // A shuffle can only come from building a vector from various
6524       // elements of other vectors.
6525       return SDValue();
6526     } else if (!isa<ConstantSDNode>(V.getOperand(1))) {
6527       // Furthermore, shuffles require a constant mask, whereas extractelts
6528       // accept variable indices.
6529       return SDValue();
6530     }
6531 
6532     // Add this element source to the list if it's not already there.
6533     SDValue SourceVec = V.getOperand(0);
6534     auto Source = llvm::find(Sources, SourceVec);
6535     if (Source == Sources.end())
6536       Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
6537 
6538     // Update the minimum and maximum lane number seen.
6539     unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
6540     Source->MinElt = std::min(Source->MinElt, EltNo);
6541     Source->MaxElt = std::max(Source->MaxElt, EltNo);
6542   }
6543 
6544   // Currently only do something sane when at most two source vectors
6545   // are involved.
6546   if (Sources.size() > 2)
6547     return SDValue();
6548 
6549   // Find out the smallest element size among result and two sources, and use
6550   // it as element size to build the shuffle_vector.
6551   EVT SmallestEltTy = VT.getVectorElementType();
6552   for (auto &Source : Sources) {
6553     EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
6554     if (SrcEltTy.bitsLT(SmallestEltTy))
6555       SmallestEltTy = SrcEltTy;
6556   }
6557   unsigned ResMultiplier =
6558       VT.getScalarSizeInBits() / SmallestEltTy.getSizeInBits();
6559   NumElts = VT.getSizeInBits() / SmallestEltTy.getSizeInBits();
6560   EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
6561 
6562   // If the source vector is too wide or too narrow, we may nevertheless be able
6563   // to construct a compatible shuffle either by concatenating it with UNDEF or
6564   // extracting a suitable range of elements.
6565   for (auto &Src : Sources) {
6566     EVT SrcVT = Src.ShuffleVec.getValueType();
6567 
6568     if (SrcVT.getSizeInBits() == VT.getSizeInBits())
6569       continue;
6570 
6571     // This stage of the search produces a source with the same element type as
6572     // the original, but with a total width matching the BUILD_VECTOR output.
6573     EVT EltVT = SrcVT.getVectorElementType();
6574     unsigned NumSrcElts = VT.getSizeInBits() / EltVT.getSizeInBits();
6575     EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
6576 
6577     if (SrcVT.getSizeInBits() < VT.getSizeInBits()) {
6578       if (2 * SrcVT.getSizeInBits() != VT.getSizeInBits())
6579         return SDValue();
6580       // We can pad out the smaller vector for free, so if it's part of a
6581       // shuffle...
6582       Src.ShuffleVec =
6583           DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
6584                       DAG.getUNDEF(Src.ShuffleVec.getValueType()));
6585       continue;
6586     }
6587 
6588     if (SrcVT.getSizeInBits() != 2 * VT.getSizeInBits())
6589       return SDValue();
6590 
6591     if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
6592       // Span too large for a VEXT to cope
6593       return SDValue();
6594     }
6595 
6596     if (Src.MinElt >= NumSrcElts) {
6597       // The extraction can just take the second half
6598       Src.ShuffleVec =
6599           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6600                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6601       Src.WindowBase = -NumSrcElts;
6602     } else if (Src.MaxElt < NumSrcElts) {
6603       // The extraction can just take the first half
6604       Src.ShuffleVec =
6605           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6606                       DAG.getConstant(0, dl, MVT::i32));
6607     } else {
6608       // An actual VEXT is needed
6609       SDValue VEXTSrc1 =
6610           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6611                       DAG.getConstant(0, dl, MVT::i32));
6612       SDValue VEXTSrc2 =
6613           DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
6614                       DAG.getConstant(NumSrcElts, dl, MVT::i32));
6615 
6616       Src.ShuffleVec = DAG.getNode(ARMISD::VEXT, dl, DestVT, VEXTSrc1,
6617                                    VEXTSrc2,
6618                                    DAG.getConstant(Src.MinElt, dl, MVT::i32));
6619       Src.WindowBase = -Src.MinElt;
6620     }
6621   }
6622 
6623   // Another possible incompatibility occurs from the vector element types. We
6624   // can fix this by bitcasting the source vectors to the same type we intend
6625   // for the shuffle.
6626   for (auto &Src : Sources) {
6627     EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
6628     if (SrcEltTy == SmallestEltTy)
6629       continue;
6630     assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
6631     Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
6632     Src.WindowScale = SrcEltTy.getSizeInBits() / SmallestEltTy.getSizeInBits();
6633     Src.WindowBase *= Src.WindowScale;
6634   }
6635 
6636   // Final sanity check before we try to actually produce a shuffle.
6637   DEBUG(
6638     for (auto Src : Sources)
6639       assert(Src.ShuffleVec.getValueType() == ShuffleVT);
6640   );
6641 
6642   // The stars all align, our next step is to produce the mask for the shuffle.
6643   SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
6644   int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
6645   for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
6646     SDValue Entry = Op.getOperand(i);
6647     if (Entry.isUndef())
6648       continue;
6649 
6650     auto Src = llvm::find(Sources, Entry.getOperand(0));
6651     int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
6652 
6653     // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
6654     // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
6655     // segment.
6656     EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
6657     int BitsDefined = std::min(OrigEltTy.getSizeInBits(),
6658                                VT.getScalarSizeInBits());
6659     int LanesDefined = BitsDefined / BitsPerShuffleLane;
6660 
6661     // This source is expected to fill ResMultiplier lanes of the final shuffle,
6662     // starting at the appropriate offset.
6663     int *LaneMask = &Mask[i * ResMultiplier];
6664 
6665     int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
6666     ExtractBase += NumElts * (Src - Sources.begin());
6667     for (int j = 0; j < LanesDefined; ++j)
6668       LaneMask[j] = ExtractBase + j;
6669   }
6670 
6671   // Final check before we try to produce nonsense...
6672   if (!isShuffleMaskLegal(Mask, ShuffleVT))
6673     return SDValue();
6674 
6675   // We can't handle more than two sources. This should have already
6676   // been checked before this point.
6677   assert(Sources.size() <= 2 && "Too many sources!");
6678 
6679   SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
6680   for (unsigned i = 0; i < Sources.size(); ++i)
6681     ShuffleOps[i] = Sources[i].ShuffleVec;
6682 
6683   SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
6684                                          ShuffleOps[1], Mask);
6685   return DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
6686 }
6687 
6688 /// isShuffleMaskLegal - Targets can use this to indicate that they only
6689 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
6690 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
6691 /// are assumed to be legal.
6692 bool ARMTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
6693   if (VT.getVectorNumElements() == 4 &&
6694       (VT.is128BitVector() || VT.is64BitVector())) {
6695     unsigned PFIndexes[4];
6696     for (unsigned i = 0; i != 4; ++i) {
6697       if (M[i] < 0)
6698         PFIndexes[i] = 8;
6699       else
6700         PFIndexes[i] = M[i];
6701     }
6702 
6703     // Compute the index in the perfect shuffle table.
6704     unsigned PFTableIndex =
6705       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6706     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6707     unsigned Cost = (PFEntry >> 30);
6708 
6709     if (Cost <= 4)
6710       return true;
6711   }
6712 
6713   bool ReverseVEXT, isV_UNDEF;
6714   unsigned Imm, WhichResult;
6715 
6716   unsigned EltSize = VT.getScalarSizeInBits();
6717   return (EltSize >= 32 ||
6718           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
6719           isVREVMask(M, VT, 64) ||
6720           isVREVMask(M, VT, 32) ||
6721           isVREVMask(M, VT, 16) ||
6722           isVEXTMask(M, VT, ReverseVEXT, Imm) ||
6723           isVTBLMask(M, VT) ||
6724           isNEONTwoResultShuffleMask(M, VT, WhichResult, isV_UNDEF) ||
6725           ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(M, VT)));
6726 }
6727 
6728 /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
6729 /// the specified operations to build the shuffle.
6730 static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
6731                                       SDValue RHS, SelectionDAG &DAG,
6732                                       const SDLoc &dl) {
6733   unsigned OpNum = (PFEntry >> 26) & 0x0F;
6734   unsigned LHSID = (PFEntry >> 13) & ((1 << 13)-1);
6735   unsigned RHSID = (PFEntry >>  0) & ((1 << 13)-1);
6736 
6737   enum {
6738     OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
6739     OP_VREV,
6740     OP_VDUP0,
6741     OP_VDUP1,
6742     OP_VDUP2,
6743     OP_VDUP3,
6744     OP_VEXT1,
6745     OP_VEXT2,
6746     OP_VEXT3,
6747     OP_VUZPL, // VUZP, left result
6748     OP_VUZPR, // VUZP, right result
6749     OP_VZIPL, // VZIP, left result
6750     OP_VZIPR, // VZIP, right result
6751     OP_VTRNL, // VTRN, left result
6752     OP_VTRNR  // VTRN, right result
6753   };
6754 
6755   if (OpNum == OP_COPY) {
6756     if (LHSID == (1*9+2)*9+3) return LHS;
6757     assert(LHSID == ((4*9+5)*9+6)*9+7 && "Illegal OP_COPY!");
6758     return RHS;
6759   }
6760 
6761   SDValue OpLHS, OpRHS;
6762   OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
6763   OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
6764   EVT VT = OpLHS.getValueType();
6765 
6766   switch (OpNum) {
6767   default: llvm_unreachable("Unknown shuffle opcode!");
6768   case OP_VREV:
6769     // VREV divides the vector in half and swaps within the half.
6770     if (VT.getVectorElementType() == MVT::i32 ||
6771         VT.getVectorElementType() == MVT::f32)
6772       return DAG.getNode(ARMISD::VREV64, dl, VT, OpLHS);
6773     // vrev <4 x i16> -> VREV32
6774     if (VT.getVectorElementType() == MVT::i16)
6775       return DAG.getNode(ARMISD::VREV32, dl, VT, OpLHS);
6776     // vrev <4 x i8> -> VREV16
6777     assert(VT.getVectorElementType() == MVT::i8);
6778     return DAG.getNode(ARMISD::VREV16, dl, VT, OpLHS);
6779   case OP_VDUP0:
6780   case OP_VDUP1:
6781   case OP_VDUP2:
6782   case OP_VDUP3:
6783     return DAG.getNode(ARMISD::VDUPLANE, dl, VT,
6784                        OpLHS, DAG.getConstant(OpNum-OP_VDUP0, dl, MVT::i32));
6785   case OP_VEXT1:
6786   case OP_VEXT2:
6787   case OP_VEXT3:
6788     return DAG.getNode(ARMISD::VEXT, dl, VT,
6789                        OpLHS, OpRHS,
6790                        DAG.getConstant(OpNum - OP_VEXT1 + 1, dl, MVT::i32));
6791   case OP_VUZPL:
6792   case OP_VUZPR:
6793     return DAG.getNode(ARMISD::VUZP, dl, DAG.getVTList(VT, VT),
6794                        OpLHS, OpRHS).getValue(OpNum-OP_VUZPL);
6795   case OP_VZIPL:
6796   case OP_VZIPR:
6797     return DAG.getNode(ARMISD::VZIP, dl, DAG.getVTList(VT, VT),
6798                        OpLHS, OpRHS).getValue(OpNum-OP_VZIPL);
6799   case OP_VTRNL:
6800   case OP_VTRNR:
6801     return DAG.getNode(ARMISD::VTRN, dl, DAG.getVTList(VT, VT),
6802                        OpLHS, OpRHS).getValue(OpNum-OP_VTRNL);
6803   }
6804 }
6805 
6806 static SDValue LowerVECTOR_SHUFFLEv8i8(SDValue Op,
6807                                        ArrayRef<int> ShuffleMask,
6808                                        SelectionDAG &DAG) {
6809   // Check to see if we can use the VTBL instruction.
6810   SDValue V1 = Op.getOperand(0);
6811   SDValue V2 = Op.getOperand(1);
6812   SDLoc DL(Op);
6813 
6814   SmallVector<SDValue, 8> VTBLMask;
6815   for (ArrayRef<int>::iterator
6816          I = ShuffleMask.begin(), E = ShuffleMask.end(); I != E; ++I)
6817     VTBLMask.push_back(DAG.getConstant(*I, DL, MVT::i32));
6818 
6819   if (V2.getNode()->isUndef())
6820     return DAG.getNode(ARMISD::VTBL1, DL, MVT::v8i8, V1,
6821                        DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6822 
6823   return DAG.getNode(ARMISD::VTBL2, DL, MVT::v8i8, V1, V2,
6824                      DAG.getBuildVector(MVT::v8i8, DL, VTBLMask));
6825 }
6826 
6827 static SDValue LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(SDValue Op,
6828                                                       SelectionDAG &DAG) {
6829   SDLoc DL(Op);
6830   SDValue OpLHS = Op.getOperand(0);
6831   EVT VT = OpLHS.getValueType();
6832 
6833   assert((VT == MVT::v8i16 || VT == MVT::v16i8) &&
6834          "Expect an v8i16/v16i8 type");
6835   OpLHS = DAG.getNode(ARMISD::VREV64, DL, VT, OpLHS);
6836   // For a v16i8 type: After the VREV, we have got <8, ...15, 8, ..., 0>. Now,
6837   // extract the first 8 bytes into the top double word and the last 8 bytes
6838   // into the bottom double word. The v8i16 case is similar.
6839   unsigned ExtractNum = (VT == MVT::v16i8) ? 8 : 4;
6840   return DAG.getNode(ARMISD::VEXT, DL, VT, OpLHS, OpLHS,
6841                      DAG.getConstant(ExtractNum, DL, MVT::i32));
6842 }
6843 
6844 static SDValue LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) {
6845   SDValue V1 = Op.getOperand(0);
6846   SDValue V2 = Op.getOperand(1);
6847   SDLoc dl(Op);
6848   EVT VT = Op.getValueType();
6849   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
6850 
6851   // Convert shuffles that are directly supported on NEON to target-specific
6852   // DAG nodes, instead of keeping them as shuffles and matching them again
6853   // during code selection.  This is more efficient and avoids the possibility
6854   // of inconsistencies between legalization and selection.
6855   // FIXME: floating-point vectors should be canonicalized to integer vectors
6856   // of the same time so that they get CSEd properly.
6857   ArrayRef<int> ShuffleMask = SVN->getMask();
6858 
6859   unsigned EltSize = VT.getScalarSizeInBits();
6860   if (EltSize <= 32) {
6861     if (SVN->isSplat()) {
6862       int Lane = SVN->getSplatIndex();
6863       // If this is undef splat, generate it via "just" vdup, if possible.
6864       if (Lane == -1) Lane = 0;
6865 
6866       // Test if V1 is a SCALAR_TO_VECTOR.
6867       if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6868         return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6869       }
6870       // Test if V1 is a BUILD_VECTOR which is equivalent to a SCALAR_TO_VECTOR
6871       // (and probably will turn into a SCALAR_TO_VECTOR once legalization
6872       // reaches it).
6873       if (Lane == 0 && V1.getOpcode() == ISD::BUILD_VECTOR &&
6874           !isa<ConstantSDNode>(V1.getOperand(0))) {
6875         bool IsScalarToVector = true;
6876         for (unsigned i = 1, e = V1.getNumOperands(); i != e; ++i)
6877           if (!V1.getOperand(i).isUndef()) {
6878             IsScalarToVector = false;
6879             break;
6880           }
6881         if (IsScalarToVector)
6882           return DAG.getNode(ARMISD::VDUP, dl, VT, V1.getOperand(0));
6883       }
6884       return DAG.getNode(ARMISD::VDUPLANE, dl, VT, V1,
6885                          DAG.getConstant(Lane, dl, MVT::i32));
6886     }
6887 
6888     bool ReverseVEXT;
6889     unsigned Imm;
6890     if (isVEXTMask(ShuffleMask, VT, ReverseVEXT, Imm)) {
6891       if (ReverseVEXT)
6892         std::swap(V1, V2);
6893       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V2,
6894                          DAG.getConstant(Imm, dl, MVT::i32));
6895     }
6896 
6897     if (isVREVMask(ShuffleMask, VT, 64))
6898       return DAG.getNode(ARMISD::VREV64, dl, VT, V1);
6899     if (isVREVMask(ShuffleMask, VT, 32))
6900       return DAG.getNode(ARMISD::VREV32, dl, VT, V1);
6901     if (isVREVMask(ShuffleMask, VT, 16))
6902       return DAG.getNode(ARMISD::VREV16, dl, VT, V1);
6903 
6904     if (V2->isUndef() && isSingletonVEXTMask(ShuffleMask, VT, Imm)) {
6905       return DAG.getNode(ARMISD::VEXT, dl, VT, V1, V1,
6906                          DAG.getConstant(Imm, dl, MVT::i32));
6907     }
6908 
6909     // Check for Neon shuffles that modify both input vectors in place.
6910     // If both results are used, i.e., if there are two shuffles with the same
6911     // source operands and with masks corresponding to both results of one of
6912     // these operations, DAG memoization will ensure that a single node is
6913     // used for both shuffles.
6914     unsigned WhichResult;
6915     bool isV_UNDEF;
6916     if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6917             ShuffleMask, VT, WhichResult, isV_UNDEF)) {
6918       if (isV_UNDEF)
6919         V2 = V1;
6920       return DAG.getNode(ShuffleOpc, dl, DAG.getVTList(VT, VT), V1, V2)
6921           .getValue(WhichResult);
6922     }
6923 
6924     // Also check for these shuffles through CONCAT_VECTORS: we canonicalize
6925     // shuffles that produce a result larger than their operands with:
6926     //   shuffle(concat(v1, undef), concat(v2, undef))
6927     // ->
6928     //   shuffle(concat(v1, v2), undef)
6929     // because we can access quad vectors (see PerformVECTOR_SHUFFLECombine).
6930     //
6931     // This is useful in the general case, but there are special cases where
6932     // native shuffles produce larger results: the two-result ops.
6933     //
6934     // Look through the concat when lowering them:
6935     //   shuffle(concat(v1, v2), undef)
6936     // ->
6937     //   concat(VZIP(v1, v2):0, :1)
6938     //
6939     if (V1->getOpcode() == ISD::CONCAT_VECTORS && V2->isUndef()) {
6940       SDValue SubV1 = V1->getOperand(0);
6941       SDValue SubV2 = V1->getOperand(1);
6942       EVT SubVT = SubV1.getValueType();
6943 
6944       // We expect these to have been canonicalized to -1.
6945       assert(llvm::all_of(ShuffleMask, [&](int i) {
6946         return i < (int)VT.getVectorNumElements();
6947       }) && "Unexpected shuffle index into UNDEF operand!");
6948 
6949       if (unsigned ShuffleOpc = isNEONTwoResultShuffleMask(
6950               ShuffleMask, SubVT, WhichResult, isV_UNDEF)) {
6951         if (isV_UNDEF)
6952           SubV2 = SubV1;
6953         assert((WhichResult == 0) &&
6954                "In-place shuffle of concat can only have one result!");
6955         SDValue Res = DAG.getNode(ShuffleOpc, dl, DAG.getVTList(SubVT, SubVT),
6956                                   SubV1, SubV2);
6957         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Res.getValue(0),
6958                            Res.getValue(1));
6959       }
6960     }
6961   }
6962 
6963   // If the shuffle is not directly supported and it has 4 elements, use
6964   // the PerfectShuffle-generated table to synthesize it from other shuffles.
6965   unsigned NumElts = VT.getVectorNumElements();
6966   if (NumElts == 4) {
6967     unsigned PFIndexes[4];
6968     for (unsigned i = 0; i != 4; ++i) {
6969       if (ShuffleMask[i] < 0)
6970         PFIndexes[i] = 8;
6971       else
6972         PFIndexes[i] = ShuffleMask[i];
6973     }
6974 
6975     // Compute the index in the perfect shuffle table.
6976     unsigned PFTableIndex =
6977       PFIndexes[0]*9*9*9+PFIndexes[1]*9*9+PFIndexes[2]*9+PFIndexes[3];
6978     unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
6979     unsigned Cost = (PFEntry >> 30);
6980 
6981     if (Cost <= 4)
6982       return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
6983   }
6984 
6985   // Implement shuffles with 32- or 64-bit elements as ARMISD::BUILD_VECTORs.
6986   if (EltSize >= 32) {
6987     // Do the expansion with floating-point types, since that is what the VFP
6988     // registers are defined to use, and since i64 is not legal.
6989     EVT EltVT = EVT::getFloatingPointVT(EltSize);
6990     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts);
6991     V1 = DAG.getNode(ISD::BITCAST, dl, VecVT, V1);
6992     V2 = DAG.getNode(ISD::BITCAST, dl, VecVT, V2);
6993     SmallVector<SDValue, 8> Ops;
6994     for (unsigned i = 0; i < NumElts; ++i) {
6995       if (ShuffleMask[i] < 0)
6996         Ops.push_back(DAG.getUNDEF(EltVT));
6997       else
6998         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
6999                                   ShuffleMask[i] < (int)NumElts ? V1 : V2,
7000                                   DAG.getConstant(ShuffleMask[i] & (NumElts-1),
7001                                                   dl, MVT::i32)));
7002     }
7003     SDValue Val = DAG.getNode(ARMISD::BUILD_VECTOR, dl, VecVT, Ops);
7004     return DAG.getNode(ISD::BITCAST, dl, VT, Val);
7005   }
7006 
7007   if ((VT == MVT::v8i16 || VT == MVT::v16i8) && isReverseMask(ShuffleMask, VT))
7008     return LowerReverse_VECTOR_SHUFFLEv16i8_v8i16(Op, DAG);
7009 
7010   if (VT == MVT::v8i8)
7011     if (SDValue NewOp = LowerVECTOR_SHUFFLEv8i8(Op, ShuffleMask, DAG))
7012       return NewOp;
7013 
7014   return SDValue();
7015 }
7016 
7017 static SDValue LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7018   // INSERT_VECTOR_ELT is legal only for immediate indexes.
7019   SDValue Lane = Op.getOperand(2);
7020   if (!isa<ConstantSDNode>(Lane))
7021     return SDValue();
7022 
7023   return Op;
7024 }
7025 
7026 static SDValue LowerEXTRACT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) {
7027   // EXTRACT_VECTOR_ELT is legal only for immediate indexes.
7028   SDValue Lane = Op.getOperand(1);
7029   if (!isa<ConstantSDNode>(Lane))
7030     return SDValue();
7031 
7032   SDValue Vec = Op.getOperand(0);
7033   if (Op.getValueType() == MVT::i32 && Vec.getScalarValueSizeInBits() < 32) {
7034     SDLoc dl(Op);
7035     return DAG.getNode(ARMISD::VGETLANEu, dl, MVT::i32, Vec, Lane);
7036   }
7037 
7038   return Op;
7039 }
7040 
7041 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7042   // The only time a CONCAT_VECTORS operation can have legal types is when
7043   // two 64-bit vectors are concatenated to a 128-bit vector.
7044   assert(Op.getValueType().is128BitVector() && Op.getNumOperands() == 2 &&
7045          "unexpected CONCAT_VECTORS");
7046   SDLoc dl(Op);
7047   SDValue Val = DAG.getUNDEF(MVT::v2f64);
7048   SDValue Op0 = Op.getOperand(0);
7049   SDValue Op1 = Op.getOperand(1);
7050   if (!Op0.isUndef())
7051     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7052                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op0),
7053                       DAG.getIntPtrConstant(0, dl));
7054   if (!Op1.isUndef())
7055     Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v2f64, Val,
7056                       DAG.getNode(ISD::BITCAST, dl, MVT::f64, Op1),
7057                       DAG.getIntPtrConstant(1, dl));
7058   return DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Val);
7059 }
7060 
7061 /// isExtendedBUILD_VECTOR - Check if N is a constant BUILD_VECTOR where each
7062 /// element has been zero/sign-extended, depending on the isSigned parameter,
7063 /// from an integer type half its size.
7064 static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
7065                                    bool isSigned) {
7066   // A v2i64 BUILD_VECTOR will have been legalized to a BITCAST from v4i32.
7067   EVT VT = N->getValueType(0);
7068   if (VT == MVT::v2i64 && N->getOpcode() == ISD::BITCAST) {
7069     SDNode *BVN = N->getOperand(0).getNode();
7070     if (BVN->getValueType(0) != MVT::v4i32 ||
7071         BVN->getOpcode() != ISD::BUILD_VECTOR)
7072       return false;
7073     unsigned LoElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7074     unsigned HiElt = 1 - LoElt;
7075     ConstantSDNode *Lo0 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt));
7076     ConstantSDNode *Hi0 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt));
7077     ConstantSDNode *Lo1 = dyn_cast<ConstantSDNode>(BVN->getOperand(LoElt+2));
7078     ConstantSDNode *Hi1 = dyn_cast<ConstantSDNode>(BVN->getOperand(HiElt+2));
7079     if (!Lo0 || !Hi0 || !Lo1 || !Hi1)
7080       return false;
7081     if (isSigned) {
7082       if (Hi0->getSExtValue() == Lo0->getSExtValue() >> 32 &&
7083           Hi1->getSExtValue() == Lo1->getSExtValue() >> 32)
7084         return true;
7085     } else {
7086       if (Hi0->isNullValue() && Hi1->isNullValue())
7087         return true;
7088     }
7089     return false;
7090   }
7091 
7092   if (N->getOpcode() != ISD::BUILD_VECTOR)
7093     return false;
7094 
7095   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
7096     SDNode *Elt = N->getOperand(i).getNode();
7097     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
7098       unsigned EltSize = VT.getScalarSizeInBits();
7099       unsigned HalfSize = EltSize / 2;
7100       if (isSigned) {
7101         if (!isIntN(HalfSize, C->getSExtValue()))
7102           return false;
7103       } else {
7104         if (!isUIntN(HalfSize, C->getZExtValue()))
7105           return false;
7106       }
7107       continue;
7108     }
7109     return false;
7110   }
7111 
7112   return true;
7113 }
7114 
7115 /// isSignExtended - Check if a node is a vector value that is sign-extended
7116 /// or a constant BUILD_VECTOR with sign-extended elements.
7117 static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
7118   if (N->getOpcode() == ISD::SIGN_EXTEND || ISD::isSEXTLoad(N))
7119     return true;
7120   if (isExtendedBUILD_VECTOR(N, DAG, true))
7121     return true;
7122   return false;
7123 }
7124 
7125 /// isZeroExtended - Check if a node is a vector value that is zero-extended
7126 /// or a constant BUILD_VECTOR with zero-extended elements.
7127 static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
7128   if (N->getOpcode() == ISD::ZERO_EXTEND || ISD::isZEXTLoad(N))
7129     return true;
7130   if (isExtendedBUILD_VECTOR(N, DAG, false))
7131     return true;
7132   return false;
7133 }
7134 
7135 static EVT getExtensionTo64Bits(const EVT &OrigVT) {
7136   if (OrigVT.getSizeInBits() >= 64)
7137     return OrigVT;
7138 
7139   assert(OrigVT.isSimple() && "Expecting a simple value type");
7140 
7141   MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
7142   switch (OrigSimpleTy) {
7143   default: llvm_unreachable("Unexpected Vector Type");
7144   case MVT::v2i8:
7145   case MVT::v2i16:
7146      return MVT::v2i32;
7147   case MVT::v4i8:
7148     return  MVT::v4i16;
7149   }
7150 }
7151 
7152 /// AddRequiredExtensionForVMULL - Add a sign/zero extension to extend the total
7153 /// value size to 64 bits. We need a 64-bit D register as an operand to VMULL.
7154 /// We insert the required extension here to get the vector to fill a D register.
7155 static SDValue AddRequiredExtensionForVMULL(SDValue N, SelectionDAG &DAG,
7156                                             const EVT &OrigTy,
7157                                             const EVT &ExtTy,
7158                                             unsigned ExtOpcode) {
7159   // The vector originally had a size of OrigTy. It was then extended to ExtTy.
7160   // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
7161   // 64-bits we need to insert a new extension so that it will be 64-bits.
7162   assert(ExtTy.is128BitVector() && "Unexpected extension size");
7163   if (OrigTy.getSizeInBits() >= 64)
7164     return N;
7165 
7166   // Must extend size to at least 64 bits to be used as an operand for VMULL.
7167   EVT NewVT = getExtensionTo64Bits(OrigTy);
7168 
7169   return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
7170 }
7171 
7172 /// SkipLoadExtensionForVMULL - return a load of the original vector size that
7173 /// does not do any sign/zero extension. If the original vector is less
7174 /// than 64 bits, an appropriate extension will be added after the load to
7175 /// reach a total size of 64 bits. We have to add the extension separately
7176 /// because ARM does not have a sign/zero extending load for vectors.
7177 static SDValue SkipLoadExtensionForVMULL(LoadSDNode *LD, SelectionDAG& DAG) {
7178   EVT ExtendedTy = getExtensionTo64Bits(LD->getMemoryVT());
7179 
7180   // The load already has the right type.
7181   if (ExtendedTy == LD->getMemoryVT())
7182     return DAG.getLoad(LD->getMemoryVT(), SDLoc(LD), LD->getChain(),
7183                        LD->getBasePtr(), LD->getPointerInfo(),
7184                        LD->getAlignment(), LD->getMemOperand()->getFlags());
7185 
7186   // We need to create a zextload/sextload. We cannot just create a load
7187   // followed by a zext/zext node because LowerMUL is also run during normal
7188   // operation legalization where we can't create illegal types.
7189   return DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD), ExtendedTy,
7190                         LD->getChain(), LD->getBasePtr(), LD->getPointerInfo(),
7191                         LD->getMemoryVT(), LD->getAlignment(),
7192                         LD->getMemOperand()->getFlags());
7193 }
7194 
7195 /// SkipExtensionForVMULL - For a node that is a SIGN_EXTEND, ZERO_EXTEND,
7196 /// extending load, or BUILD_VECTOR with extended elements, return the
7197 /// unextended value. The unextended vector should be 64 bits so that it can
7198 /// be used as an operand to a VMULL instruction. If the original vector size
7199 /// before extension is less than 64 bits we add a an extension to resize
7200 /// the vector to 64 bits.
7201 static SDValue SkipExtensionForVMULL(SDNode *N, SelectionDAG &DAG) {
7202   if (N->getOpcode() == ISD::SIGN_EXTEND || N->getOpcode() == ISD::ZERO_EXTEND)
7203     return AddRequiredExtensionForVMULL(N->getOperand(0), DAG,
7204                                         N->getOperand(0)->getValueType(0),
7205                                         N->getValueType(0),
7206                                         N->getOpcode());
7207 
7208   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7209     assert((ISD::isSEXTLoad(LD) || ISD::isZEXTLoad(LD)) &&
7210            "Expected extending load");
7211 
7212     SDValue newLoad = SkipLoadExtensionForVMULL(LD, DAG);
7213     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), newLoad.getValue(1));
7214     unsigned Opcode = ISD::isSEXTLoad(LD) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
7215     SDValue extLoad =
7216         DAG.getNode(Opcode, SDLoc(newLoad), LD->getValueType(0), newLoad);
7217     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 0), extLoad);
7218 
7219     return newLoad;
7220   }
7221 
7222   // Otherwise, the value must be a BUILD_VECTOR.  For v2i64, it will
7223   // have been legalized as a BITCAST from v4i32.
7224   if (N->getOpcode() == ISD::BITCAST) {
7225     SDNode *BVN = N->getOperand(0).getNode();
7226     assert(BVN->getOpcode() == ISD::BUILD_VECTOR &&
7227            BVN->getValueType(0) == MVT::v4i32 && "expected v4i32 BUILD_VECTOR");
7228     unsigned LowElt = DAG.getDataLayout().isBigEndian() ? 1 : 0;
7229     return DAG.getBuildVector(
7230         MVT::v2i32, SDLoc(N),
7231         {BVN->getOperand(LowElt), BVN->getOperand(LowElt + 2)});
7232   }
7233   // Construct a new BUILD_VECTOR with elements truncated to half the size.
7234   assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
7235   EVT VT = N->getValueType(0);
7236   unsigned EltSize = VT.getScalarSizeInBits() / 2;
7237   unsigned NumElts = VT.getVectorNumElements();
7238   MVT TruncVT = MVT::getIntegerVT(EltSize);
7239   SmallVector<SDValue, 8> Ops;
7240   SDLoc dl(N);
7241   for (unsigned i = 0; i != NumElts; ++i) {
7242     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
7243     const APInt &CInt = C->getAPIntValue();
7244     // Element types smaller than 32 bits are not legal, so use i32 elements.
7245     // The values are implicitly truncated so sext vs. zext doesn't matter.
7246     Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
7247   }
7248   return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
7249 }
7250 
7251 static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
7252   unsigned Opcode = N->getOpcode();
7253   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7254     SDNode *N0 = N->getOperand(0).getNode();
7255     SDNode *N1 = N->getOperand(1).getNode();
7256     return N0->hasOneUse() && N1->hasOneUse() &&
7257       isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
7258   }
7259   return false;
7260 }
7261 
7262 static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
7263   unsigned Opcode = N->getOpcode();
7264   if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
7265     SDNode *N0 = N->getOperand(0).getNode();
7266     SDNode *N1 = N->getOperand(1).getNode();
7267     return N0->hasOneUse() && N1->hasOneUse() &&
7268       isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
7269   }
7270   return false;
7271 }
7272 
7273 static SDValue LowerMUL(SDValue Op, SelectionDAG &DAG) {
7274   // Multiplications are only custom-lowered for 128-bit vectors so that
7275   // VMULL can be detected.  Otherwise v2i64 multiplications are not legal.
7276   EVT VT = Op.getValueType();
7277   assert(VT.is128BitVector() && VT.isInteger() &&
7278          "unexpected type for custom-lowering ISD::MUL");
7279   SDNode *N0 = Op.getOperand(0).getNode();
7280   SDNode *N1 = Op.getOperand(1).getNode();
7281   unsigned NewOpc = 0;
7282   bool isMLA = false;
7283   bool isN0SExt = isSignExtended(N0, DAG);
7284   bool isN1SExt = isSignExtended(N1, DAG);
7285   if (isN0SExt && isN1SExt)
7286     NewOpc = ARMISD::VMULLs;
7287   else {
7288     bool isN0ZExt = isZeroExtended(N0, DAG);
7289     bool isN1ZExt = isZeroExtended(N1, DAG);
7290     if (isN0ZExt && isN1ZExt)
7291       NewOpc = ARMISD::VMULLu;
7292     else if (isN1SExt || isN1ZExt) {
7293       // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
7294       // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
7295       if (isN1SExt && isAddSubSExt(N0, DAG)) {
7296         NewOpc = ARMISD::VMULLs;
7297         isMLA = true;
7298       } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
7299         NewOpc = ARMISD::VMULLu;
7300         isMLA = true;
7301       } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
7302         std::swap(N0, N1);
7303         NewOpc = ARMISD::VMULLu;
7304         isMLA = true;
7305       }
7306     }
7307 
7308     if (!NewOpc) {
7309       if (VT == MVT::v2i64)
7310         // Fall through to expand this.  It is not legal.
7311         return SDValue();
7312       else
7313         // Other vector multiplications are legal.
7314         return Op;
7315     }
7316   }
7317 
7318   // Legalize to a VMULL instruction.
7319   SDLoc DL(Op);
7320   SDValue Op0;
7321   SDValue Op1 = SkipExtensionForVMULL(N1, DAG);
7322   if (!isMLA) {
7323     Op0 = SkipExtensionForVMULL(N0, DAG);
7324     assert(Op0.getValueType().is64BitVector() &&
7325            Op1.getValueType().is64BitVector() &&
7326            "unexpected types for extended operands to VMULL");
7327     return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
7328   }
7329 
7330   // Optimizing (zext A + zext B) * C, to (VMULL A, C) + (VMULL B, C) during
7331   // isel lowering to take advantage of no-stall back to back vmul + vmla.
7332   //   vmull q0, d4, d6
7333   //   vmlal q0, d5, d6
7334   // is faster than
7335   //   vaddl q0, d4, d5
7336   //   vmovl q1, d6
7337   //   vmul  q0, q0, q1
7338   SDValue N00 = SkipExtensionForVMULL(N0->getOperand(0).getNode(), DAG);
7339   SDValue N01 = SkipExtensionForVMULL(N0->getOperand(1).getNode(), DAG);
7340   EVT Op1VT = Op1.getValueType();
7341   return DAG.getNode(N0->getOpcode(), DL, VT,
7342                      DAG.getNode(NewOpc, DL, VT,
7343                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
7344                      DAG.getNode(NewOpc, DL, VT,
7345                                DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
7346 }
7347 
7348 static SDValue LowerSDIV_v4i8(SDValue X, SDValue Y, const SDLoc &dl,
7349                               SelectionDAG &DAG) {
7350   // TODO: Should this propagate fast-math-flags?
7351 
7352   // Convert to float
7353   // float4 xf = vcvt_f32_s32(vmovl_s16(a.lo));
7354   // float4 yf = vcvt_f32_s32(vmovl_s16(b.lo));
7355   X = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, X);
7356   Y = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, Y);
7357   X = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, X);
7358   Y = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, Y);
7359   // Get reciprocal estimate.
7360   // float4 recip = vrecpeq_f32(yf);
7361   Y = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7362                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7363                    Y);
7364   // Because char has a smaller range than uchar, we can actually get away
7365   // without any newton steps.  This requires that we use a weird bias
7366   // of 0xb000, however (again, this has been exhaustively tested).
7367   // float4 result = as_float4(as_int4(xf*recip) + 0xb000);
7368   X = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, X, Y);
7369   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, X);
7370   Y = DAG.getConstant(0xb000, dl, MVT::v4i32);
7371   X = DAG.getNode(ISD::ADD, dl, MVT::v4i32, X, Y);
7372   X = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, X);
7373   // Convert back to short.
7374   X = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, X);
7375   X = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, X);
7376   return X;
7377 }
7378 
7379 static SDValue LowerSDIV_v4i16(SDValue N0, SDValue N1, const SDLoc &dl,
7380                                SelectionDAG &DAG) {
7381   // TODO: Should this propagate fast-math-flags?
7382 
7383   SDValue N2;
7384   // Convert to float.
7385   // float4 yf = vcvt_f32_s32(vmovl_s16(y));
7386   // float4 xf = vcvt_f32_s32(vmovl_s16(x));
7387   N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N0);
7388   N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i32, N1);
7389   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7390   N1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7391 
7392   // Use reciprocal estimate and one refinement step.
7393   // float4 recip = vrecpeq_f32(yf);
7394   // recip *= vrecpsq_f32(yf, recip);
7395   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7396                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7397                    N1);
7398   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7399                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7400                    N1, N2);
7401   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7402   // Because short has a smaller range than ushort, we can actually get away
7403   // with only a single newton step.  This requires that we use a weird bias
7404   // of 89, however (again, this has been exhaustively tested).
7405   // float4 result = as_float4(as_int4(xf*recip) + 0x89);
7406   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7407   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7408   N1 = DAG.getConstant(0x89, dl, MVT::v4i32);
7409   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7410   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7411   // Convert back to integer and return.
7412   // return vmovn_s32(vcvt_s32_f32(result));
7413   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7414   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7415   return N0;
7416 }
7417 
7418 static SDValue LowerSDIV(SDValue Op, SelectionDAG &DAG) {
7419   EVT VT = Op.getValueType();
7420   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7421          "unexpected type for custom-lowering ISD::SDIV");
7422 
7423   SDLoc dl(Op);
7424   SDValue N0 = Op.getOperand(0);
7425   SDValue N1 = Op.getOperand(1);
7426   SDValue N2, N3;
7427 
7428   if (VT == MVT::v8i8) {
7429     N0 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N0);
7430     N1 = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i16, N1);
7431 
7432     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7433                      DAG.getIntPtrConstant(4, dl));
7434     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7435                      DAG.getIntPtrConstant(4, dl));
7436     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7437                      DAG.getIntPtrConstant(0, dl));
7438     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7439                      DAG.getIntPtrConstant(0, dl));
7440 
7441     N0 = LowerSDIV_v4i8(N0, N1, dl, DAG); // v4i16
7442     N2 = LowerSDIV_v4i8(N2, N3, dl, DAG); // v4i16
7443 
7444     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7445     N0 = LowerCONCAT_VECTORS(N0, DAG);
7446 
7447     N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v8i8, N0);
7448     return N0;
7449   }
7450   return LowerSDIV_v4i16(N0, N1, dl, DAG);
7451 }
7452 
7453 static SDValue LowerUDIV(SDValue Op, SelectionDAG &DAG) {
7454   // TODO: Should this propagate fast-math-flags?
7455   EVT VT = Op.getValueType();
7456   assert((VT == MVT::v4i16 || VT == MVT::v8i8) &&
7457          "unexpected type for custom-lowering ISD::UDIV");
7458 
7459   SDLoc dl(Op);
7460   SDValue N0 = Op.getOperand(0);
7461   SDValue N1 = Op.getOperand(1);
7462   SDValue N2, N3;
7463 
7464   if (VT == MVT::v8i8) {
7465     N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N0);
7466     N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v8i16, N1);
7467 
7468     N2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7469                      DAG.getIntPtrConstant(4, dl));
7470     N3 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7471                      DAG.getIntPtrConstant(4, dl));
7472     N0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N0,
7473                      DAG.getIntPtrConstant(0, dl));
7474     N1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MVT::v4i16, N1,
7475                      DAG.getIntPtrConstant(0, dl));
7476 
7477     N0 = LowerSDIV_v4i16(N0, N1, dl, DAG); // v4i16
7478     N2 = LowerSDIV_v4i16(N2, N3, dl, DAG); // v4i16
7479 
7480     N0 = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v8i16, N0, N2);
7481     N0 = LowerCONCAT_VECTORS(N0, DAG);
7482 
7483     N0 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v8i8,
7484                      DAG.getConstant(Intrinsic::arm_neon_vqmovnsu, dl,
7485                                      MVT::i32),
7486                      N0);
7487     return N0;
7488   }
7489 
7490   // v4i16 sdiv ... Convert to float.
7491   // float4 yf = vcvt_f32_s32(vmovl_u16(y));
7492   // float4 xf = vcvt_f32_s32(vmovl_u16(x));
7493   N0 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N0);
7494   N1 = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v4i32, N1);
7495   N0 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N0);
7496   SDValue BN1 = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::v4f32, N1);
7497 
7498   // Use reciprocal estimate and two refinement steps.
7499   // float4 recip = vrecpeq_f32(yf);
7500   // recip *= vrecpsq_f32(yf, recip);
7501   // recip *= vrecpsq_f32(yf, recip);
7502   N2 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7503                    DAG.getConstant(Intrinsic::arm_neon_vrecpe, dl, MVT::i32),
7504                    BN1);
7505   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7506                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7507                    BN1, N2);
7508   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7509   N1 = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, MVT::v4f32,
7510                    DAG.getConstant(Intrinsic::arm_neon_vrecps, dl, MVT::i32),
7511                    BN1, N2);
7512   N2 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N1, N2);
7513   // Simply multiplying by the reciprocal estimate can leave us a few ulps
7514   // too low, so we add 2 ulps (exhaustive testing shows that this is enough,
7515   // and that it will never cause us to return an answer too large).
7516   // float4 result = as_float4(as_int4(xf*recip) + 2);
7517   N0 = DAG.getNode(ISD::FMUL, dl, MVT::v4f32, N0, N2);
7518   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, N0);
7519   N1 = DAG.getConstant(2, dl, MVT::v4i32);
7520   N0 = DAG.getNode(ISD::ADD, dl, MVT::v4i32, N0, N1);
7521   N0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, N0);
7522   // Convert back to integer and return.
7523   // return vmovn_u32(vcvt_s32_f32(result));
7524   N0 = DAG.getNode(ISD::FP_TO_SINT, dl, MVT::v4i32, N0);
7525   N0 = DAG.getNode(ISD::TRUNCATE, dl, MVT::v4i16, N0);
7526   return N0;
7527 }
7528 
7529 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
7530   EVT VT = Op.getNode()->getValueType(0);
7531   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7532 
7533   unsigned Opc;
7534   bool ExtraOp = false;
7535   switch (Op.getOpcode()) {
7536   default: llvm_unreachable("Invalid code");
7537   case ISD::ADDC: Opc = ARMISD::ADDC; break;
7538   case ISD::ADDE: Opc = ARMISD::ADDE; ExtraOp = true; break;
7539   case ISD::SUBC: Opc = ARMISD::SUBC; break;
7540   case ISD::SUBE: Opc = ARMISD::SUBE; ExtraOp = true; break;
7541   }
7542 
7543   if (!ExtraOp)
7544     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7545                        Op.getOperand(1));
7546   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
7547                      Op.getOperand(1), Op.getOperand(2));
7548 }
7549 
7550 static SDValue LowerADDSUBCARRY(SDValue Op, SelectionDAG &DAG) {
7551   SDNode *N = Op.getNode();
7552   EVT VT = N->getValueType(0);
7553   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
7554 
7555   SDValue Carry = Op.getOperand(2);
7556   EVT CarryVT = Carry.getValueType();
7557 
7558   SDLoc DL(Op);
7559 
7560   APInt NegOne = APInt::getAllOnesValue(CarryVT.getScalarSizeInBits());
7561 
7562   SDValue Result;
7563   if (Op.getOpcode() == ISD::ADDCARRY) {
7564     // This converts the boolean value carry into the carry flag.
7565     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7566 
7567     // Do the addition proper using the carry flag we wanted.
7568     Result = DAG.getNode(ARMISD::ADDE, DL, VTs, Op.getOperand(0),
7569                          Op.getOperand(1), Carry.getValue(1));
7570 
7571     // Now convert the carry flag into a boolean value.
7572     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7573   } else {
7574     // ARMISD::SUBE expects a carry not a borrow like ISD::SUBCARRY so we
7575     // have to invert the carry first.
7576     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7577                         DAG.getConstant(1, DL, MVT::i32), Carry);
7578     // This converts the boolean value carry into the carry flag.
7579     Carry = ConvertBooleanCarryToCarryFlag(Carry, DAG);
7580 
7581     // Do the subtraction proper using the carry flag we wanted.
7582     Result = DAG.getNode(ARMISD::SUBE, DL, VTs, Op.getOperand(0),
7583                          Op.getOperand(1), Carry.getValue(1));
7584 
7585     // Now convert the carry flag into a boolean value.
7586     Carry = ConvertCarryFlagToBooleanCarry(Result.getValue(1), VT, DAG);
7587     // But the carry returned by ARMISD::SUBE is not a borrow as expected
7588     // by ISD::SUBCARRY, so compute 1 - C.
7589     Carry = DAG.getNode(ISD::SUB, DL, MVT::i32,
7590                         DAG.getConstant(1, DL, MVT::i32), Carry);
7591   }
7592 
7593   // Return both values.
7594   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Result, Carry);
7595 }
7596 
7597 SDValue ARMTargetLowering::LowerFSINCOS(SDValue Op, SelectionDAG &DAG) const {
7598   assert(Subtarget->isTargetDarwin());
7599 
7600   // For iOS, we want to call an alternative entry point: __sincos_stret,
7601   // return values are passed via sret.
7602   SDLoc dl(Op);
7603   SDValue Arg = Op.getOperand(0);
7604   EVT ArgVT = Arg.getValueType();
7605   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
7606   auto PtrVT = getPointerTy(DAG.getDataLayout());
7607 
7608   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
7609   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7610 
7611   // Pair of floats / doubles used to pass the result.
7612   Type *RetTy = StructType::get(ArgTy, ArgTy);
7613   auto &DL = DAG.getDataLayout();
7614 
7615   ArgListTy Args;
7616   bool ShouldUseSRet = Subtarget->isAPCS_ABI();
7617   SDValue SRet;
7618   if (ShouldUseSRet) {
7619     // Create stack object for sret.
7620     const uint64_t ByteSize = DL.getTypeAllocSize(RetTy);
7621     const unsigned StackAlign = DL.getPrefTypeAlignment(RetTy);
7622     int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
7623     SRet = DAG.getFrameIndex(FrameIdx, TLI.getPointerTy(DL));
7624 
7625     ArgListEntry Entry;
7626     Entry.Node = SRet;
7627     Entry.Ty = RetTy->getPointerTo();
7628     Entry.IsSExt = false;
7629     Entry.IsZExt = false;
7630     Entry.IsSRet = true;
7631     Args.push_back(Entry);
7632     RetTy = Type::getVoidTy(*DAG.getContext());
7633   }
7634 
7635   ArgListEntry Entry;
7636   Entry.Node = Arg;
7637   Entry.Ty = ArgTy;
7638   Entry.IsSExt = false;
7639   Entry.IsZExt = false;
7640   Args.push_back(Entry);
7641 
7642   RTLIB::Libcall LC =
7643       (ArgVT == MVT::f64) ? RTLIB::SINCOS_STRET_F64 : RTLIB::SINCOS_STRET_F32;
7644   const char *LibcallName = getLibcallName(LC);
7645   CallingConv::ID CC = getLibcallCallingConv(LC);
7646   SDValue Callee = DAG.getExternalSymbol(LibcallName, getPointerTy(DL));
7647 
7648   TargetLowering::CallLoweringInfo CLI(DAG);
7649   CLI.setDebugLoc(dl)
7650       .setChain(DAG.getEntryNode())
7651       .setCallee(CC, RetTy, Callee, std::move(Args))
7652       .setDiscardResult(ShouldUseSRet);
7653   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
7654 
7655   if (!ShouldUseSRet)
7656     return CallResult.first;
7657 
7658   SDValue LoadSin =
7659       DAG.getLoad(ArgVT, dl, CallResult.second, SRet, MachinePointerInfo());
7660 
7661   // Address of cos field.
7662   SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, SRet,
7663                             DAG.getIntPtrConstant(ArgVT.getStoreSize(), dl));
7664   SDValue LoadCos =
7665       DAG.getLoad(ArgVT, dl, LoadSin.getValue(1), Add, MachinePointerInfo());
7666 
7667   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
7668   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys,
7669                      LoadSin.getValue(0), LoadCos.getValue(0));
7670 }
7671 
7672 SDValue ARMTargetLowering::LowerWindowsDIVLibCall(SDValue Op, SelectionDAG &DAG,
7673                                                   bool Signed,
7674                                                   SDValue &Chain) const {
7675   EVT VT = Op.getValueType();
7676   assert((VT == MVT::i32 || VT == MVT::i64) &&
7677          "unexpected type for custom lowering DIV");
7678   SDLoc dl(Op);
7679 
7680   const auto &DL = DAG.getDataLayout();
7681   const auto &TLI = DAG.getTargetLoweringInfo();
7682 
7683   const char *Name = nullptr;
7684   if (Signed)
7685     Name = (VT == MVT::i32) ? "__rt_sdiv" : "__rt_sdiv64";
7686   else
7687     Name = (VT == MVT::i32) ? "__rt_udiv" : "__rt_udiv64";
7688 
7689   SDValue ES = DAG.getExternalSymbol(Name, TLI.getPointerTy(DL));
7690 
7691   ARMTargetLowering::ArgListTy Args;
7692 
7693   for (auto AI : {1, 0}) {
7694     ArgListEntry Arg;
7695     Arg.Node = Op.getOperand(AI);
7696     Arg.Ty = Arg.Node.getValueType().getTypeForEVT(*DAG.getContext());
7697     Args.push_back(Arg);
7698   }
7699 
7700   CallLoweringInfo CLI(DAG);
7701   CLI.setDebugLoc(dl)
7702     .setChain(Chain)
7703     .setCallee(CallingConv::ARM_AAPCS_VFP, VT.getTypeForEVT(*DAG.getContext()),
7704                ES, std::move(Args));
7705 
7706   return LowerCallTo(CLI).first;
7707 }
7708 
7709 SDValue ARMTargetLowering::LowerDIV_Windows(SDValue Op, SelectionDAG &DAG,
7710                                             bool Signed) const {
7711   assert(Op.getValueType() == MVT::i32 &&
7712          "unexpected type for custom lowering DIV");
7713   SDLoc dl(Op);
7714 
7715   SDValue DBZCHK = DAG.getNode(ARMISD::WIN__DBZCHK, dl, MVT::Other,
7716                                DAG.getEntryNode(), Op.getOperand(1));
7717 
7718   return LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7719 }
7720 
7721 static SDValue WinDBZCheckDenominator(SelectionDAG &DAG, SDNode *N, SDValue InChain) {
7722   SDLoc DL(N);
7723   SDValue Op = N->getOperand(1);
7724   if (N->getValueType(0) == MVT::i32)
7725     return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain, Op);
7726   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7727                            DAG.getConstant(0, DL, MVT::i32));
7728   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Op,
7729                            DAG.getConstant(1, DL, MVT::i32));
7730   return DAG.getNode(ARMISD::WIN__DBZCHK, DL, MVT::Other, InChain,
7731                      DAG.getNode(ISD::OR, DL, MVT::i32, Lo, Hi));
7732 }
7733 
7734 void ARMTargetLowering::ExpandDIV_Windows(
7735     SDValue Op, SelectionDAG &DAG, bool Signed,
7736     SmallVectorImpl<SDValue> &Results) const {
7737   const auto &DL = DAG.getDataLayout();
7738   const auto &TLI = DAG.getTargetLoweringInfo();
7739 
7740   assert(Op.getValueType() == MVT::i64 &&
7741          "unexpected type for custom lowering DIV");
7742   SDLoc dl(Op);
7743 
7744   SDValue DBZCHK = WinDBZCheckDenominator(DAG, Op.getNode(), DAG.getEntryNode());
7745 
7746   SDValue Result = LowerWindowsDIVLibCall(Op, DAG, Signed, DBZCHK);
7747 
7748   SDValue Lower = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Result);
7749   SDValue Upper = DAG.getNode(ISD::SRL, dl, MVT::i64, Result,
7750                               DAG.getConstant(32, dl, TLI.getPointerTy(DL)));
7751   Upper = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Upper);
7752 
7753   Results.push_back(Lower);
7754   Results.push_back(Upper);
7755 }
7756 
7757 static SDValue LowerAtomicLoadStore(SDValue Op, SelectionDAG &DAG) {
7758   if (isStrongerThanMonotonic(cast<AtomicSDNode>(Op)->getOrdering()))
7759     // Acquire/Release load/store is not legal for targets without a dmb or
7760     // equivalent available.
7761     return SDValue();
7762 
7763   // Monotonic load/store is legal for all targets.
7764   return Op;
7765 }
7766 
7767 static void ReplaceREADCYCLECOUNTER(SDNode *N,
7768                                     SmallVectorImpl<SDValue> &Results,
7769                                     SelectionDAG &DAG,
7770                                     const ARMSubtarget *Subtarget) {
7771   SDLoc DL(N);
7772   // Under Power Management extensions, the cycle-count is:
7773   //    mrc p15, #0, <Rt>, c9, c13, #0
7774   SDValue Ops[] = { N->getOperand(0), // Chain
7775                     DAG.getConstant(Intrinsic::arm_mrc, DL, MVT::i32),
7776                     DAG.getConstant(15, DL, MVT::i32),
7777                     DAG.getConstant(0, DL, MVT::i32),
7778                     DAG.getConstant(9, DL, MVT::i32),
7779                     DAG.getConstant(13, DL, MVT::i32),
7780                     DAG.getConstant(0, DL, MVT::i32)
7781   };
7782 
7783   SDValue Cycles32 = DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL,
7784                                  DAG.getVTList(MVT::i32, MVT::Other), Ops);
7785   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Cycles32,
7786                                 DAG.getConstant(0, DL, MVT::i32)));
7787   Results.push_back(Cycles32.getValue(1));
7788 }
7789 
7790 static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
7791   SDLoc dl(V.getNode());
7792   SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i32);
7793   SDValue VHi = DAG.getAnyExtOrTrunc(
7794       DAG.getNode(ISD::SRL, dl, MVT::i64, V, DAG.getConstant(32, dl, MVT::i32)),
7795       dl, MVT::i32);
7796   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7797   if (isBigEndian)
7798     std::swap (VLo, VHi);
7799   SDValue RegClass =
7800       DAG.getTargetConstant(ARM::GPRPairRegClassID, dl, MVT::i32);
7801   SDValue SubReg0 = DAG.getTargetConstant(ARM::gsub_0, dl, MVT::i32);
7802   SDValue SubReg1 = DAG.getTargetConstant(ARM::gsub_1, dl, MVT::i32);
7803   const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
7804   return SDValue(
7805       DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
7806 }
7807 
7808 static void ReplaceCMP_SWAP_64Results(SDNode *N,
7809                                        SmallVectorImpl<SDValue> & Results,
7810                                        SelectionDAG &DAG) {
7811   assert(N->getValueType(0) == MVT::i64 &&
7812          "AtomicCmpSwap on types less than 64 should be legal");
7813   SDValue Ops[] = {N->getOperand(1),
7814                    createGPRPairNode(DAG, N->getOperand(2)),
7815                    createGPRPairNode(DAG, N->getOperand(3)),
7816                    N->getOperand(0)};
7817   SDNode *CmpSwap = DAG.getMachineNode(
7818       ARM::CMP_SWAP_64, SDLoc(N),
7819       DAG.getVTList(MVT::Untyped, MVT::i32, MVT::Other), Ops);
7820 
7821   MachineFunction &MF = DAG.getMachineFunction();
7822   MachineSDNode::mmo_iterator MemOp = MF.allocateMemRefsArray(1);
7823   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
7824   cast<MachineSDNode>(CmpSwap)->setMemRefs(MemOp, MemOp + 1);
7825 
7826   bool isBigEndian = DAG.getDataLayout().isBigEndian();
7827 
7828   Results.push_back(
7829       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_1 : ARM::gsub_0,
7830                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7831   Results.push_back(
7832       DAG.getTargetExtractSubreg(isBigEndian ? ARM::gsub_0 : ARM::gsub_1,
7833                                  SDLoc(N), MVT::i32, SDValue(CmpSwap, 0)));
7834   Results.push_back(SDValue(CmpSwap, 2));
7835 }
7836 
7837 static SDValue LowerFPOWI(SDValue Op, const ARMSubtarget &Subtarget,
7838                           SelectionDAG &DAG) {
7839   const auto &TLI = DAG.getTargetLoweringInfo();
7840 
7841   assert(Subtarget.getTargetTriple().isOSMSVCRT() &&
7842          "Custom lowering is MSVCRT specific!");
7843 
7844   SDLoc dl(Op);
7845   SDValue Val = Op.getOperand(0);
7846   MVT Ty = Val->getSimpleValueType(0);
7847   SDValue Exponent = DAG.getNode(ISD::SINT_TO_FP, dl, Ty, Op.getOperand(1));
7848   SDValue Callee = DAG.getExternalSymbol(Ty == MVT::f32 ? "powf" : "pow",
7849                                          TLI.getPointerTy(DAG.getDataLayout()));
7850 
7851   TargetLowering::ArgListTy Args;
7852   TargetLowering::ArgListEntry Entry;
7853 
7854   Entry.Node = Val;
7855   Entry.Ty = Val.getValueType().getTypeForEVT(*DAG.getContext());
7856   Entry.IsZExt = true;
7857   Args.push_back(Entry);
7858 
7859   Entry.Node = Exponent;
7860   Entry.Ty = Exponent.getValueType().getTypeForEVT(*DAG.getContext());
7861   Entry.IsZExt = true;
7862   Args.push_back(Entry);
7863 
7864   Type *LCRTy = Val.getValueType().getTypeForEVT(*DAG.getContext());
7865 
7866   // In the in-chain to the call is the entry node  If we are emitting a
7867   // tailcall, the chain will be mutated if the node has a non-entry input
7868   // chain.
7869   SDValue InChain = DAG.getEntryNode();
7870   SDValue TCChain = InChain;
7871 
7872   const Function &F = DAG.getMachineFunction().getFunction();
7873   bool IsTC = TLI.isInTailCallPosition(DAG, Op.getNode(), TCChain) &&
7874               F.getReturnType() == LCRTy;
7875   if (IsTC)
7876     InChain = TCChain;
7877 
7878   TargetLowering::CallLoweringInfo CLI(DAG);
7879   CLI.setDebugLoc(dl)
7880       .setChain(InChain)
7881       .setCallee(CallingConv::ARM_AAPCS_VFP, LCRTy, Callee, std::move(Args))
7882       .setTailCall(IsTC);
7883   std::pair<SDValue, SDValue> CI = TLI.LowerCallTo(CLI);
7884 
7885   // Return the chain (the DAG root) if it is a tail call
7886   return !CI.second.getNode() ? DAG.getRoot() : CI.first;
7887 }
7888 
7889 SDValue ARMTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
7890   DEBUG(dbgs() << "Lowering node: "; Op.dump());
7891   switch (Op.getOpcode()) {
7892   default: llvm_unreachable("Don't know how to custom lower this!");
7893   case ISD::WRITE_REGISTER: return LowerWRITE_REGISTER(Op, DAG);
7894   case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
7895   case ISD::BlockAddress:  return LowerBlockAddress(Op, DAG);
7896   case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
7897   case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
7898   case ISD::SELECT:        return LowerSELECT(Op, DAG);
7899   case ISD::SELECT_CC:     return LowerSELECT_CC(Op, DAG);
7900   case ISD::BRCOND:        return LowerBRCOND(Op, DAG);
7901   case ISD::BR_CC:         return LowerBR_CC(Op, DAG);
7902   case ISD::BR_JT:         return LowerBR_JT(Op, DAG);
7903   case ISD::VASTART:       return LowerVASTART(Op, DAG);
7904   case ISD::ATOMIC_FENCE:  return LowerATOMIC_FENCE(Op, DAG, Subtarget);
7905   case ISD::PREFETCH:      return LowerPREFETCH(Op, DAG, Subtarget);
7906   case ISD::SINT_TO_FP:
7907   case ISD::UINT_TO_FP:    return LowerINT_TO_FP(Op, DAG);
7908   case ISD::FP_TO_SINT:
7909   case ISD::FP_TO_UINT:    return LowerFP_TO_INT(Op, DAG);
7910   case ISD::FCOPYSIGN:     return LowerFCOPYSIGN(Op, DAG);
7911   case ISD::RETURNADDR:    return LowerRETURNADDR(Op, DAG);
7912   case ISD::FRAMEADDR:     return LowerFRAMEADDR(Op, DAG);
7913   case ISD::EH_SJLJ_SETJMP: return LowerEH_SJLJ_SETJMP(Op, DAG);
7914   case ISD::EH_SJLJ_LONGJMP: return LowerEH_SJLJ_LONGJMP(Op, DAG);
7915   case ISD::EH_SJLJ_SETUP_DISPATCH: return LowerEH_SJLJ_SETUP_DISPATCH(Op, DAG);
7916   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG,
7917                                                                Subtarget);
7918   case ISD::BITCAST:       return ExpandBITCAST(Op.getNode(), DAG);
7919   case ISD::SHL:
7920   case ISD::SRL:
7921   case ISD::SRA:           return LowerShift(Op.getNode(), DAG, Subtarget);
7922   case ISD::SREM:          return LowerREM(Op.getNode(), DAG);
7923   case ISD::UREM:          return LowerREM(Op.getNode(), DAG);
7924   case ISD::SHL_PARTS:     return LowerShiftLeftParts(Op, DAG);
7925   case ISD::SRL_PARTS:
7926   case ISD::SRA_PARTS:     return LowerShiftRightParts(Op, DAG);
7927   case ISD::CTTZ:
7928   case ISD::CTTZ_ZERO_UNDEF: return LowerCTTZ(Op.getNode(), DAG, Subtarget);
7929   case ISD::CTPOP:         return LowerCTPOP(Op.getNode(), DAG, Subtarget);
7930   case ISD::SETCC:         return LowerVSETCC(Op, DAG);
7931   case ISD::SETCCE:        return LowerSETCCE(Op, DAG);
7932   case ISD::ConstantFP:    return LowerConstantFP(Op, DAG, Subtarget);
7933   case ISD::BUILD_VECTOR:  return LowerBUILD_VECTOR(Op, DAG, Subtarget);
7934   case ISD::VECTOR_SHUFFLE: return LowerVECTOR_SHUFFLE(Op, DAG);
7935   case ISD::INSERT_VECTOR_ELT: return LowerINSERT_VECTOR_ELT(Op, DAG);
7936   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
7937   case ISD::CONCAT_VECTORS: return LowerCONCAT_VECTORS(Op, DAG);
7938   case ISD::FLT_ROUNDS_:   return LowerFLT_ROUNDS_(Op, DAG);
7939   case ISD::MUL:           return LowerMUL(Op, DAG);
7940   case ISD::SDIV:
7941     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7942       return LowerDIV_Windows(Op, DAG, /* Signed */ true);
7943     return LowerSDIV(Op, DAG);
7944   case ISD::UDIV:
7945     if (Subtarget->isTargetWindows() && !Op.getValueType().isVector())
7946       return LowerDIV_Windows(Op, DAG, /* Signed */ false);
7947     return LowerUDIV(Op, DAG);
7948   case ISD::ADDC:
7949   case ISD::ADDE:
7950   case ISD::SUBC:
7951   case ISD::SUBE:          return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
7952   case ISD::ADDCARRY:
7953   case ISD::SUBCARRY:      return LowerADDSUBCARRY(Op, DAG);
7954   case ISD::SADDO:
7955   case ISD::SSUBO:
7956     return LowerSignedALUO(Op, DAG);
7957   case ISD::UADDO:
7958   case ISD::USUBO:
7959     return LowerUnsignedALUO(Op, DAG);
7960   case ISD::ATOMIC_LOAD:
7961   case ISD::ATOMIC_STORE:  return LowerAtomicLoadStore(Op, DAG);
7962   case ISD::FSINCOS:       return LowerFSINCOS(Op, DAG);
7963   case ISD::SDIVREM:
7964   case ISD::UDIVREM:       return LowerDivRem(Op, DAG);
7965   case ISD::DYNAMIC_STACKALLOC:
7966     if (Subtarget->isTargetWindows())
7967       return LowerDYNAMIC_STACKALLOC(Op, DAG);
7968     llvm_unreachable("Don't know how to custom lower this!");
7969   case ISD::FP_ROUND: return LowerFP_ROUND(Op, DAG);
7970   case ISD::FP_EXTEND: return LowerFP_EXTEND(Op, DAG);
7971   case ISD::FPOWI: return LowerFPOWI(Op, *Subtarget, DAG);
7972   case ARMISD::WIN__DBZCHK: return SDValue();
7973   }
7974 }
7975 
7976 static void ReplaceLongIntrinsic(SDNode *N, SmallVectorImpl<SDValue> &Results,
7977                                  SelectionDAG &DAG) {
7978   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
7979   unsigned Opc = 0;
7980   if (IntNo == Intrinsic::arm_smlald)
7981     Opc = ARMISD::SMLALD;
7982   else if (IntNo == Intrinsic::arm_smlaldx)
7983     Opc = ARMISD::SMLALDX;
7984   else if (IntNo == Intrinsic::arm_smlsld)
7985     Opc = ARMISD::SMLSLD;
7986   else if (IntNo == Intrinsic::arm_smlsldx)
7987     Opc = ARMISD::SMLSLDX;
7988   else
7989     return;
7990 
7991   SDLoc dl(N);
7992   SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7993                            N->getOperand(3),
7994                            DAG.getConstant(0, dl, MVT::i32));
7995   SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
7996                            N->getOperand(3),
7997                            DAG.getConstant(1, dl, MVT::i32));
7998 
7999   SDValue LongMul = DAG.getNode(Opc, dl,
8000                                 DAG.getVTList(MVT::i32, MVT::i32),
8001                                 N->getOperand(1), N->getOperand(2),
8002                                 Lo, Hi);
8003   Results.push_back(LongMul.getValue(0));
8004   Results.push_back(LongMul.getValue(1));
8005 }
8006 
8007 /// ReplaceNodeResults - Replace the results of node with an illegal result
8008 /// type with new values built out of custom code.
8009 void ARMTargetLowering::ReplaceNodeResults(SDNode *N,
8010                                            SmallVectorImpl<SDValue> &Results,
8011                                            SelectionDAG &DAG) const {
8012   SDValue Res;
8013   switch (N->getOpcode()) {
8014   default:
8015     llvm_unreachable("Don't know how to custom expand this!");
8016   case ISD::READ_REGISTER:
8017     ExpandREAD_REGISTER(N, Results, DAG);
8018     break;
8019   case ISD::BITCAST:
8020     Res = ExpandBITCAST(N, DAG);
8021     break;
8022   case ISD::SRL:
8023   case ISD::SRA:
8024     Res = Expand64BitShift(N, DAG, Subtarget);
8025     break;
8026   case ISD::SREM:
8027   case ISD::UREM:
8028     Res = LowerREM(N, DAG);
8029     break;
8030   case ISD::SDIVREM:
8031   case ISD::UDIVREM:
8032     Res = LowerDivRem(SDValue(N, 0), DAG);
8033     assert(Res.getNumOperands() == 2 && "DivRem needs two values");
8034     Results.push_back(Res.getValue(0));
8035     Results.push_back(Res.getValue(1));
8036     return;
8037   case ISD::READCYCLECOUNTER:
8038     ReplaceREADCYCLECOUNTER(N, Results, DAG, Subtarget);
8039     return;
8040   case ISD::UDIV:
8041   case ISD::SDIV:
8042     assert(Subtarget->isTargetWindows() && "can only expand DIV on Windows");
8043     return ExpandDIV_Windows(SDValue(N, 0), DAG, N->getOpcode() == ISD::SDIV,
8044                              Results);
8045   case ISD::ATOMIC_CMP_SWAP:
8046     ReplaceCMP_SWAP_64Results(N, Results, DAG);
8047     return;
8048   case ISD::INTRINSIC_WO_CHAIN:
8049     return ReplaceLongIntrinsic(N, Results, DAG);
8050   }
8051   if (Res.getNode())
8052     Results.push_back(Res);
8053 }
8054 
8055 //===----------------------------------------------------------------------===//
8056 //                           ARM Scheduler Hooks
8057 //===----------------------------------------------------------------------===//
8058 
8059 /// SetupEntryBlockForSjLj - Insert code into the entry block that creates and
8060 /// registers the function context.
8061 void ARMTargetLowering::SetupEntryBlockForSjLj(MachineInstr &MI,
8062                                                MachineBasicBlock *MBB,
8063                                                MachineBasicBlock *DispatchBB,
8064                                                int FI) const {
8065   assert(!Subtarget->isROPI() && !Subtarget->isRWPI() &&
8066          "ROPI/RWPI not currently supported with SjLj");
8067   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8068   DebugLoc dl = MI.getDebugLoc();
8069   MachineFunction *MF = MBB->getParent();
8070   MachineRegisterInfo *MRI = &MF->getRegInfo();
8071   MachineConstantPool *MCP = MF->getConstantPool();
8072   ARMFunctionInfo *AFI = MF->getInfo<ARMFunctionInfo>();
8073   const Function &F = MF->getFunction();
8074 
8075   bool isThumb = Subtarget->isThumb();
8076   bool isThumb2 = Subtarget->isThumb2();
8077 
8078   unsigned PCLabelId = AFI->createPICLabelUId();
8079   unsigned PCAdj = (isThumb || isThumb2) ? 4 : 8;
8080   ARMConstantPoolValue *CPV =
8081     ARMConstantPoolMBB::Create(F.getContext(), DispatchBB, PCLabelId, PCAdj);
8082   unsigned CPI = MCP->getConstantPoolIndex(CPV, 4);
8083 
8084   const TargetRegisterClass *TRC = isThumb ? &ARM::tGPRRegClass
8085                                            : &ARM::GPRRegClass;
8086 
8087   // Grab constant pool and fixed stack memory operands.
8088   MachineMemOperand *CPMMO =
8089       MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
8090                                MachineMemOperand::MOLoad, 4, 4);
8091 
8092   MachineMemOperand *FIMMOSt =
8093       MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI),
8094                                MachineMemOperand::MOStore, 4, 4);
8095 
8096   // Load the address of the dispatch MBB into the jump buffer.
8097   if (isThumb2) {
8098     // Incoming value: jbuf
8099     //   ldr.n  r5, LCPI1_1
8100     //   orr    r5, r5, #1
8101     //   add    r5, pc
8102     //   str    r5, [$jbuf, #+4] ; &jbuf[1]
8103     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8104     BuildMI(*MBB, MI, dl, TII->get(ARM::t2LDRpci), NewVReg1)
8105         .addConstantPoolIndex(CPI)
8106         .addMemOperand(CPMMO)
8107         .add(predOps(ARMCC::AL));
8108     // Set the low bit because of thumb mode.
8109     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8110     BuildMI(*MBB, MI, dl, TII->get(ARM::t2ORRri), NewVReg2)
8111         .addReg(NewVReg1, RegState::Kill)
8112         .addImm(0x01)
8113         .add(predOps(ARMCC::AL))
8114         .add(condCodeOp());
8115     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8116     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg3)
8117       .addReg(NewVReg2, RegState::Kill)
8118       .addImm(PCLabelId);
8119     BuildMI(*MBB, MI, dl, TII->get(ARM::t2STRi12))
8120         .addReg(NewVReg3, RegState::Kill)
8121         .addFrameIndex(FI)
8122         .addImm(36) // &jbuf[1] :: pc
8123         .addMemOperand(FIMMOSt)
8124         .add(predOps(ARMCC::AL));
8125   } else if (isThumb) {
8126     // Incoming value: jbuf
8127     //   ldr.n  r1, LCPI1_4
8128     //   add    r1, pc
8129     //   mov    r2, #1
8130     //   orrs   r1, r2
8131     //   add    r2, $jbuf, #+4 ; &jbuf[1]
8132     //   str    r1, [r2]
8133     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8134     BuildMI(*MBB, MI, dl, TII->get(ARM::tLDRpci), NewVReg1)
8135         .addConstantPoolIndex(CPI)
8136         .addMemOperand(CPMMO)
8137         .add(predOps(ARMCC::AL));
8138     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8139     BuildMI(*MBB, MI, dl, TII->get(ARM::tPICADD), NewVReg2)
8140       .addReg(NewVReg1, RegState::Kill)
8141       .addImm(PCLabelId);
8142     // Set the low bit because of thumb mode.
8143     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8144     BuildMI(*MBB, MI, dl, TII->get(ARM::tMOVi8), NewVReg3)
8145         .addReg(ARM::CPSR, RegState::Define)
8146         .addImm(1)
8147         .add(predOps(ARMCC::AL));
8148     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8149     BuildMI(*MBB, MI, dl, TII->get(ARM::tORR), NewVReg4)
8150         .addReg(ARM::CPSR, RegState::Define)
8151         .addReg(NewVReg2, RegState::Kill)
8152         .addReg(NewVReg3, RegState::Kill)
8153         .add(predOps(ARMCC::AL));
8154     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8155     BuildMI(*MBB, MI, dl, TII->get(ARM::tADDframe), NewVReg5)
8156             .addFrameIndex(FI)
8157             .addImm(36); // &jbuf[1] :: pc
8158     BuildMI(*MBB, MI, dl, TII->get(ARM::tSTRi))
8159         .addReg(NewVReg4, RegState::Kill)
8160         .addReg(NewVReg5, RegState::Kill)
8161         .addImm(0)
8162         .addMemOperand(FIMMOSt)
8163         .add(predOps(ARMCC::AL));
8164   } else {
8165     // Incoming value: jbuf
8166     //   ldr  r1, LCPI1_1
8167     //   add  r1, pc, r1
8168     //   str  r1, [$jbuf, #+4] ; &jbuf[1]
8169     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8170     BuildMI(*MBB, MI, dl, TII->get(ARM::LDRi12), NewVReg1)
8171         .addConstantPoolIndex(CPI)
8172         .addImm(0)
8173         .addMemOperand(CPMMO)
8174         .add(predOps(ARMCC::AL));
8175     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8176     BuildMI(*MBB, MI, dl, TII->get(ARM::PICADD), NewVReg2)
8177         .addReg(NewVReg1, RegState::Kill)
8178         .addImm(PCLabelId)
8179         .add(predOps(ARMCC::AL));
8180     BuildMI(*MBB, MI, dl, TII->get(ARM::STRi12))
8181         .addReg(NewVReg2, RegState::Kill)
8182         .addFrameIndex(FI)
8183         .addImm(36) // &jbuf[1] :: pc
8184         .addMemOperand(FIMMOSt)
8185         .add(predOps(ARMCC::AL));
8186   }
8187 }
8188 
8189 void ARMTargetLowering::EmitSjLjDispatchBlock(MachineInstr &MI,
8190                                               MachineBasicBlock *MBB) const {
8191   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8192   DebugLoc dl = MI.getDebugLoc();
8193   MachineFunction *MF = MBB->getParent();
8194   MachineRegisterInfo *MRI = &MF->getRegInfo();
8195   MachineFrameInfo &MFI = MF->getFrameInfo();
8196   int FI = MFI.getFunctionContextIndex();
8197 
8198   const TargetRegisterClass *TRC = Subtarget->isThumb() ? &ARM::tGPRRegClass
8199                                                         : &ARM::GPRnopcRegClass;
8200 
8201   // Get a mapping of the call site numbers to all of the landing pads they're
8202   // associated with.
8203   DenseMap<unsigned, SmallVector<MachineBasicBlock*, 2>> CallSiteNumToLPad;
8204   unsigned MaxCSNum = 0;
8205   for (MachineFunction::iterator BB = MF->begin(), E = MF->end(); BB != E;
8206        ++BB) {
8207     if (!BB->isEHPad()) continue;
8208 
8209     // FIXME: We should assert that the EH_LABEL is the first MI in the landing
8210     // pad.
8211     for (MachineBasicBlock::iterator
8212            II = BB->begin(), IE = BB->end(); II != IE; ++II) {
8213       if (!II->isEHLabel()) continue;
8214 
8215       MCSymbol *Sym = II->getOperand(0).getMCSymbol();
8216       if (!MF->hasCallSiteLandingPad(Sym)) continue;
8217 
8218       SmallVectorImpl<unsigned> &CallSiteIdxs = MF->getCallSiteLandingPad(Sym);
8219       for (SmallVectorImpl<unsigned>::iterator
8220              CSI = CallSiteIdxs.begin(), CSE = CallSiteIdxs.end();
8221            CSI != CSE; ++CSI) {
8222         CallSiteNumToLPad[*CSI].push_back(&*BB);
8223         MaxCSNum = std::max(MaxCSNum, *CSI);
8224       }
8225       break;
8226     }
8227   }
8228 
8229   // Get an ordered list of the machine basic blocks for the jump table.
8230   std::vector<MachineBasicBlock*> LPadList;
8231   SmallPtrSet<MachineBasicBlock*, 32> InvokeBBs;
8232   LPadList.reserve(CallSiteNumToLPad.size());
8233   for (unsigned I = 1; I <= MaxCSNum; ++I) {
8234     SmallVectorImpl<MachineBasicBlock*> &MBBList = CallSiteNumToLPad[I];
8235     for (SmallVectorImpl<MachineBasicBlock*>::iterator
8236            II = MBBList.begin(), IE = MBBList.end(); II != IE; ++II) {
8237       LPadList.push_back(*II);
8238       InvokeBBs.insert((*II)->pred_begin(), (*II)->pred_end());
8239     }
8240   }
8241 
8242   assert(!LPadList.empty() &&
8243          "No landing pad destinations for the dispatch jump table!");
8244 
8245   // Create the jump table and associated information.
8246   MachineJumpTableInfo *JTI =
8247     MF->getOrCreateJumpTableInfo(MachineJumpTableInfo::EK_Inline);
8248   unsigned MJTI = JTI->createJumpTableIndex(LPadList);
8249 
8250   // Create the MBBs for the dispatch code.
8251 
8252   // Shove the dispatch's address into the return slot in the function context.
8253   MachineBasicBlock *DispatchBB = MF->CreateMachineBasicBlock();
8254   DispatchBB->setIsEHPad();
8255 
8256   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
8257   unsigned trap_opcode;
8258   if (Subtarget->isThumb())
8259     trap_opcode = ARM::tTRAP;
8260   else
8261     trap_opcode = Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP;
8262 
8263   BuildMI(TrapBB, dl, TII->get(trap_opcode));
8264   DispatchBB->addSuccessor(TrapBB);
8265 
8266   MachineBasicBlock *DispContBB = MF->CreateMachineBasicBlock();
8267   DispatchBB->addSuccessor(DispContBB);
8268 
8269   // Insert and MBBs.
8270   MF->insert(MF->end(), DispatchBB);
8271   MF->insert(MF->end(), DispContBB);
8272   MF->insert(MF->end(), TrapBB);
8273 
8274   // Insert code into the entry block that creates and registers the function
8275   // context.
8276   SetupEntryBlockForSjLj(MI, MBB, DispatchBB, FI);
8277 
8278   MachineMemOperand *FIMMOLd = MF->getMachineMemOperand(
8279       MachinePointerInfo::getFixedStack(*MF, FI),
8280       MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile, 4, 4);
8281 
8282   MachineInstrBuilder MIB;
8283   MIB = BuildMI(DispatchBB, dl, TII->get(ARM::Int_eh_sjlj_dispatchsetup));
8284 
8285   const ARMBaseInstrInfo *AII = static_cast<const ARMBaseInstrInfo*>(TII);
8286   const ARMBaseRegisterInfo &RI = AII->getRegisterInfo();
8287 
8288   // Add a register mask with no preserved registers.  This results in all
8289   // registers being marked as clobbered. This can't work if the dispatch block
8290   // is in a Thumb1 function and is linked with ARM code which uses the FP
8291   // registers, as there is no way to preserve the FP registers in Thumb1 mode.
8292   MIB.addRegMask(RI.getSjLjDispatchPreservedMask(*MF));
8293 
8294   bool IsPositionIndependent = isPositionIndependent();
8295   unsigned NumLPads = LPadList.size();
8296   if (Subtarget->isThumb2()) {
8297     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8298     BuildMI(DispatchBB, dl, TII->get(ARM::t2LDRi12), NewVReg1)
8299         .addFrameIndex(FI)
8300         .addImm(4)
8301         .addMemOperand(FIMMOLd)
8302         .add(predOps(ARMCC::AL));
8303 
8304     if (NumLPads < 256) {
8305       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPri))
8306           .addReg(NewVReg1)
8307           .addImm(LPadList.size())
8308           .add(predOps(ARMCC::AL));
8309     } else {
8310       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8311       BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVi16), VReg1)
8312           .addImm(NumLPads & 0xFFFF)
8313           .add(predOps(ARMCC::AL));
8314 
8315       unsigned VReg2 = VReg1;
8316       if ((NumLPads & 0xFFFF0000) != 0) {
8317         VReg2 = MRI->createVirtualRegister(TRC);
8318         BuildMI(DispatchBB, dl, TII->get(ARM::t2MOVTi16), VReg2)
8319             .addReg(VReg1)
8320             .addImm(NumLPads >> 16)
8321             .add(predOps(ARMCC::AL));
8322       }
8323 
8324       BuildMI(DispatchBB, dl, TII->get(ARM::t2CMPrr))
8325           .addReg(NewVReg1)
8326           .addReg(VReg2)
8327           .add(predOps(ARMCC::AL));
8328     }
8329 
8330     BuildMI(DispatchBB, dl, TII->get(ARM::t2Bcc))
8331       .addMBB(TrapBB)
8332       .addImm(ARMCC::HI)
8333       .addReg(ARM::CPSR);
8334 
8335     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8336     BuildMI(DispContBB, dl, TII->get(ARM::t2LEApcrelJT), NewVReg3)
8337         .addJumpTableIndex(MJTI)
8338         .add(predOps(ARMCC::AL));
8339 
8340     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8341     BuildMI(DispContBB, dl, TII->get(ARM::t2ADDrs), NewVReg4)
8342         .addReg(NewVReg3, RegState::Kill)
8343         .addReg(NewVReg1)
8344         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8345         .add(predOps(ARMCC::AL))
8346         .add(condCodeOp());
8347 
8348     BuildMI(DispContBB, dl, TII->get(ARM::t2BR_JT))
8349       .addReg(NewVReg4, RegState::Kill)
8350       .addReg(NewVReg1)
8351       .addJumpTableIndex(MJTI);
8352   } else if (Subtarget->isThumb()) {
8353     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8354     BuildMI(DispatchBB, dl, TII->get(ARM::tLDRspi), NewVReg1)
8355         .addFrameIndex(FI)
8356         .addImm(1)
8357         .addMemOperand(FIMMOLd)
8358         .add(predOps(ARMCC::AL));
8359 
8360     if (NumLPads < 256) {
8361       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPi8))
8362           .addReg(NewVReg1)
8363           .addImm(NumLPads)
8364           .add(predOps(ARMCC::AL));
8365     } else {
8366       MachineConstantPool *ConstantPool = MF->getConstantPool();
8367       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8368       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8369 
8370       // MachineConstantPool wants an explicit alignment.
8371       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8372       if (Align == 0)
8373         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8374       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8375 
8376       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8377       BuildMI(DispatchBB, dl, TII->get(ARM::tLDRpci))
8378           .addReg(VReg1, RegState::Define)
8379           .addConstantPoolIndex(Idx)
8380           .add(predOps(ARMCC::AL));
8381       BuildMI(DispatchBB, dl, TII->get(ARM::tCMPr))
8382           .addReg(NewVReg1)
8383           .addReg(VReg1)
8384           .add(predOps(ARMCC::AL));
8385     }
8386 
8387     BuildMI(DispatchBB, dl, TII->get(ARM::tBcc))
8388       .addMBB(TrapBB)
8389       .addImm(ARMCC::HI)
8390       .addReg(ARM::CPSR);
8391 
8392     unsigned NewVReg2 = MRI->createVirtualRegister(TRC);
8393     BuildMI(DispContBB, dl, TII->get(ARM::tLSLri), NewVReg2)
8394         .addReg(ARM::CPSR, RegState::Define)
8395         .addReg(NewVReg1)
8396         .addImm(2)
8397         .add(predOps(ARMCC::AL));
8398 
8399     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8400     BuildMI(DispContBB, dl, TII->get(ARM::tLEApcrelJT), NewVReg3)
8401         .addJumpTableIndex(MJTI)
8402         .add(predOps(ARMCC::AL));
8403 
8404     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8405     BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg4)
8406         .addReg(ARM::CPSR, RegState::Define)
8407         .addReg(NewVReg2, RegState::Kill)
8408         .addReg(NewVReg3)
8409         .add(predOps(ARMCC::AL));
8410 
8411     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8412         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8413 
8414     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8415     BuildMI(DispContBB, dl, TII->get(ARM::tLDRi), NewVReg5)
8416         .addReg(NewVReg4, RegState::Kill)
8417         .addImm(0)
8418         .addMemOperand(JTMMOLd)
8419         .add(predOps(ARMCC::AL));
8420 
8421     unsigned NewVReg6 = NewVReg5;
8422     if (IsPositionIndependent) {
8423       NewVReg6 = MRI->createVirtualRegister(TRC);
8424       BuildMI(DispContBB, dl, TII->get(ARM::tADDrr), NewVReg6)
8425           .addReg(ARM::CPSR, RegState::Define)
8426           .addReg(NewVReg5, RegState::Kill)
8427           .addReg(NewVReg3)
8428           .add(predOps(ARMCC::AL));
8429     }
8430 
8431     BuildMI(DispContBB, dl, TII->get(ARM::tBR_JTr))
8432       .addReg(NewVReg6, RegState::Kill)
8433       .addJumpTableIndex(MJTI);
8434   } else {
8435     unsigned NewVReg1 = MRI->createVirtualRegister(TRC);
8436     BuildMI(DispatchBB, dl, TII->get(ARM::LDRi12), NewVReg1)
8437         .addFrameIndex(FI)
8438         .addImm(4)
8439         .addMemOperand(FIMMOLd)
8440         .add(predOps(ARMCC::AL));
8441 
8442     if (NumLPads < 256) {
8443       BuildMI(DispatchBB, dl, TII->get(ARM::CMPri))
8444           .addReg(NewVReg1)
8445           .addImm(NumLPads)
8446           .add(predOps(ARMCC::AL));
8447     } else if (Subtarget->hasV6T2Ops() && isUInt<16>(NumLPads)) {
8448       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8449       BuildMI(DispatchBB, dl, TII->get(ARM::MOVi16), VReg1)
8450           .addImm(NumLPads & 0xFFFF)
8451           .add(predOps(ARMCC::AL));
8452 
8453       unsigned VReg2 = VReg1;
8454       if ((NumLPads & 0xFFFF0000) != 0) {
8455         VReg2 = MRI->createVirtualRegister(TRC);
8456         BuildMI(DispatchBB, dl, TII->get(ARM::MOVTi16), VReg2)
8457             .addReg(VReg1)
8458             .addImm(NumLPads >> 16)
8459             .add(predOps(ARMCC::AL));
8460       }
8461 
8462       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8463           .addReg(NewVReg1)
8464           .addReg(VReg2)
8465           .add(predOps(ARMCC::AL));
8466     } else {
8467       MachineConstantPool *ConstantPool = MF->getConstantPool();
8468       Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8469       const Constant *C = ConstantInt::get(Int32Ty, NumLPads);
8470 
8471       // MachineConstantPool wants an explicit alignment.
8472       unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8473       if (Align == 0)
8474         Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8475       unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8476 
8477       unsigned VReg1 = MRI->createVirtualRegister(TRC);
8478       BuildMI(DispatchBB, dl, TII->get(ARM::LDRcp))
8479           .addReg(VReg1, RegState::Define)
8480           .addConstantPoolIndex(Idx)
8481           .addImm(0)
8482           .add(predOps(ARMCC::AL));
8483       BuildMI(DispatchBB, dl, TII->get(ARM::CMPrr))
8484           .addReg(NewVReg1)
8485           .addReg(VReg1, RegState::Kill)
8486           .add(predOps(ARMCC::AL));
8487     }
8488 
8489     BuildMI(DispatchBB, dl, TII->get(ARM::Bcc))
8490       .addMBB(TrapBB)
8491       .addImm(ARMCC::HI)
8492       .addReg(ARM::CPSR);
8493 
8494     unsigned NewVReg3 = MRI->createVirtualRegister(TRC);
8495     BuildMI(DispContBB, dl, TII->get(ARM::MOVsi), NewVReg3)
8496         .addReg(NewVReg1)
8497         .addImm(ARM_AM::getSORegOpc(ARM_AM::lsl, 2))
8498         .add(predOps(ARMCC::AL))
8499         .add(condCodeOp());
8500     unsigned NewVReg4 = MRI->createVirtualRegister(TRC);
8501     BuildMI(DispContBB, dl, TII->get(ARM::LEApcrelJT), NewVReg4)
8502         .addJumpTableIndex(MJTI)
8503         .add(predOps(ARMCC::AL));
8504 
8505     MachineMemOperand *JTMMOLd = MF->getMachineMemOperand(
8506         MachinePointerInfo::getJumpTable(*MF), MachineMemOperand::MOLoad, 4, 4);
8507     unsigned NewVReg5 = MRI->createVirtualRegister(TRC);
8508     BuildMI(DispContBB, dl, TII->get(ARM::LDRrs), NewVReg5)
8509         .addReg(NewVReg3, RegState::Kill)
8510         .addReg(NewVReg4)
8511         .addImm(0)
8512         .addMemOperand(JTMMOLd)
8513         .add(predOps(ARMCC::AL));
8514 
8515     if (IsPositionIndependent) {
8516       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTadd))
8517         .addReg(NewVReg5, RegState::Kill)
8518         .addReg(NewVReg4)
8519         .addJumpTableIndex(MJTI);
8520     } else {
8521       BuildMI(DispContBB, dl, TII->get(ARM::BR_JTr))
8522         .addReg(NewVReg5, RegState::Kill)
8523         .addJumpTableIndex(MJTI);
8524     }
8525   }
8526 
8527   // Add the jump table entries as successors to the MBB.
8528   SmallPtrSet<MachineBasicBlock*, 8> SeenMBBs;
8529   for (std::vector<MachineBasicBlock*>::iterator
8530          I = LPadList.begin(), E = LPadList.end(); I != E; ++I) {
8531     MachineBasicBlock *CurMBB = *I;
8532     if (SeenMBBs.insert(CurMBB).second)
8533       DispContBB->addSuccessor(CurMBB);
8534   }
8535 
8536   // N.B. the order the invoke BBs are processed in doesn't matter here.
8537   const MCPhysReg *SavedRegs = RI.getCalleeSavedRegs(MF);
8538   SmallVector<MachineBasicBlock*, 64> MBBLPads;
8539   for (MachineBasicBlock *BB : InvokeBBs) {
8540 
8541     // Remove the landing pad successor from the invoke block and replace it
8542     // with the new dispatch block.
8543     SmallVector<MachineBasicBlock*, 4> Successors(BB->succ_begin(),
8544                                                   BB->succ_end());
8545     while (!Successors.empty()) {
8546       MachineBasicBlock *SMBB = Successors.pop_back_val();
8547       if (SMBB->isEHPad()) {
8548         BB->removeSuccessor(SMBB);
8549         MBBLPads.push_back(SMBB);
8550       }
8551     }
8552 
8553     BB->addSuccessor(DispatchBB, BranchProbability::getZero());
8554     BB->normalizeSuccProbs();
8555 
8556     // Find the invoke call and mark all of the callee-saved registers as
8557     // 'implicit defined' so that they're spilled. This prevents code from
8558     // moving instructions to before the EH block, where they will never be
8559     // executed.
8560     for (MachineBasicBlock::reverse_iterator
8561            II = BB->rbegin(), IE = BB->rend(); II != IE; ++II) {
8562       if (!II->isCall()) continue;
8563 
8564       DenseMap<unsigned, bool> DefRegs;
8565       for (MachineInstr::mop_iterator
8566              OI = II->operands_begin(), OE = II->operands_end();
8567            OI != OE; ++OI) {
8568         if (!OI->isReg()) continue;
8569         DefRegs[OI->getReg()] = true;
8570       }
8571 
8572       MachineInstrBuilder MIB(*MF, &*II);
8573 
8574       for (unsigned i = 0; SavedRegs[i] != 0; ++i) {
8575         unsigned Reg = SavedRegs[i];
8576         if (Subtarget->isThumb2() &&
8577             !ARM::tGPRRegClass.contains(Reg) &&
8578             !ARM::hGPRRegClass.contains(Reg))
8579           continue;
8580         if (Subtarget->isThumb1Only() && !ARM::tGPRRegClass.contains(Reg))
8581           continue;
8582         if (!Subtarget->isThumb() && !ARM::GPRRegClass.contains(Reg))
8583           continue;
8584         if (!DefRegs[Reg])
8585           MIB.addReg(Reg, RegState::ImplicitDefine | RegState::Dead);
8586       }
8587 
8588       break;
8589     }
8590   }
8591 
8592   // Mark all former landing pads as non-landing pads. The dispatch is the only
8593   // landing pad now.
8594   for (SmallVectorImpl<MachineBasicBlock*>::iterator
8595          I = MBBLPads.begin(), E = MBBLPads.end(); I != E; ++I)
8596     (*I)->setIsEHPad(false);
8597 
8598   // The instruction is gone now.
8599   MI.eraseFromParent();
8600 }
8601 
8602 static
8603 MachineBasicBlock *OtherSucc(MachineBasicBlock *MBB, MachineBasicBlock *Succ) {
8604   for (MachineBasicBlock::succ_iterator I = MBB->succ_begin(),
8605        E = MBB->succ_end(); I != E; ++I)
8606     if (*I != Succ)
8607       return *I;
8608   llvm_unreachable("Expecting a BB with two successors!");
8609 }
8610 
8611 /// Return the load opcode for a given load size. If load size >= 8,
8612 /// neon opcode will be returned.
8613 static unsigned getLdOpcode(unsigned LdSize, bool IsThumb1, bool IsThumb2) {
8614   if (LdSize >= 8)
8615     return LdSize == 16 ? ARM::VLD1q32wb_fixed
8616                         : LdSize == 8 ? ARM::VLD1d32wb_fixed : 0;
8617   if (IsThumb1)
8618     return LdSize == 4 ? ARM::tLDRi
8619                        : LdSize == 2 ? ARM::tLDRHi
8620                                      : LdSize == 1 ? ARM::tLDRBi : 0;
8621   if (IsThumb2)
8622     return LdSize == 4 ? ARM::t2LDR_POST
8623                        : LdSize == 2 ? ARM::t2LDRH_POST
8624                                      : LdSize == 1 ? ARM::t2LDRB_POST : 0;
8625   return LdSize == 4 ? ARM::LDR_POST_IMM
8626                      : LdSize == 2 ? ARM::LDRH_POST
8627                                    : LdSize == 1 ? ARM::LDRB_POST_IMM : 0;
8628 }
8629 
8630 /// Return the store opcode for a given store size. If store size >= 8,
8631 /// neon opcode will be returned.
8632 static unsigned getStOpcode(unsigned StSize, bool IsThumb1, bool IsThumb2) {
8633   if (StSize >= 8)
8634     return StSize == 16 ? ARM::VST1q32wb_fixed
8635                         : StSize == 8 ? ARM::VST1d32wb_fixed : 0;
8636   if (IsThumb1)
8637     return StSize == 4 ? ARM::tSTRi
8638                        : StSize == 2 ? ARM::tSTRHi
8639                                      : StSize == 1 ? ARM::tSTRBi : 0;
8640   if (IsThumb2)
8641     return StSize == 4 ? ARM::t2STR_POST
8642                        : StSize == 2 ? ARM::t2STRH_POST
8643                                      : StSize == 1 ? ARM::t2STRB_POST : 0;
8644   return StSize == 4 ? ARM::STR_POST_IMM
8645                      : StSize == 2 ? ARM::STRH_POST
8646                                    : StSize == 1 ? ARM::STRB_POST_IMM : 0;
8647 }
8648 
8649 /// Emit a post-increment load operation with given size. The instructions
8650 /// will be added to BB at Pos.
8651 static void emitPostLd(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8652                        const TargetInstrInfo *TII, const DebugLoc &dl,
8653                        unsigned LdSize, unsigned Data, unsigned AddrIn,
8654                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8655   unsigned LdOpc = getLdOpcode(LdSize, IsThumb1, IsThumb2);
8656   assert(LdOpc != 0 && "Should have a load opcode");
8657   if (LdSize >= 8) {
8658     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8659         .addReg(AddrOut, RegState::Define)
8660         .addReg(AddrIn)
8661         .addImm(0)
8662         .add(predOps(ARMCC::AL));
8663   } else if (IsThumb1) {
8664     // load + update AddrIn
8665     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8666         .addReg(AddrIn)
8667         .addImm(0)
8668         .add(predOps(ARMCC::AL));
8669     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8670         .add(t1CondCodeOp())
8671         .addReg(AddrIn)
8672         .addImm(LdSize)
8673         .add(predOps(ARMCC::AL));
8674   } else if (IsThumb2) {
8675     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8676         .addReg(AddrOut, RegState::Define)
8677         .addReg(AddrIn)
8678         .addImm(LdSize)
8679         .add(predOps(ARMCC::AL));
8680   } else { // arm
8681     BuildMI(*BB, Pos, dl, TII->get(LdOpc), Data)
8682         .addReg(AddrOut, RegState::Define)
8683         .addReg(AddrIn)
8684         .addReg(0)
8685         .addImm(LdSize)
8686         .add(predOps(ARMCC::AL));
8687   }
8688 }
8689 
8690 /// Emit a post-increment store operation with given size. The instructions
8691 /// will be added to BB at Pos.
8692 static void emitPostSt(MachineBasicBlock *BB, MachineBasicBlock::iterator Pos,
8693                        const TargetInstrInfo *TII, const DebugLoc &dl,
8694                        unsigned StSize, unsigned Data, unsigned AddrIn,
8695                        unsigned AddrOut, bool IsThumb1, bool IsThumb2) {
8696   unsigned StOpc = getStOpcode(StSize, IsThumb1, IsThumb2);
8697   assert(StOpc != 0 && "Should have a store opcode");
8698   if (StSize >= 8) {
8699     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8700         .addReg(AddrIn)
8701         .addImm(0)
8702         .addReg(Data)
8703         .add(predOps(ARMCC::AL));
8704   } else if (IsThumb1) {
8705     // store + update AddrIn
8706     BuildMI(*BB, Pos, dl, TII->get(StOpc))
8707         .addReg(Data)
8708         .addReg(AddrIn)
8709         .addImm(0)
8710         .add(predOps(ARMCC::AL));
8711     BuildMI(*BB, Pos, dl, TII->get(ARM::tADDi8), AddrOut)
8712         .add(t1CondCodeOp())
8713         .addReg(AddrIn)
8714         .addImm(StSize)
8715         .add(predOps(ARMCC::AL));
8716   } else if (IsThumb2) {
8717     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8718         .addReg(Data)
8719         .addReg(AddrIn)
8720         .addImm(StSize)
8721         .add(predOps(ARMCC::AL));
8722   } else { // arm
8723     BuildMI(*BB, Pos, dl, TII->get(StOpc), AddrOut)
8724         .addReg(Data)
8725         .addReg(AddrIn)
8726         .addReg(0)
8727         .addImm(StSize)
8728         .add(predOps(ARMCC::AL));
8729   }
8730 }
8731 
8732 MachineBasicBlock *
8733 ARMTargetLowering::EmitStructByval(MachineInstr &MI,
8734                                    MachineBasicBlock *BB) const {
8735   // This pseudo instruction has 3 operands: dst, src, size
8736   // We expand it to a loop if size > Subtarget->getMaxInlineSizeThreshold().
8737   // Otherwise, we will generate unrolled scalar copies.
8738   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
8739   const BasicBlock *LLVM_BB = BB->getBasicBlock();
8740   MachineFunction::iterator It = ++BB->getIterator();
8741 
8742   unsigned dest = MI.getOperand(0).getReg();
8743   unsigned src = MI.getOperand(1).getReg();
8744   unsigned SizeVal = MI.getOperand(2).getImm();
8745   unsigned Align = MI.getOperand(3).getImm();
8746   DebugLoc dl = MI.getDebugLoc();
8747 
8748   MachineFunction *MF = BB->getParent();
8749   MachineRegisterInfo &MRI = MF->getRegInfo();
8750   unsigned UnitSize = 0;
8751   const TargetRegisterClass *TRC = nullptr;
8752   const TargetRegisterClass *VecTRC = nullptr;
8753 
8754   bool IsThumb1 = Subtarget->isThumb1Only();
8755   bool IsThumb2 = Subtarget->isThumb2();
8756   bool IsThumb = Subtarget->isThumb();
8757 
8758   if (Align & 1) {
8759     UnitSize = 1;
8760   } else if (Align & 2) {
8761     UnitSize = 2;
8762   } else {
8763     // Check whether we can use NEON instructions.
8764     if (!MF->getFunction().hasFnAttribute(Attribute::NoImplicitFloat) &&
8765         Subtarget->hasNEON()) {
8766       if ((Align % 16 == 0) && SizeVal >= 16)
8767         UnitSize = 16;
8768       else if ((Align % 8 == 0) && SizeVal >= 8)
8769         UnitSize = 8;
8770     }
8771     // Can't use NEON instructions.
8772     if (UnitSize == 0)
8773       UnitSize = 4;
8774   }
8775 
8776   // Select the correct opcode and register class for unit size load/store
8777   bool IsNeon = UnitSize >= 8;
8778   TRC = IsThumb ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
8779   if (IsNeon)
8780     VecTRC = UnitSize == 16 ? &ARM::DPairRegClass
8781                             : UnitSize == 8 ? &ARM::DPRRegClass
8782                                             : nullptr;
8783 
8784   unsigned BytesLeft = SizeVal % UnitSize;
8785   unsigned LoopSize = SizeVal - BytesLeft;
8786 
8787   if (SizeVal <= Subtarget->getMaxInlineSizeThreshold()) {
8788     // Use LDR and STR to copy.
8789     // [scratch, srcOut] = LDR_POST(srcIn, UnitSize)
8790     // [destOut] = STR_POST(scratch, destIn, UnitSize)
8791     unsigned srcIn = src;
8792     unsigned destIn = dest;
8793     for (unsigned i = 0; i < LoopSize; i+=UnitSize) {
8794       unsigned srcOut = MRI.createVirtualRegister(TRC);
8795       unsigned destOut = MRI.createVirtualRegister(TRC);
8796       unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8797       emitPostLd(BB, MI, TII, dl, UnitSize, scratch, srcIn, srcOut,
8798                  IsThumb1, IsThumb2);
8799       emitPostSt(BB, MI, TII, dl, UnitSize, scratch, destIn, destOut,
8800                  IsThumb1, IsThumb2);
8801       srcIn = srcOut;
8802       destIn = destOut;
8803     }
8804 
8805     // Handle the leftover bytes with LDRB and STRB.
8806     // [scratch, srcOut] = LDRB_POST(srcIn, 1)
8807     // [destOut] = STRB_POST(scratch, destIn, 1)
8808     for (unsigned i = 0; i < BytesLeft; i++) {
8809       unsigned srcOut = MRI.createVirtualRegister(TRC);
8810       unsigned destOut = MRI.createVirtualRegister(TRC);
8811       unsigned scratch = MRI.createVirtualRegister(TRC);
8812       emitPostLd(BB, MI, TII, dl, 1, scratch, srcIn, srcOut,
8813                  IsThumb1, IsThumb2);
8814       emitPostSt(BB, MI, TII, dl, 1, scratch, destIn, destOut,
8815                  IsThumb1, IsThumb2);
8816       srcIn = srcOut;
8817       destIn = destOut;
8818     }
8819     MI.eraseFromParent(); // The instruction is gone now.
8820     return BB;
8821   }
8822 
8823   // Expand the pseudo op to a loop.
8824   // thisMBB:
8825   //   ...
8826   //   movw varEnd, # --> with thumb2
8827   //   movt varEnd, #
8828   //   ldrcp varEnd, idx --> without thumb2
8829   //   fallthrough --> loopMBB
8830   // loopMBB:
8831   //   PHI varPhi, varEnd, varLoop
8832   //   PHI srcPhi, src, srcLoop
8833   //   PHI destPhi, dst, destLoop
8834   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8835   //   [destLoop] = STR_POST(scratch, destPhi, UnitSize)
8836   //   subs varLoop, varPhi, #UnitSize
8837   //   bne loopMBB
8838   //   fallthrough --> exitMBB
8839   // exitMBB:
8840   //   epilogue to handle left-over bytes
8841   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8842   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8843   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8844   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
8845   MF->insert(It, loopMBB);
8846   MF->insert(It, exitMBB);
8847 
8848   // Transfer the remainder of BB and its successor edges to exitMBB.
8849   exitMBB->splice(exitMBB->begin(), BB,
8850                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
8851   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
8852 
8853   // Load an immediate to varEnd.
8854   unsigned varEnd = MRI.createVirtualRegister(TRC);
8855   if (Subtarget->useMovt(*MF)) {
8856     unsigned Vtmp = varEnd;
8857     if ((LoopSize & 0xFFFF0000) != 0)
8858       Vtmp = MRI.createVirtualRegister(TRC);
8859     BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVi16 : ARM::MOVi16), Vtmp)
8860         .addImm(LoopSize & 0xFFFF)
8861         .add(predOps(ARMCC::AL));
8862 
8863     if ((LoopSize & 0xFFFF0000) != 0)
8864       BuildMI(BB, dl, TII->get(IsThumb ? ARM::t2MOVTi16 : ARM::MOVTi16), varEnd)
8865           .addReg(Vtmp)
8866           .addImm(LoopSize >> 16)
8867           .add(predOps(ARMCC::AL));
8868   } else {
8869     MachineConstantPool *ConstantPool = MF->getConstantPool();
8870     Type *Int32Ty = Type::getInt32Ty(MF->getFunction().getContext());
8871     const Constant *C = ConstantInt::get(Int32Ty, LoopSize);
8872 
8873     // MachineConstantPool wants an explicit alignment.
8874     unsigned Align = MF->getDataLayout().getPrefTypeAlignment(Int32Ty);
8875     if (Align == 0)
8876       Align = MF->getDataLayout().getTypeAllocSize(C->getType());
8877     unsigned Idx = ConstantPool->getConstantPoolIndex(C, Align);
8878 
8879     if (IsThumb)
8880       BuildMI(*BB, MI, dl, TII->get(ARM::tLDRpci))
8881           .addReg(varEnd, RegState::Define)
8882           .addConstantPoolIndex(Idx)
8883           .add(predOps(ARMCC::AL));
8884     else
8885       BuildMI(*BB, MI, dl, TII->get(ARM::LDRcp))
8886           .addReg(varEnd, RegState::Define)
8887           .addConstantPoolIndex(Idx)
8888           .addImm(0)
8889           .add(predOps(ARMCC::AL));
8890   }
8891   BB->addSuccessor(loopMBB);
8892 
8893   // Generate the loop body:
8894   //   varPhi = PHI(varLoop, varEnd)
8895   //   srcPhi = PHI(srcLoop, src)
8896   //   destPhi = PHI(destLoop, dst)
8897   MachineBasicBlock *entryBB = BB;
8898   BB = loopMBB;
8899   unsigned varLoop = MRI.createVirtualRegister(TRC);
8900   unsigned varPhi = MRI.createVirtualRegister(TRC);
8901   unsigned srcLoop = MRI.createVirtualRegister(TRC);
8902   unsigned srcPhi = MRI.createVirtualRegister(TRC);
8903   unsigned destLoop = MRI.createVirtualRegister(TRC);
8904   unsigned destPhi = MRI.createVirtualRegister(TRC);
8905 
8906   BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), varPhi)
8907     .addReg(varLoop).addMBB(loopMBB)
8908     .addReg(varEnd).addMBB(entryBB);
8909   BuildMI(BB, dl, TII->get(ARM::PHI), srcPhi)
8910     .addReg(srcLoop).addMBB(loopMBB)
8911     .addReg(src).addMBB(entryBB);
8912   BuildMI(BB, dl, TII->get(ARM::PHI), destPhi)
8913     .addReg(destLoop).addMBB(loopMBB)
8914     .addReg(dest).addMBB(entryBB);
8915 
8916   //   [scratch, srcLoop] = LDR_POST(srcPhi, UnitSize)
8917   //   [destLoop] = STR_POST(scratch, destPhi, UnitSiz)
8918   unsigned scratch = MRI.createVirtualRegister(IsNeon ? VecTRC : TRC);
8919   emitPostLd(BB, BB->end(), TII, dl, UnitSize, scratch, srcPhi, srcLoop,
8920              IsThumb1, IsThumb2);
8921   emitPostSt(BB, BB->end(), TII, dl, UnitSize, scratch, destPhi, destLoop,
8922              IsThumb1, IsThumb2);
8923 
8924   // Decrement loop variable by UnitSize.
8925   if (IsThumb1) {
8926     BuildMI(*BB, BB->end(), dl, TII->get(ARM::tSUBi8), varLoop)
8927         .add(t1CondCodeOp())
8928         .addReg(varPhi)
8929         .addImm(UnitSize)
8930         .add(predOps(ARMCC::AL));
8931   } else {
8932     MachineInstrBuilder MIB =
8933         BuildMI(*BB, BB->end(), dl,
8934                 TII->get(IsThumb2 ? ARM::t2SUBri : ARM::SUBri), varLoop);
8935     MIB.addReg(varPhi)
8936         .addImm(UnitSize)
8937         .add(predOps(ARMCC::AL))
8938         .add(condCodeOp());
8939     MIB->getOperand(5).setReg(ARM::CPSR);
8940     MIB->getOperand(5).setIsDef(true);
8941   }
8942   BuildMI(*BB, BB->end(), dl,
8943           TII->get(IsThumb1 ? ARM::tBcc : IsThumb2 ? ARM::t2Bcc : ARM::Bcc))
8944       .addMBB(loopMBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
8945 
8946   // loopMBB can loop back to loopMBB or fall through to exitMBB.
8947   BB->addSuccessor(loopMBB);
8948   BB->addSuccessor(exitMBB);
8949 
8950   // Add epilogue to handle BytesLeft.
8951   BB = exitMBB;
8952   auto StartOfExit = exitMBB->begin();
8953 
8954   //   [scratch, srcOut] = LDRB_POST(srcLoop, 1)
8955   //   [destOut] = STRB_POST(scratch, destLoop, 1)
8956   unsigned srcIn = srcLoop;
8957   unsigned destIn = destLoop;
8958   for (unsigned i = 0; i < BytesLeft; i++) {
8959     unsigned srcOut = MRI.createVirtualRegister(TRC);
8960     unsigned destOut = MRI.createVirtualRegister(TRC);
8961     unsigned scratch = MRI.createVirtualRegister(TRC);
8962     emitPostLd(BB, StartOfExit, TII, dl, 1, scratch, srcIn, srcOut,
8963                IsThumb1, IsThumb2);
8964     emitPostSt(BB, StartOfExit, TII, dl, 1, scratch, destIn, destOut,
8965                IsThumb1, IsThumb2);
8966     srcIn = srcOut;
8967     destIn = destOut;
8968   }
8969 
8970   MI.eraseFromParent(); // The instruction is gone now.
8971   return BB;
8972 }
8973 
8974 MachineBasicBlock *
8975 ARMTargetLowering::EmitLowered__chkstk(MachineInstr &MI,
8976                                        MachineBasicBlock *MBB) const {
8977   const TargetMachine &TM = getTargetMachine();
8978   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
8979   DebugLoc DL = MI.getDebugLoc();
8980 
8981   assert(Subtarget->isTargetWindows() &&
8982          "__chkstk is only supported on Windows");
8983   assert(Subtarget->isThumb2() && "Windows on ARM requires Thumb-2 mode");
8984 
8985   // __chkstk takes the number of words to allocate on the stack in R4, and
8986   // returns the stack adjustment in number of bytes in R4.  This will not
8987   // clober any other registers (other than the obvious lr).
8988   //
8989   // Although, technically, IP should be considered a register which may be
8990   // clobbered, the call itself will not touch it.  Windows on ARM is a pure
8991   // thumb-2 environment, so there is no interworking required.  As a result, we
8992   // do not expect a veneer to be emitted by the linker, clobbering IP.
8993   //
8994   // Each module receives its own copy of __chkstk, so no import thunk is
8995   // required, again, ensuring that IP is not clobbered.
8996   //
8997   // Finally, although some linkers may theoretically provide a trampoline for
8998   // out of range calls (which is quite common due to a 32M range limitation of
8999   // branches for Thumb), we can generate the long-call version via
9000   // -mcmodel=large, alleviating the need for the trampoline which may clobber
9001   // IP.
9002 
9003   switch (TM.getCodeModel()) {
9004   case CodeModel::Small:
9005   case CodeModel::Medium:
9006   case CodeModel::Kernel:
9007     BuildMI(*MBB, MI, DL, TII.get(ARM::tBL))
9008         .add(predOps(ARMCC::AL))
9009         .addExternalSymbol("__chkstk")
9010         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9011         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9012         .addReg(ARM::R12,
9013                 RegState::Implicit | RegState::Define | RegState::Dead)
9014         .addReg(ARM::CPSR,
9015                 RegState::Implicit | RegState::Define | RegState::Dead);
9016     break;
9017   case CodeModel::Large: {
9018     MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
9019     unsigned Reg = MRI.createVirtualRegister(&ARM::rGPRRegClass);
9020 
9021     BuildMI(*MBB, MI, DL, TII.get(ARM::t2MOVi32imm), Reg)
9022       .addExternalSymbol("__chkstk");
9023     BuildMI(*MBB, MI, DL, TII.get(ARM::tBLXr))
9024         .add(predOps(ARMCC::AL))
9025         .addReg(Reg, RegState::Kill)
9026         .addReg(ARM::R4, RegState::Implicit | RegState::Kill)
9027         .addReg(ARM::R4, RegState::Implicit | RegState::Define)
9028         .addReg(ARM::R12,
9029                 RegState::Implicit | RegState::Define | RegState::Dead)
9030         .addReg(ARM::CPSR,
9031                 RegState::Implicit | RegState::Define | RegState::Dead);
9032     break;
9033   }
9034   }
9035 
9036   BuildMI(*MBB, MI, DL, TII.get(ARM::t2SUBrr), ARM::SP)
9037       .addReg(ARM::SP, RegState::Kill)
9038       .addReg(ARM::R4, RegState::Kill)
9039       .setMIFlags(MachineInstr::FrameSetup)
9040       .add(predOps(ARMCC::AL))
9041       .add(condCodeOp());
9042 
9043   MI.eraseFromParent();
9044   return MBB;
9045 }
9046 
9047 MachineBasicBlock *
9048 ARMTargetLowering::EmitLowered__dbzchk(MachineInstr &MI,
9049                                        MachineBasicBlock *MBB) const {
9050   DebugLoc DL = MI.getDebugLoc();
9051   MachineFunction *MF = MBB->getParent();
9052   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9053 
9054   MachineBasicBlock *ContBB = MF->CreateMachineBasicBlock();
9055   MF->insert(++MBB->getIterator(), ContBB);
9056   ContBB->splice(ContBB->begin(), MBB,
9057                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
9058   ContBB->transferSuccessorsAndUpdatePHIs(MBB);
9059   MBB->addSuccessor(ContBB);
9060 
9061   MachineBasicBlock *TrapBB = MF->CreateMachineBasicBlock();
9062   BuildMI(TrapBB, DL, TII->get(ARM::t__brkdiv0));
9063   MF->push_back(TrapBB);
9064   MBB->addSuccessor(TrapBB);
9065 
9066   BuildMI(*MBB, MI, DL, TII->get(ARM::tCMPi8))
9067       .addReg(MI.getOperand(0).getReg())
9068       .addImm(0)
9069       .add(predOps(ARMCC::AL));
9070   BuildMI(*MBB, MI, DL, TII->get(ARM::t2Bcc))
9071       .addMBB(TrapBB)
9072       .addImm(ARMCC::EQ)
9073       .addReg(ARM::CPSR);
9074 
9075   MI.eraseFromParent();
9076   return ContBB;
9077 }
9078 
9079 MachineBasicBlock *
9080 ARMTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
9081                                                MachineBasicBlock *BB) const {
9082   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
9083   DebugLoc dl = MI.getDebugLoc();
9084   bool isThumb2 = Subtarget->isThumb2();
9085   switch (MI.getOpcode()) {
9086   default: {
9087     MI.print(errs());
9088     llvm_unreachable("Unexpected instr type to insert");
9089   }
9090 
9091   // Thumb1 post-indexed loads are really just single-register LDMs.
9092   case ARM::tLDR_postidx: {
9093     MachineOperand Def(MI.getOperand(1));
9094     if (TargetRegisterInfo::isPhysicalRegister(Def.getReg()))
9095       Def.setIsRenamable(false);
9096     BuildMI(*BB, MI, dl, TII->get(ARM::tLDMIA_UPD))
9097         .add(Def)  // Rn_wb
9098         .add(MI.getOperand(2))  // Rn
9099         .add(MI.getOperand(3))  // PredImm
9100         .add(MI.getOperand(4))  // PredReg
9101         .add(MI.getOperand(0)); // Rt
9102     MI.eraseFromParent();
9103     return BB;
9104   }
9105 
9106   // The Thumb2 pre-indexed stores have the same MI operands, they just
9107   // define them differently in the .td files from the isel patterns, so
9108   // they need pseudos.
9109   case ARM::t2STR_preidx:
9110     MI.setDesc(TII->get(ARM::t2STR_PRE));
9111     return BB;
9112   case ARM::t2STRB_preidx:
9113     MI.setDesc(TII->get(ARM::t2STRB_PRE));
9114     return BB;
9115   case ARM::t2STRH_preidx:
9116     MI.setDesc(TII->get(ARM::t2STRH_PRE));
9117     return BB;
9118 
9119   case ARM::STRi_preidx:
9120   case ARM::STRBi_preidx: {
9121     unsigned NewOpc = MI.getOpcode() == ARM::STRi_preidx ? ARM::STR_PRE_IMM
9122                                                          : ARM::STRB_PRE_IMM;
9123     // Decode the offset.
9124     unsigned Offset = MI.getOperand(4).getImm();
9125     bool isSub = ARM_AM::getAM2Op(Offset) == ARM_AM::sub;
9126     Offset = ARM_AM::getAM2Offset(Offset);
9127     if (isSub)
9128       Offset = -Offset;
9129 
9130     MachineMemOperand *MMO = *MI.memoperands_begin();
9131     BuildMI(*BB, MI, dl, TII->get(NewOpc))
9132         .add(MI.getOperand(0)) // Rn_wb
9133         .add(MI.getOperand(1)) // Rt
9134         .add(MI.getOperand(2)) // Rn
9135         .addImm(Offset)        // offset (skip GPR==zero_reg)
9136         .add(MI.getOperand(5)) // pred
9137         .add(MI.getOperand(6))
9138         .addMemOperand(MMO);
9139     MI.eraseFromParent();
9140     return BB;
9141   }
9142   case ARM::STRr_preidx:
9143   case ARM::STRBr_preidx:
9144   case ARM::STRH_preidx: {
9145     unsigned NewOpc;
9146     switch (MI.getOpcode()) {
9147     default: llvm_unreachable("unexpected opcode!");
9148     case ARM::STRr_preidx: NewOpc = ARM::STR_PRE_REG; break;
9149     case ARM::STRBr_preidx: NewOpc = ARM::STRB_PRE_REG; break;
9150     case ARM::STRH_preidx: NewOpc = ARM::STRH_PRE; break;
9151     }
9152     MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(NewOpc));
9153     for (unsigned i = 0; i < MI.getNumOperands(); ++i)
9154       MIB.add(MI.getOperand(i));
9155     MI.eraseFromParent();
9156     return BB;
9157   }
9158 
9159   case ARM::tMOVCCr_pseudo: {
9160     // To "insert" a SELECT_CC instruction, we actually have to insert the
9161     // diamond control-flow pattern.  The incoming instruction knows the
9162     // destination vreg to set, the condition code register to branch on, the
9163     // true/false values to select between, and a branch opcode to use.
9164     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9165     MachineFunction::iterator It = ++BB->getIterator();
9166 
9167     //  thisMBB:
9168     //  ...
9169     //   TrueVal = ...
9170     //   cmpTY ccX, r1, r2
9171     //   bCC copy1MBB
9172     //   fallthrough --> copy0MBB
9173     MachineBasicBlock *thisMBB  = BB;
9174     MachineFunction *F = BB->getParent();
9175     MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
9176     MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
9177     F->insert(It, copy0MBB);
9178     F->insert(It, sinkMBB);
9179 
9180     // Transfer the remainder of BB and its successor edges to sinkMBB.
9181     sinkMBB->splice(sinkMBB->begin(), BB,
9182                     std::next(MachineBasicBlock::iterator(MI)), BB->end());
9183     sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
9184 
9185     BB->addSuccessor(copy0MBB);
9186     BB->addSuccessor(sinkMBB);
9187 
9188     BuildMI(BB, dl, TII->get(ARM::tBcc))
9189         .addMBB(sinkMBB)
9190         .addImm(MI.getOperand(3).getImm())
9191         .addReg(MI.getOperand(4).getReg());
9192 
9193     //  copy0MBB:
9194     //   %FalseValue = ...
9195     //   # fallthrough to sinkMBB
9196     BB = copy0MBB;
9197 
9198     // Update machine-CFG edges
9199     BB->addSuccessor(sinkMBB);
9200 
9201     //  sinkMBB:
9202     //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
9203     //  ...
9204     BB = sinkMBB;
9205     BuildMI(*BB, BB->begin(), dl, TII->get(ARM::PHI), MI.getOperand(0).getReg())
9206         .addReg(MI.getOperand(1).getReg())
9207         .addMBB(copy0MBB)
9208         .addReg(MI.getOperand(2).getReg())
9209         .addMBB(thisMBB);
9210 
9211     MI.eraseFromParent(); // The pseudo instruction is gone now.
9212     return BB;
9213   }
9214 
9215   case ARM::BCCi64:
9216   case ARM::BCCZi64: {
9217     // If there is an unconditional branch to the other successor, remove it.
9218     BB->erase(std::next(MachineBasicBlock::iterator(MI)), BB->end());
9219 
9220     // Compare both parts that make up the double comparison separately for
9221     // equality.
9222     bool RHSisZero = MI.getOpcode() == ARM::BCCZi64;
9223 
9224     unsigned LHS1 = MI.getOperand(1).getReg();
9225     unsigned LHS2 = MI.getOperand(2).getReg();
9226     if (RHSisZero) {
9227       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9228           .addReg(LHS1)
9229           .addImm(0)
9230           .add(predOps(ARMCC::AL));
9231       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9232         .addReg(LHS2).addImm(0)
9233         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9234     } else {
9235       unsigned RHS1 = MI.getOperand(3).getReg();
9236       unsigned RHS2 = MI.getOperand(4).getReg();
9237       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9238           .addReg(LHS1)
9239           .addReg(RHS1)
9240           .add(predOps(ARMCC::AL));
9241       BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPrr : ARM::CMPrr))
9242         .addReg(LHS2).addReg(RHS2)
9243         .addImm(ARMCC::EQ).addReg(ARM::CPSR);
9244     }
9245 
9246     MachineBasicBlock *destMBB = MI.getOperand(RHSisZero ? 3 : 5).getMBB();
9247     MachineBasicBlock *exitMBB = OtherSucc(BB, destMBB);
9248     if (MI.getOperand(0).getImm() == ARMCC::NE)
9249       std::swap(destMBB, exitMBB);
9250 
9251     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc))
9252       .addMBB(destMBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
9253     if (isThumb2)
9254       BuildMI(BB, dl, TII->get(ARM::t2B))
9255           .addMBB(exitMBB)
9256           .add(predOps(ARMCC::AL));
9257     else
9258       BuildMI(BB, dl, TII->get(ARM::B)) .addMBB(exitMBB);
9259 
9260     MI.eraseFromParent(); // The pseudo instruction is gone now.
9261     return BB;
9262   }
9263 
9264   case ARM::Int_eh_sjlj_setjmp:
9265   case ARM::Int_eh_sjlj_setjmp_nofp:
9266   case ARM::tInt_eh_sjlj_setjmp:
9267   case ARM::t2Int_eh_sjlj_setjmp:
9268   case ARM::t2Int_eh_sjlj_setjmp_nofp:
9269     return BB;
9270 
9271   case ARM::Int_eh_sjlj_setup_dispatch:
9272     EmitSjLjDispatchBlock(MI, BB);
9273     return BB;
9274 
9275   case ARM::ABS:
9276   case ARM::t2ABS: {
9277     // To insert an ABS instruction, we have to insert the
9278     // diamond control-flow pattern.  The incoming instruction knows the
9279     // source vreg to test against 0, the destination vreg to set,
9280     // the condition code register to branch on, the
9281     // true/false values to select between, and a branch opcode to use.
9282     // It transforms
9283     //     V1 = ABS V0
9284     // into
9285     //     V2 = MOVS V0
9286     //     BCC                      (branch to SinkBB if V0 >= 0)
9287     //     RSBBB: V3 = RSBri V2, 0  (compute ABS if V2 < 0)
9288     //     SinkBB: V1 = PHI(V2, V3)
9289     const BasicBlock *LLVM_BB = BB->getBasicBlock();
9290     MachineFunction::iterator BBI = ++BB->getIterator();
9291     MachineFunction *Fn = BB->getParent();
9292     MachineBasicBlock *RSBBB = Fn->CreateMachineBasicBlock(LLVM_BB);
9293     MachineBasicBlock *SinkBB  = Fn->CreateMachineBasicBlock(LLVM_BB);
9294     Fn->insert(BBI, RSBBB);
9295     Fn->insert(BBI, SinkBB);
9296 
9297     unsigned int ABSSrcReg = MI.getOperand(1).getReg();
9298     unsigned int ABSDstReg = MI.getOperand(0).getReg();
9299     bool ABSSrcKIll = MI.getOperand(1).isKill();
9300     bool isThumb2 = Subtarget->isThumb2();
9301     MachineRegisterInfo &MRI = Fn->getRegInfo();
9302     // In Thumb mode S must not be specified if source register is the SP or
9303     // PC and if destination register is the SP, so restrict register class
9304     unsigned NewRsbDstReg =
9305       MRI.createVirtualRegister(isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass);
9306 
9307     // Transfer the remainder of BB and its successor edges to sinkMBB.
9308     SinkBB->splice(SinkBB->begin(), BB,
9309                    std::next(MachineBasicBlock::iterator(MI)), BB->end());
9310     SinkBB->transferSuccessorsAndUpdatePHIs(BB);
9311 
9312     BB->addSuccessor(RSBBB);
9313     BB->addSuccessor(SinkBB);
9314 
9315     // fall through to SinkMBB
9316     RSBBB->addSuccessor(SinkBB);
9317 
9318     // insert a cmp at the end of BB
9319     BuildMI(BB, dl, TII->get(isThumb2 ? ARM::t2CMPri : ARM::CMPri))
9320         .addReg(ABSSrcReg)
9321         .addImm(0)
9322         .add(predOps(ARMCC::AL));
9323 
9324     // insert a bcc with opposite CC to ARMCC::MI at the end of BB
9325     BuildMI(BB, dl,
9326       TII->get(isThumb2 ? ARM::t2Bcc : ARM::Bcc)).addMBB(SinkBB)
9327       .addImm(ARMCC::getOppositeCondition(ARMCC::MI)).addReg(ARM::CPSR);
9328 
9329     // insert rsbri in RSBBB
9330     // Note: BCC and rsbri will be converted into predicated rsbmi
9331     // by if-conversion pass
9332     BuildMI(*RSBBB, RSBBB->begin(), dl,
9333             TII->get(isThumb2 ? ARM::t2RSBri : ARM::RSBri), NewRsbDstReg)
9334         .addReg(ABSSrcReg, ABSSrcKIll ? RegState::Kill : 0)
9335         .addImm(0)
9336         .add(predOps(ARMCC::AL))
9337         .add(condCodeOp());
9338 
9339     // insert PHI in SinkBB,
9340     // reuse ABSDstReg to not change uses of ABS instruction
9341     BuildMI(*SinkBB, SinkBB->begin(), dl,
9342       TII->get(ARM::PHI), ABSDstReg)
9343       .addReg(NewRsbDstReg).addMBB(RSBBB)
9344       .addReg(ABSSrcReg).addMBB(BB);
9345 
9346     // remove ABS instruction
9347     MI.eraseFromParent();
9348 
9349     // return last added BB
9350     return SinkBB;
9351   }
9352   case ARM::COPY_STRUCT_BYVAL_I32:
9353     ++NumLoopByVals;
9354     return EmitStructByval(MI, BB);
9355   case ARM::WIN__CHKSTK:
9356     return EmitLowered__chkstk(MI, BB);
9357   case ARM::WIN__DBZCHK:
9358     return EmitLowered__dbzchk(MI, BB);
9359   }
9360 }
9361 
9362 /// \brief Attaches vregs to MEMCPY that it will use as scratch registers
9363 /// when it is expanded into LDM/STM. This is done as a post-isel lowering
9364 /// instead of as a custom inserter because we need the use list from the SDNode.
9365 static void attachMEMCPYScratchRegs(const ARMSubtarget *Subtarget,
9366                                     MachineInstr &MI, const SDNode *Node) {
9367   bool isThumb1 = Subtarget->isThumb1Only();
9368 
9369   DebugLoc DL = MI.getDebugLoc();
9370   MachineFunction *MF = MI.getParent()->getParent();
9371   MachineRegisterInfo &MRI = MF->getRegInfo();
9372   MachineInstrBuilder MIB(*MF, MI);
9373 
9374   // If the new dst/src is unused mark it as dead.
9375   if (!Node->hasAnyUseOfValue(0)) {
9376     MI.getOperand(0).setIsDead(true);
9377   }
9378   if (!Node->hasAnyUseOfValue(1)) {
9379     MI.getOperand(1).setIsDead(true);
9380   }
9381 
9382   // The MEMCPY both defines and kills the scratch registers.
9383   for (unsigned I = 0; I != MI.getOperand(4).getImm(); ++I) {
9384     unsigned TmpReg = MRI.createVirtualRegister(isThumb1 ? &ARM::tGPRRegClass
9385                                                          : &ARM::GPRRegClass);
9386     MIB.addReg(TmpReg, RegState::Define|RegState::Dead);
9387   }
9388 }
9389 
9390 void ARMTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9391                                                       SDNode *Node) const {
9392   if (MI.getOpcode() == ARM::MEMCPY) {
9393     attachMEMCPYScratchRegs(Subtarget, MI, Node);
9394     return;
9395   }
9396 
9397   const MCInstrDesc *MCID = &MI.getDesc();
9398   // Adjust potentially 's' setting instructions after isel, i.e. ADC, SBC, RSB,
9399   // RSC. Coming out of isel, they have an implicit CPSR def, but the optional
9400   // operand is still set to noreg. If needed, set the optional operand's
9401   // register to CPSR, and remove the redundant implicit def.
9402   //
9403   // e.g. ADCS (..., implicit-def CPSR) -> ADC (... opt:def CPSR).
9404 
9405   // Rename pseudo opcodes.
9406   unsigned NewOpc = convertAddSubFlagsOpcode(MI.getOpcode());
9407   unsigned ccOutIdx;
9408   if (NewOpc) {
9409     const ARMBaseInstrInfo *TII = Subtarget->getInstrInfo();
9410     MCID = &TII->get(NewOpc);
9411 
9412     assert(MCID->getNumOperands() ==
9413            MI.getDesc().getNumOperands() + 5 - MI.getDesc().getSize()
9414         && "converted opcode should be the same except for cc_out"
9415            " (and, on Thumb1, pred)");
9416 
9417     MI.setDesc(*MCID);
9418 
9419     // Add the optional cc_out operand
9420     MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/true));
9421 
9422     // On Thumb1, move all input operands to the end, then add the predicate
9423     if (Subtarget->isThumb1Only()) {
9424       for (unsigned c = MCID->getNumOperands() - 4; c--;) {
9425         MI.addOperand(MI.getOperand(1));
9426         MI.RemoveOperand(1);
9427       }
9428 
9429       // Restore the ties
9430       for (unsigned i = MI.getNumOperands(); i--;) {
9431         const MachineOperand& op = MI.getOperand(i);
9432         if (op.isReg() && op.isUse()) {
9433           int DefIdx = MCID->getOperandConstraint(i, MCOI::TIED_TO);
9434           if (DefIdx != -1)
9435             MI.tieOperands(DefIdx, i);
9436         }
9437       }
9438 
9439       MI.addOperand(MachineOperand::CreateImm(ARMCC::AL));
9440       MI.addOperand(MachineOperand::CreateReg(0, /*isDef=*/false));
9441       ccOutIdx = 1;
9442     } else
9443       ccOutIdx = MCID->getNumOperands() - 1;
9444   } else
9445     ccOutIdx = MCID->getNumOperands() - 1;
9446 
9447   // Any ARM instruction that sets the 's' bit should specify an optional
9448   // "cc_out" operand in the last operand position.
9449   if (!MI.hasOptionalDef() || !MCID->OpInfo[ccOutIdx].isOptionalDef()) {
9450     assert(!NewOpc && "Optional cc_out operand required");
9451     return;
9452   }
9453   // Look for an implicit def of CPSR added by MachineInstr ctor. Remove it
9454   // since we already have an optional CPSR def.
9455   bool definesCPSR = false;
9456   bool deadCPSR = false;
9457   for (unsigned i = MCID->getNumOperands(), e = MI.getNumOperands(); i != e;
9458        ++i) {
9459     const MachineOperand &MO = MI.getOperand(i);
9460     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR) {
9461       definesCPSR = true;
9462       if (MO.isDead())
9463         deadCPSR = true;
9464       MI.RemoveOperand(i);
9465       break;
9466     }
9467   }
9468   if (!definesCPSR) {
9469     assert(!NewOpc && "Optional cc_out operand required");
9470     return;
9471   }
9472   assert(deadCPSR == !Node->hasAnyUseOfValue(1) && "inconsistent dead flag");
9473   if (deadCPSR) {
9474     assert(!MI.getOperand(ccOutIdx).getReg() &&
9475            "expect uninitialized optional cc_out operand");
9476     // Thumb1 instructions must have the S bit even if the CPSR is dead.
9477     if (!Subtarget->isThumb1Only())
9478       return;
9479   }
9480 
9481   // If this instruction was defined with an optional CPSR def and its dag node
9482   // had a live implicit CPSR def, then activate the optional CPSR def.
9483   MachineOperand &MO = MI.getOperand(ccOutIdx);
9484   MO.setReg(ARM::CPSR);
9485   MO.setIsDef(true);
9486 }
9487 
9488 //===----------------------------------------------------------------------===//
9489 //                           ARM Optimization Hooks
9490 //===----------------------------------------------------------------------===//
9491 
9492 // Helper function that checks if N is a null or all ones constant.
9493 static inline bool isZeroOrAllOnes(SDValue N, bool AllOnes) {
9494   return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
9495 }
9496 
9497 // Return true if N is conditionally 0 or all ones.
9498 // Detects these expressions where cc is an i1 value:
9499 //
9500 //   (select cc 0, y)   [AllOnes=0]
9501 //   (select cc y, 0)   [AllOnes=0]
9502 //   (zext cc)          [AllOnes=0]
9503 //   (sext cc)          [AllOnes=0/1]
9504 //   (select cc -1, y)  [AllOnes=1]
9505 //   (select cc y, -1)  [AllOnes=1]
9506 //
9507 // Invert is set when N is the null/all ones constant when CC is false.
9508 // OtherOp is set to the alternative value of N.
9509 static bool isConditionalZeroOrAllOnes(SDNode *N, bool AllOnes,
9510                                        SDValue &CC, bool &Invert,
9511                                        SDValue &OtherOp,
9512                                        SelectionDAG &DAG) {
9513   switch (N->getOpcode()) {
9514   default: return false;
9515   case ISD::SELECT: {
9516     CC = N->getOperand(0);
9517     SDValue N1 = N->getOperand(1);
9518     SDValue N2 = N->getOperand(2);
9519     if (isZeroOrAllOnes(N1, AllOnes)) {
9520       Invert = false;
9521       OtherOp = N2;
9522       return true;
9523     }
9524     if (isZeroOrAllOnes(N2, AllOnes)) {
9525       Invert = true;
9526       OtherOp = N1;
9527       return true;
9528     }
9529     return false;
9530   }
9531   case ISD::ZERO_EXTEND:
9532     // (zext cc) can never be the all ones value.
9533     if (AllOnes)
9534       return false;
9535     LLVM_FALLTHROUGH;
9536   case ISD::SIGN_EXTEND: {
9537     SDLoc dl(N);
9538     EVT VT = N->getValueType(0);
9539     CC = N->getOperand(0);
9540     if (CC.getValueType() != MVT::i1 || CC.getOpcode() != ISD::SETCC)
9541       return false;
9542     Invert = !AllOnes;
9543     if (AllOnes)
9544       // When looking for an AllOnes constant, N is an sext, and the 'other'
9545       // value is 0.
9546       OtherOp = DAG.getConstant(0, dl, VT);
9547     else if (N->getOpcode() == ISD::ZERO_EXTEND)
9548       // When looking for a 0 constant, N can be zext or sext.
9549       OtherOp = DAG.getConstant(1, dl, VT);
9550     else
9551       OtherOp = DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), dl,
9552                                 VT);
9553     return true;
9554   }
9555   }
9556 }
9557 
9558 // Combine a constant select operand into its use:
9559 //
9560 //   (add (select cc, 0, c), x)  -> (select cc, x, (add, x, c))
9561 //   (sub x, (select cc, 0, c))  -> (select cc, x, (sub, x, c))
9562 //   (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))  [AllOnes=1]
9563 //   (or  (select cc, 0, c), x)  -> (select cc, x, (or, x, c))
9564 //   (xor (select cc, 0, c), x)  -> (select cc, x, (xor, x, c))
9565 //
9566 // The transform is rejected if the select doesn't have a constant operand that
9567 // is null, or all ones when AllOnes is set.
9568 //
9569 // Also recognize sext/zext from i1:
9570 //
9571 //   (add (zext cc), x) -> (select cc (add x, 1), x)
9572 //   (add (sext cc), x) -> (select cc (add x, -1), x)
9573 //
9574 // These transformations eventually create predicated instructions.
9575 //
9576 // @param N       The node to transform.
9577 // @param Slct    The N operand that is a select.
9578 // @param OtherOp The other N operand (x above).
9579 // @param DCI     Context.
9580 // @param AllOnes Require the select constant to be all ones instead of null.
9581 // @returns The new node, or SDValue() on failure.
9582 static
9583 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
9584                             TargetLowering::DAGCombinerInfo &DCI,
9585                             bool AllOnes = false) {
9586   SelectionDAG &DAG = DCI.DAG;
9587   EVT VT = N->getValueType(0);
9588   SDValue NonConstantVal;
9589   SDValue CCOp;
9590   bool SwapSelectOps;
9591   if (!isConditionalZeroOrAllOnes(Slct.getNode(), AllOnes, CCOp, SwapSelectOps,
9592                                   NonConstantVal, DAG))
9593     return SDValue();
9594 
9595   // Slct is now know to be the desired identity constant when CC is true.
9596   SDValue TrueVal = OtherOp;
9597   SDValue FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
9598                                  OtherOp, NonConstantVal);
9599   // Unless SwapSelectOps says CC should be false.
9600   if (SwapSelectOps)
9601     std::swap(TrueVal, FalseVal);
9602 
9603   return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
9604                      CCOp, TrueVal, FalseVal);
9605 }
9606 
9607 // Attempt combineSelectAndUse on each operand of a commutative operator N.
9608 static
9609 SDValue combineSelectAndUseCommutative(SDNode *N, bool AllOnes,
9610                                        TargetLowering::DAGCombinerInfo &DCI) {
9611   SDValue N0 = N->getOperand(0);
9612   SDValue N1 = N->getOperand(1);
9613   if (N0.getNode()->hasOneUse())
9614     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI, AllOnes))
9615       return Result;
9616   if (N1.getNode()->hasOneUse())
9617     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI, AllOnes))
9618       return Result;
9619   return SDValue();
9620 }
9621 
9622 static bool IsVUZPShuffleNode(SDNode *N) {
9623   // VUZP shuffle node.
9624   if (N->getOpcode() == ARMISD::VUZP)
9625     return true;
9626 
9627   // "VUZP" on i32 is an alias for VTRN.
9628   if (N->getOpcode() == ARMISD::VTRN && N->getValueType(0) == MVT::v2i32)
9629     return true;
9630 
9631   return false;
9632 }
9633 
9634 static SDValue AddCombineToVPADD(SDNode *N, SDValue N0, SDValue N1,
9635                                  TargetLowering::DAGCombinerInfo &DCI,
9636                                  const ARMSubtarget *Subtarget) {
9637   // Look for ADD(VUZP.0, VUZP.1).
9638   if (!IsVUZPShuffleNode(N0.getNode()) || N0.getNode() != N1.getNode() ||
9639       N0 == N1)
9640    return SDValue();
9641 
9642   // Make sure the ADD is a 64-bit add; there is no 128-bit VPADD.
9643   if (!N->getValueType(0).is64BitVector())
9644     return SDValue();
9645 
9646   // Generate vpadd.
9647   SelectionDAG &DAG = DCI.DAG;
9648   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9649   SDLoc dl(N);
9650   SDNode *Unzip = N0.getNode();
9651   EVT VT = N->getValueType(0);
9652 
9653   SmallVector<SDValue, 8> Ops;
9654   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpadd, dl,
9655                                 TLI.getPointerTy(DAG.getDataLayout())));
9656   Ops.push_back(Unzip->getOperand(0));
9657   Ops.push_back(Unzip->getOperand(1));
9658 
9659   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9660 }
9661 
9662 static SDValue AddCombineVUZPToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9663                                       TargetLowering::DAGCombinerInfo &DCI,
9664                                       const ARMSubtarget *Subtarget) {
9665   // Check for two extended operands.
9666   if (!(N0.getOpcode() == ISD::SIGN_EXTEND &&
9667         N1.getOpcode() == ISD::SIGN_EXTEND) &&
9668       !(N0.getOpcode() == ISD::ZERO_EXTEND &&
9669         N1.getOpcode() == ISD::ZERO_EXTEND))
9670     return SDValue();
9671 
9672   SDValue N00 = N0.getOperand(0);
9673   SDValue N10 = N1.getOperand(0);
9674 
9675   // Look for ADD(SEXT(VUZP.0), SEXT(VUZP.1))
9676   if (!IsVUZPShuffleNode(N00.getNode()) || N00.getNode() != N10.getNode() ||
9677       N00 == N10)
9678     return SDValue();
9679 
9680   // We only recognize Q register paddl here; this can't be reached until
9681   // after type legalization.
9682   if (!N00.getValueType().is64BitVector() ||
9683       !N0.getValueType().is128BitVector())
9684     return SDValue();
9685 
9686   // Generate vpaddl.
9687   SelectionDAG &DAG = DCI.DAG;
9688   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9689   SDLoc dl(N);
9690   EVT VT = N->getValueType(0);
9691 
9692   SmallVector<SDValue, 8> Ops;
9693   // Form vpaddl.sN or vpaddl.uN depending on the kind of extension.
9694   unsigned Opcode;
9695   if (N0.getOpcode() == ISD::SIGN_EXTEND)
9696     Opcode = Intrinsic::arm_neon_vpaddls;
9697   else
9698     Opcode = Intrinsic::arm_neon_vpaddlu;
9699   Ops.push_back(DAG.getConstant(Opcode, dl,
9700                                 TLI.getPointerTy(DAG.getDataLayout())));
9701   EVT ElemTy = N00.getValueType().getVectorElementType();
9702   unsigned NumElts = VT.getVectorNumElements();
9703   EVT ConcatVT = EVT::getVectorVT(*DAG.getContext(), ElemTy, NumElts * 2);
9704   SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), ConcatVT,
9705                                N00.getOperand(0), N00.getOperand(1));
9706   Ops.push_back(Concat);
9707 
9708   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, Ops);
9709 }
9710 
9711 // FIXME: This function shouldn't be necessary; if we lower BUILD_VECTOR in
9712 // an appropriate manner, we end up with ADD(VUZP(ZEXT(N))), which is
9713 // much easier to match.
9714 static SDValue
9715 AddCombineBUILD_VECTORToVPADDL(SDNode *N, SDValue N0, SDValue N1,
9716                                TargetLowering::DAGCombinerInfo &DCI,
9717                                const ARMSubtarget *Subtarget) {
9718   // Only perform optimization if after legalize, and if NEON is available. We
9719   // also expected both operands to be BUILD_VECTORs.
9720   if (DCI.isBeforeLegalize() || !Subtarget->hasNEON()
9721       || N0.getOpcode() != ISD::BUILD_VECTOR
9722       || N1.getOpcode() != ISD::BUILD_VECTOR)
9723     return SDValue();
9724 
9725   // Check output type since VPADDL operand elements can only be 8, 16, or 32.
9726   EVT VT = N->getValueType(0);
9727   if (!VT.isInteger() || VT.getVectorElementType() == MVT::i64)
9728     return SDValue();
9729 
9730   // Check that the vector operands are of the right form.
9731   // N0 and N1 are BUILD_VECTOR nodes with N number of EXTRACT_VECTOR
9732   // operands, where N is the size of the formed vector.
9733   // Each EXTRACT_VECTOR should have the same input vector and odd or even
9734   // index such that we have a pair wise add pattern.
9735 
9736   // Grab the vector that all EXTRACT_VECTOR nodes should be referencing.
9737   if (N0->getOperand(0)->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9738     return SDValue();
9739   SDValue Vec = N0->getOperand(0)->getOperand(0);
9740   SDNode *V = Vec.getNode();
9741   unsigned nextIndex = 0;
9742 
9743   // For each operands to the ADD which are BUILD_VECTORs,
9744   // check to see if each of their operands are an EXTRACT_VECTOR with
9745   // the same vector and appropriate index.
9746   for (unsigned i = 0, e = N0->getNumOperands(); i != e; ++i) {
9747     if (N0->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT
9748         && N1->getOperand(i)->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
9749 
9750       SDValue ExtVec0 = N0->getOperand(i);
9751       SDValue ExtVec1 = N1->getOperand(i);
9752 
9753       // First operand is the vector, verify its the same.
9754       if (V != ExtVec0->getOperand(0).getNode() ||
9755           V != ExtVec1->getOperand(0).getNode())
9756         return SDValue();
9757 
9758       // Second is the constant, verify its correct.
9759       ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(ExtVec0->getOperand(1));
9760       ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(ExtVec1->getOperand(1));
9761 
9762       // For the constant, we want to see all the even or all the odd.
9763       if (!C0 || !C1 || C0->getZExtValue() != nextIndex
9764           || C1->getZExtValue() != nextIndex+1)
9765         return SDValue();
9766 
9767       // Increment index.
9768       nextIndex+=2;
9769     } else
9770       return SDValue();
9771   }
9772 
9773   // Don't generate vpaddl+vmovn; we'll match it to vpadd later. Also make sure
9774   // we're using the entire input vector, otherwise there's a size/legality
9775   // mismatch somewhere.
9776   if (nextIndex != Vec.getValueType().getVectorNumElements() ||
9777       Vec.getValueType().getVectorElementType() == VT.getVectorElementType())
9778     return SDValue();
9779 
9780   // Create VPADDL node.
9781   SelectionDAG &DAG = DCI.DAG;
9782   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9783 
9784   SDLoc dl(N);
9785 
9786   // Build operand list.
9787   SmallVector<SDValue, 8> Ops;
9788   Ops.push_back(DAG.getConstant(Intrinsic::arm_neon_vpaddls, dl,
9789                                 TLI.getPointerTy(DAG.getDataLayout())));
9790 
9791   // Input is the vector.
9792   Ops.push_back(Vec);
9793 
9794   // Get widened type and narrowed type.
9795   MVT widenType;
9796   unsigned numElem = VT.getVectorNumElements();
9797 
9798   EVT inputLaneType = Vec.getValueType().getVectorElementType();
9799   switch (inputLaneType.getSimpleVT().SimpleTy) {
9800     case MVT::i8: widenType = MVT::getVectorVT(MVT::i16, numElem); break;
9801     case MVT::i16: widenType = MVT::getVectorVT(MVT::i32, numElem); break;
9802     case MVT::i32: widenType = MVT::getVectorVT(MVT::i64, numElem); break;
9803     default:
9804       llvm_unreachable("Invalid vector element type for padd optimization.");
9805   }
9806 
9807   SDValue tmp = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, widenType, Ops);
9808   unsigned ExtOp = VT.bitsGT(tmp.getValueType()) ? ISD::ANY_EXTEND : ISD::TRUNCATE;
9809   return DAG.getNode(ExtOp, dl, VT, tmp);
9810 }
9811 
9812 static SDValue findMUL_LOHI(SDValue V) {
9813   if (V->getOpcode() == ISD::UMUL_LOHI ||
9814       V->getOpcode() == ISD::SMUL_LOHI)
9815     return V;
9816   return SDValue();
9817 }
9818 
9819 static SDValue AddCombineTo64BitSMLAL16(SDNode *AddcNode, SDNode *AddeNode,
9820                                         TargetLowering::DAGCombinerInfo &DCI,
9821                                         const ARMSubtarget *Subtarget) {
9822   if (Subtarget->isThumb()) {
9823     if (!Subtarget->hasDSP())
9824       return SDValue();
9825   } else if (!Subtarget->hasV5TEOps())
9826     return SDValue();
9827 
9828   // SMLALBB, SMLALBT, SMLALTB, SMLALTT multiply two 16-bit values and
9829   // accumulates the product into a 64-bit value. The 16-bit values will
9830   // be sign extended somehow or SRA'd into 32-bit values
9831   // (addc (adde (mul 16bit, 16bit), lo), hi)
9832   SDValue Mul = AddcNode->getOperand(0);
9833   SDValue Lo = AddcNode->getOperand(1);
9834   if (Mul.getOpcode() != ISD::MUL) {
9835     Lo = AddcNode->getOperand(0);
9836     Mul = AddcNode->getOperand(1);
9837     if (Mul.getOpcode() != ISD::MUL)
9838       return SDValue();
9839   }
9840 
9841   SDValue SRA = AddeNode->getOperand(0);
9842   SDValue Hi = AddeNode->getOperand(1);
9843   if (SRA.getOpcode() != ISD::SRA) {
9844     SRA = AddeNode->getOperand(1);
9845     Hi = AddeNode->getOperand(0);
9846     if (SRA.getOpcode() != ISD::SRA)
9847       return SDValue();
9848   }
9849   if (auto Const = dyn_cast<ConstantSDNode>(SRA.getOperand(1))) {
9850     if (Const->getZExtValue() != 31)
9851       return SDValue();
9852   } else
9853     return SDValue();
9854 
9855   if (SRA.getOperand(0) != Mul)
9856     return SDValue();
9857 
9858   SelectionDAG &DAG = DCI.DAG;
9859   SDLoc dl(AddcNode);
9860   unsigned Opcode = 0;
9861   SDValue Op0;
9862   SDValue Op1;
9863 
9864   if (isS16(Mul.getOperand(0), DAG) && isS16(Mul.getOperand(1), DAG)) {
9865     Opcode = ARMISD::SMLALBB;
9866     Op0 = Mul.getOperand(0);
9867     Op1 = Mul.getOperand(1);
9868   } else if (isS16(Mul.getOperand(0), DAG) && isSRA16(Mul.getOperand(1))) {
9869     Opcode = ARMISD::SMLALBT;
9870     Op0 = Mul.getOperand(0);
9871     Op1 = Mul.getOperand(1).getOperand(0);
9872   } else if (isSRA16(Mul.getOperand(0)) && isS16(Mul.getOperand(1), DAG)) {
9873     Opcode = ARMISD::SMLALTB;
9874     Op0 = Mul.getOperand(0).getOperand(0);
9875     Op1 = Mul.getOperand(1);
9876   } else if (isSRA16(Mul.getOperand(0)) && isSRA16(Mul.getOperand(1))) {
9877     Opcode = ARMISD::SMLALTT;
9878     Op0 = Mul->getOperand(0).getOperand(0);
9879     Op1 = Mul->getOperand(1).getOperand(0);
9880   }
9881 
9882   if (!Op0 || !Op1)
9883     return SDValue();
9884 
9885   SDValue SMLAL = DAG.getNode(Opcode, dl, DAG.getVTList(MVT::i32, MVT::i32),
9886                               Op0, Op1, Lo, Hi);
9887   // Replace the ADDs' nodes uses by the MLA node's values.
9888   SDValue HiMLALResult(SMLAL.getNode(), 1);
9889   SDValue LoMLALResult(SMLAL.getNode(), 0);
9890 
9891   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), LoMLALResult);
9892   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), HiMLALResult);
9893 
9894   // Return original node to notify the driver to stop replacing.
9895   SDValue resNode(AddcNode, 0);
9896   return resNode;
9897 }
9898 
9899 static SDValue AddCombineTo64bitMLAL(SDNode *AddeSubeNode,
9900                                      TargetLowering::DAGCombinerInfo &DCI,
9901                                      const ARMSubtarget *Subtarget) {
9902   // Look for multiply add opportunities.
9903   // The pattern is a ISD::UMUL_LOHI followed by two add nodes, where
9904   // each add nodes consumes a value from ISD::UMUL_LOHI and there is
9905   // a glue link from the first add to the second add.
9906   // If we find this pattern, we can replace the U/SMUL_LOHI, ADDC, and ADDE by
9907   // a S/UMLAL instruction.
9908   //                  UMUL_LOHI
9909   //                 / :lo    \ :hi
9910   //                V          \          [no multiline comment]
9911   //    loAdd ->  ADDC         |
9912   //                 \ :carry /
9913   //                  V      V
9914   //                    ADDE   <- hiAdd
9915   //
9916   // In the special case where only the higher part of a signed result is used
9917   // and the add to the low part of the result of ISD::UMUL_LOHI adds or subtracts
9918   // a constant with the exact value of 0x80000000, we recognize we are dealing
9919   // with a "rounded multiply and add" (or subtract) and transform it into
9920   // either a ARMISD::SMMLAR or ARMISD::SMMLSR respectively.
9921 
9922   assert((AddeSubeNode->getOpcode() == ARMISD::ADDE ||
9923           AddeSubeNode->getOpcode() == ARMISD::SUBE) &&
9924          "Expect an ADDE or SUBE");
9925 
9926   assert(AddeSubeNode->getNumOperands() == 3 &&
9927          AddeSubeNode->getOperand(2).getValueType() == MVT::i32 &&
9928          "ADDE node has the wrong inputs");
9929 
9930   // Check that we are chained to the right ADDC or SUBC node.
9931   SDNode *AddcSubcNode = AddeSubeNode->getOperand(2).getNode();
9932   if ((AddeSubeNode->getOpcode() == ARMISD::ADDE &&
9933        AddcSubcNode->getOpcode() != ARMISD::ADDC) ||
9934       (AddeSubeNode->getOpcode() == ARMISD::SUBE &&
9935        AddcSubcNode->getOpcode() != ARMISD::SUBC))
9936     return SDValue();
9937 
9938   SDValue AddcSubcOp0 = AddcSubcNode->getOperand(0);
9939   SDValue AddcSubcOp1 = AddcSubcNode->getOperand(1);
9940 
9941   // Check if the two operands are from the same mul_lohi node.
9942   if (AddcSubcOp0.getNode() == AddcSubcOp1.getNode())
9943     return SDValue();
9944 
9945   assert(AddcSubcNode->getNumValues() == 2 &&
9946          AddcSubcNode->getValueType(0) == MVT::i32 &&
9947          "Expect ADDC with two result values. First: i32");
9948 
9949   // Check that the ADDC adds the low result of the S/UMUL_LOHI. If not, it
9950   // maybe a SMLAL which multiplies two 16-bit values.
9951   if (AddeSubeNode->getOpcode() == ARMISD::ADDE &&
9952       AddcSubcOp0->getOpcode() != ISD::UMUL_LOHI &&
9953       AddcSubcOp0->getOpcode() != ISD::SMUL_LOHI &&
9954       AddcSubcOp1->getOpcode() != ISD::UMUL_LOHI &&
9955       AddcSubcOp1->getOpcode() != ISD::SMUL_LOHI)
9956     return AddCombineTo64BitSMLAL16(AddcSubcNode, AddeSubeNode, DCI, Subtarget);
9957 
9958   // Check for the triangle shape.
9959   SDValue AddeSubeOp0 = AddeSubeNode->getOperand(0);
9960   SDValue AddeSubeOp1 = AddeSubeNode->getOperand(1);
9961 
9962   // Make sure that the ADDE/SUBE operands are not coming from the same node.
9963   if (AddeSubeOp0.getNode() == AddeSubeOp1.getNode())
9964     return SDValue();
9965 
9966   // Find the MUL_LOHI node walking up ADDE/SUBE's operands.
9967   bool IsLeftOperandMUL = false;
9968   SDValue MULOp = findMUL_LOHI(AddeSubeOp0);
9969   if (MULOp == SDValue())
9970     MULOp = findMUL_LOHI(AddeSubeOp1);
9971   else
9972     IsLeftOperandMUL = true;
9973   if (MULOp == SDValue())
9974     return SDValue();
9975 
9976   // Figure out the right opcode.
9977   unsigned Opc = MULOp->getOpcode();
9978   unsigned FinalOpc = (Opc == ISD::SMUL_LOHI) ? ARMISD::SMLAL : ARMISD::UMLAL;
9979 
9980   // Figure out the high and low input values to the MLAL node.
9981   SDValue *HiAddSub = nullptr;
9982   SDValue *LoMul = nullptr;
9983   SDValue *LowAddSub = nullptr;
9984 
9985   // Ensure that ADDE/SUBE is from high result of ISD::xMUL_LOHI.
9986   if ((AddeSubeOp0 != MULOp.getValue(1)) && (AddeSubeOp1 != MULOp.getValue(1)))
9987     return SDValue();
9988 
9989   if (IsLeftOperandMUL)
9990     HiAddSub = &AddeSubeOp1;
9991   else
9992     HiAddSub = &AddeSubeOp0;
9993 
9994   // Ensure that LoMul and LowAddSub are taken from correct ISD::SMUL_LOHI node
9995   // whose low result is fed to the ADDC/SUBC we are checking.
9996 
9997   if (AddcSubcOp0 == MULOp.getValue(0)) {
9998     LoMul = &AddcSubcOp0;
9999     LowAddSub = &AddcSubcOp1;
10000   }
10001   if (AddcSubcOp1 == MULOp.getValue(0)) {
10002     LoMul = &AddcSubcOp1;
10003     LowAddSub = &AddcSubcOp0;
10004   }
10005 
10006   if (!LoMul)
10007     return SDValue();
10008 
10009   // If HiAddSub is the same node as ADDC/SUBC or is a predecessor of ADDC/SUBC
10010   // the replacement below will create a cycle.
10011   if (AddcSubcNode == HiAddSub->getNode() ||
10012       AddcSubcNode->isPredecessorOf(HiAddSub->getNode()))
10013     return SDValue();
10014 
10015   // Create the merged node.
10016   SelectionDAG &DAG = DCI.DAG;
10017 
10018   // Start building operand list.
10019   SmallVector<SDValue, 8> Ops;
10020   Ops.push_back(LoMul->getOperand(0));
10021   Ops.push_back(LoMul->getOperand(1));
10022 
10023   // Check whether we can use SMMLAR, SMMLSR or SMMULR instead.  For this to be
10024   // the case, we must be doing signed multiplication and only use the higher
10025   // part of the result of the MLAL, furthermore the LowAddSub must be a constant
10026   // addition or subtraction with the value of 0x800000.
10027   if (Subtarget->hasV6Ops() && Subtarget->hasDSP() && Subtarget->useMulOps() &&
10028       FinalOpc == ARMISD::SMLAL && !AddeSubeNode->hasAnyUseOfValue(1) &&
10029       LowAddSub->getNode()->getOpcode() == ISD::Constant &&
10030       static_cast<ConstantSDNode *>(LowAddSub->getNode())->getZExtValue() ==
10031           0x80000000) {
10032     Ops.push_back(*HiAddSub);
10033     if (AddcSubcNode->getOpcode() == ARMISD::SUBC) {
10034       FinalOpc = ARMISD::SMMLSR;
10035     } else {
10036       FinalOpc = ARMISD::SMMLAR;
10037     }
10038     SDValue NewNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode), MVT::i32, Ops);
10039     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), NewNode);
10040 
10041     return SDValue(AddeSubeNode, 0);
10042   } else if (AddcSubcNode->getOpcode() == ARMISD::SUBC)
10043     // SMMLS is generated during instruction selection and the rest of this
10044     // function can not handle the case where AddcSubcNode is a SUBC.
10045     return SDValue();
10046 
10047   // Finish building the operand list for {U/S}MLAL
10048   Ops.push_back(*LowAddSub);
10049   Ops.push_back(*HiAddSub);
10050 
10051   SDValue MLALNode = DAG.getNode(FinalOpc, SDLoc(AddcSubcNode),
10052                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10053 
10054   // Replace the ADDs' nodes uses by the MLA node's values.
10055   SDValue HiMLALResult(MLALNode.getNode(), 1);
10056   DAG.ReplaceAllUsesOfValueWith(SDValue(AddeSubeNode, 0), HiMLALResult);
10057 
10058   SDValue LoMLALResult(MLALNode.getNode(), 0);
10059   DAG.ReplaceAllUsesOfValueWith(SDValue(AddcSubcNode, 0), LoMLALResult);
10060 
10061   // Return original node to notify the driver to stop replacing.
10062   return SDValue(AddeSubeNode, 0);
10063 }
10064 
10065 static SDValue AddCombineTo64bitUMAAL(SDNode *AddeNode,
10066                                       TargetLowering::DAGCombinerInfo &DCI,
10067                                       const ARMSubtarget *Subtarget) {
10068   // UMAAL is similar to UMLAL except that it adds two unsigned values.
10069   // While trying to combine for the other MLAL nodes, first search for the
10070   // chance to use UMAAL. Check if Addc uses a node which has already
10071   // been combined into a UMLAL. The other pattern is UMLAL using Addc/Adde
10072   // as the addend, and it's handled in PerformUMLALCombine.
10073 
10074   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10075     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10076 
10077   // Check that we have a glued ADDC node.
10078   SDNode* AddcNode = AddeNode->getOperand(2).getNode();
10079   if (AddcNode->getOpcode() != ARMISD::ADDC)
10080     return SDValue();
10081 
10082   // Find the converted UMAAL or quit if it doesn't exist.
10083   SDNode *UmlalNode = nullptr;
10084   SDValue AddHi;
10085   if (AddcNode->getOperand(0).getOpcode() == ARMISD::UMLAL) {
10086     UmlalNode = AddcNode->getOperand(0).getNode();
10087     AddHi = AddcNode->getOperand(1);
10088   } else if (AddcNode->getOperand(1).getOpcode() == ARMISD::UMLAL) {
10089     UmlalNode = AddcNode->getOperand(1).getNode();
10090     AddHi = AddcNode->getOperand(0);
10091   } else {
10092     return AddCombineTo64bitMLAL(AddeNode, DCI, Subtarget);
10093   }
10094 
10095   // The ADDC should be glued to an ADDE node, which uses the same UMLAL as
10096   // the ADDC as well as Zero.
10097   if (!isNullConstant(UmlalNode->getOperand(3)))
10098     return SDValue();
10099 
10100   if ((isNullConstant(AddeNode->getOperand(0)) &&
10101        AddeNode->getOperand(1).getNode() == UmlalNode) ||
10102       (AddeNode->getOperand(0).getNode() == UmlalNode &&
10103        isNullConstant(AddeNode->getOperand(1)))) {
10104     SelectionDAG &DAG = DCI.DAG;
10105     SDValue Ops[] = { UmlalNode->getOperand(0), UmlalNode->getOperand(1),
10106                       UmlalNode->getOperand(2), AddHi };
10107     SDValue UMAAL =  DAG.getNode(ARMISD::UMAAL, SDLoc(AddcNode),
10108                                  DAG.getVTList(MVT::i32, MVT::i32), Ops);
10109 
10110     // Replace the ADDs' nodes uses by the UMAAL node's values.
10111     DAG.ReplaceAllUsesOfValueWith(SDValue(AddeNode, 0), SDValue(UMAAL.getNode(), 1));
10112     DAG.ReplaceAllUsesOfValueWith(SDValue(AddcNode, 0), SDValue(UMAAL.getNode(), 0));
10113 
10114     // Return original node to notify the driver to stop replacing.
10115     return SDValue(AddeNode, 0);
10116   }
10117   return SDValue();
10118 }
10119 
10120 static SDValue PerformUMLALCombine(SDNode *N, SelectionDAG &DAG,
10121                                    const ARMSubtarget *Subtarget) {
10122   if (!Subtarget->hasV6Ops() || !Subtarget->hasDSP())
10123     return SDValue();
10124 
10125   // Check that we have a pair of ADDC and ADDE as operands.
10126   // Both addends of the ADDE must be zero.
10127   SDNode* AddcNode = N->getOperand(2).getNode();
10128   SDNode* AddeNode = N->getOperand(3).getNode();
10129   if ((AddcNode->getOpcode() == ARMISD::ADDC) &&
10130       (AddeNode->getOpcode() == ARMISD::ADDE) &&
10131       isNullConstant(AddeNode->getOperand(0)) &&
10132       isNullConstant(AddeNode->getOperand(1)) &&
10133       (AddeNode->getOperand(2).getNode() == AddcNode))
10134     return DAG.getNode(ARMISD::UMAAL, SDLoc(N),
10135                        DAG.getVTList(MVT::i32, MVT::i32),
10136                        {N->getOperand(0), N->getOperand(1),
10137                         AddcNode->getOperand(0), AddcNode->getOperand(1)});
10138   else
10139     return SDValue();
10140 }
10141 
10142 static SDValue PerformAddcSubcCombine(SDNode *N,
10143                                       TargetLowering::DAGCombinerInfo &DCI,
10144                                       const ARMSubtarget *Subtarget) {
10145   SelectionDAG &DAG(DCI.DAG);
10146 
10147   if (N->getOpcode() == ARMISD::ADDC) {
10148     // (ADDC (ADDE 0, 0, C), -1) -> C
10149     SDValue LHS = N->getOperand(0);
10150     SDValue RHS = N->getOperand(1);
10151     if (LHS->getOpcode() == ARMISD::ADDE &&
10152         isNullConstant(LHS->getOperand(0)) &&
10153         isNullConstant(LHS->getOperand(1)) && isAllOnesConstant(RHS)) {
10154       return DCI.CombineTo(N, SDValue(N, 0), LHS->getOperand(2));
10155     }
10156   }
10157 
10158   if (Subtarget->isThumb1Only()) {
10159     SDValue RHS = N->getOperand(1);
10160     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10161       int32_t imm = C->getSExtValue();
10162       if (imm < 0 && imm > std::numeric_limits<int>::min()) {
10163         SDLoc DL(N);
10164         RHS = DAG.getConstant(-imm, DL, MVT::i32);
10165         unsigned Opcode = (N->getOpcode() == ARMISD::ADDC) ? ARMISD::SUBC
10166                                                            : ARMISD::ADDC;
10167         return DAG.getNode(Opcode, DL, N->getVTList(), N->getOperand(0), RHS);
10168       }
10169     }
10170   }
10171   return SDValue();
10172 }
10173 
10174 static SDValue PerformAddeSubeCombine(SDNode *N,
10175                                       TargetLowering::DAGCombinerInfo &DCI,
10176                                       const ARMSubtarget *Subtarget) {
10177   if (Subtarget->isThumb1Only()) {
10178     SelectionDAG &DAG = DCI.DAG;
10179     SDValue RHS = N->getOperand(1);
10180     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS)) {
10181       int64_t imm = C->getSExtValue();
10182       if (imm < 0) {
10183         SDLoc DL(N);
10184 
10185         // The with-carry-in form matches bitwise not instead of the negation.
10186         // Effectively, the inverse interpretation of the carry flag already
10187         // accounts for part of the negation.
10188         RHS = DAG.getConstant(~imm, DL, MVT::i32);
10189 
10190         unsigned Opcode = (N->getOpcode() == ARMISD::ADDE) ? ARMISD::SUBE
10191                                                            : ARMISD::ADDE;
10192         return DAG.getNode(Opcode, DL, N->getVTList(),
10193                            N->getOperand(0), RHS, N->getOperand(2));
10194       }
10195     }
10196   } else if (N->getOperand(1)->getOpcode() == ISD::SMUL_LOHI) {
10197     return AddCombineTo64bitMLAL(N, DCI, Subtarget);
10198   }
10199   return SDValue();
10200 }
10201 
10202 /// PerformADDECombine - Target-specific dag combine transform from
10203 /// ARMISD::ADDC, ARMISD::ADDE, and ISD::MUL_LOHI to MLAL or
10204 /// ARMISD::ADDC, ARMISD::ADDE and ARMISD::UMLAL to ARMISD::UMAAL
10205 static SDValue PerformADDECombine(SDNode *N,
10206                                   TargetLowering::DAGCombinerInfo &DCI,
10207                                   const ARMSubtarget *Subtarget) {
10208   // Only ARM and Thumb2 support UMLAL/SMLAL.
10209   if (Subtarget->isThumb1Only())
10210     return PerformAddeSubeCombine(N, DCI, Subtarget);
10211 
10212   // Only perform the checks after legalize when the pattern is available.
10213   if (DCI.isBeforeLegalize()) return SDValue();
10214 
10215   return AddCombineTo64bitUMAAL(N, DCI, Subtarget);
10216 }
10217 
10218 /// PerformADDCombineWithOperands - Try DAG combinations for an ADD with
10219 /// operands N0 and N1.  This is a helper for PerformADDCombine that is
10220 /// called with the default operands, and if that fails, with commuted
10221 /// operands.
10222 static SDValue PerformADDCombineWithOperands(SDNode *N, SDValue N0, SDValue N1,
10223                                           TargetLowering::DAGCombinerInfo &DCI,
10224                                           const ARMSubtarget *Subtarget){
10225   // Attempt to create vpadd for this add.
10226   if (SDValue Result = AddCombineToVPADD(N, N0, N1, DCI, Subtarget))
10227     return Result;
10228 
10229   // Attempt to create vpaddl for this add.
10230   if (SDValue Result = AddCombineVUZPToVPADDL(N, N0, N1, DCI, Subtarget))
10231     return Result;
10232   if (SDValue Result = AddCombineBUILD_VECTORToVPADDL(N, N0, N1, DCI,
10233                                                       Subtarget))
10234     return Result;
10235 
10236   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
10237   if (N0.getNode()->hasOneUse())
10238     if (SDValue Result = combineSelectAndUse(N, N0, N1, DCI))
10239       return Result;
10240   return SDValue();
10241 }
10242 
10243 static SDValue PerformSHLSimplify(SDNode *N,
10244                                 TargetLowering::DAGCombinerInfo &DCI,
10245                                 const ARMSubtarget *ST) {
10246   // Allow the generic combiner to identify potential bswaps.
10247   if (DCI.isBeforeLegalize())
10248     return SDValue();
10249 
10250   // DAG combiner will fold:
10251   // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
10252   // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2
10253   // Other code patterns that can be also be modified have the following form:
10254   // b + ((a << 1) | 510)
10255   // b + ((a << 1) & 510)
10256   // b + ((a << 1) ^ 510)
10257   // b + ((a << 1) + 510)
10258 
10259   // Many instructions can  perform the shift for free, but it requires both
10260   // the operands to be registers. If c1 << c2 is too large, a mov immediate
10261   // instruction will needed. So, unfold back to the original pattern if:
10262   // - if c1 and c2 are small enough that they don't require mov imms.
10263   // - the user(s) of the node can perform an shl
10264 
10265   // No shifted operands for 16-bit instructions.
10266   if (ST->isThumb() && ST->isThumb1Only())
10267     return SDValue();
10268 
10269   // Check that all the users could perform the shl themselves.
10270   for (auto U : N->uses()) {
10271     switch(U->getOpcode()) {
10272     default:
10273       return SDValue();
10274     case ISD::SUB:
10275     case ISD::ADD:
10276     case ISD::AND:
10277     case ISD::OR:
10278     case ISD::XOR:
10279     case ISD::SETCC:
10280     case ARMISD::CMP:
10281       // Check that its not already using a shl.
10282       if (U->getOperand(0).getOpcode() == ISD::SHL ||
10283           U->getOperand(1).getOpcode() == ISD::SHL)
10284         return SDValue();
10285       break;
10286     }
10287   }
10288 
10289   if (N->getOpcode() != ISD::ADD && N->getOpcode() != ISD::OR &&
10290       N->getOpcode() != ISD::XOR && N->getOpcode() != ISD::AND)
10291     return SDValue();
10292 
10293   if (N->getOperand(0).getOpcode() != ISD::SHL)
10294     return SDValue();
10295 
10296   SDValue SHL = N->getOperand(0);
10297 
10298   auto *C1ShlC2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
10299   auto *C2 = dyn_cast<ConstantSDNode>(SHL.getOperand(1));
10300   if (!C1ShlC2 || !C2)
10301     return SDValue();
10302 
10303   DEBUG(dbgs() << "Trying to simplify shl: "; N->dump());
10304 
10305   APInt C2Int = C2->getAPIntValue();
10306   APInt C1Int = C1ShlC2->getAPIntValue();
10307 
10308   // Check that performing a lshr will not lose any information.
10309   APInt Mask = APInt::getHighBitsSet(C2Int.getBitWidth(),
10310                                      C2Int.getBitWidth() - C2->getZExtValue());
10311   if ((C1Int & Mask) != C1Int)
10312     return SDValue();
10313 
10314   // Shift the first constant.
10315   C1Int.lshrInPlace(C2Int);
10316 
10317   // The immediates are encoded as an 8-bit value that can be rotated.
10318   unsigned Zeros = C1Int.countLeadingZeros() + C1Int.countTrailingZeros();
10319   if (C1Int.getBitWidth() - Zeros > 8)
10320     return SDValue();
10321 
10322   Zeros = C2Int.countLeadingZeros() + C2Int.countTrailingZeros();
10323   if (C2Int.getBitWidth() - Zeros > 8)
10324     return SDValue();
10325 
10326   SelectionDAG &DAG = DCI.DAG;
10327   SDLoc dl(N);
10328   SDValue X = SHL.getOperand(0);
10329   SDValue BinOp = DAG.getNode(N->getOpcode(), dl, MVT::i32, X,
10330                               DAG.getConstant(C1Int, dl, MVT::i32));
10331   // Shift left to compensate for the lshr of C1Int.
10332   SDValue Res = DAG.getNode(ISD::SHL, dl, MVT::i32, BinOp, SHL.getOperand(1));
10333 
10334   DAG.ReplaceAllUsesWith(SDValue(N, 0), Res);
10335   return SDValue(N, 0);
10336 }
10337 
10338 
10339 /// PerformADDCombine - Target-specific dag combine xforms for ISD::ADD.
10340 ///
10341 static SDValue PerformADDCombine(SDNode *N,
10342                                  TargetLowering::DAGCombinerInfo &DCI,
10343                                  const ARMSubtarget *Subtarget) {
10344   SDValue N0 = N->getOperand(0);
10345   SDValue N1 = N->getOperand(1);
10346 
10347   // Only works one way, because it needs an immediate operand.
10348   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10349     return Result;
10350 
10351   // First try with the default operand order.
10352   if (SDValue Result = PerformADDCombineWithOperands(N, N0, N1, DCI, Subtarget))
10353     return Result;
10354 
10355   // If that didn't work, try again with the operands commuted.
10356   return PerformADDCombineWithOperands(N, N1, N0, DCI, Subtarget);
10357 }
10358 
10359 /// PerformSUBCombine - Target-specific dag combine xforms for ISD::SUB.
10360 ///
10361 static SDValue PerformSUBCombine(SDNode *N,
10362                                  TargetLowering::DAGCombinerInfo &DCI) {
10363   SDValue N0 = N->getOperand(0);
10364   SDValue N1 = N->getOperand(1);
10365 
10366   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
10367   if (N1.getNode()->hasOneUse())
10368     if (SDValue Result = combineSelectAndUse(N, N1, N0, DCI))
10369       return Result;
10370 
10371   return SDValue();
10372 }
10373 
10374 /// PerformVMULCombine
10375 /// Distribute (A + B) * C to (A * C) + (B * C) to take advantage of the
10376 /// special multiplier accumulator forwarding.
10377 ///   vmul d3, d0, d2
10378 ///   vmla d3, d1, d2
10379 /// is faster than
10380 ///   vadd d3, d0, d1
10381 ///   vmul d3, d3, d2
10382 //  However, for (A + B) * (A + B),
10383 //    vadd d2, d0, d1
10384 //    vmul d3, d0, d2
10385 //    vmla d3, d1, d2
10386 //  is slower than
10387 //    vadd d2, d0, d1
10388 //    vmul d3, d2, d2
10389 static SDValue PerformVMULCombine(SDNode *N,
10390                                   TargetLowering::DAGCombinerInfo &DCI,
10391                                   const ARMSubtarget *Subtarget) {
10392   if (!Subtarget->hasVMLxForwarding())
10393     return SDValue();
10394 
10395   SelectionDAG &DAG = DCI.DAG;
10396   SDValue N0 = N->getOperand(0);
10397   SDValue N1 = N->getOperand(1);
10398   unsigned Opcode = N0.getOpcode();
10399   if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10400       Opcode != ISD::FADD && Opcode != ISD::FSUB) {
10401     Opcode = N1.getOpcode();
10402     if (Opcode != ISD::ADD && Opcode != ISD::SUB &&
10403         Opcode != ISD::FADD && Opcode != ISD::FSUB)
10404       return SDValue();
10405     std::swap(N0, N1);
10406   }
10407 
10408   if (N0 == N1)
10409     return SDValue();
10410 
10411   EVT VT = N->getValueType(0);
10412   SDLoc DL(N);
10413   SDValue N00 = N0->getOperand(0);
10414   SDValue N01 = N0->getOperand(1);
10415   return DAG.getNode(Opcode, DL, VT,
10416                      DAG.getNode(ISD::MUL, DL, VT, N00, N1),
10417                      DAG.getNode(ISD::MUL, DL, VT, N01, N1));
10418 }
10419 
10420 static SDValue PerformMULCombine(SDNode *N,
10421                                  TargetLowering::DAGCombinerInfo &DCI,
10422                                  const ARMSubtarget *Subtarget) {
10423   SelectionDAG &DAG = DCI.DAG;
10424 
10425   if (Subtarget->isThumb1Only())
10426     return SDValue();
10427 
10428   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
10429     return SDValue();
10430 
10431   EVT VT = N->getValueType(0);
10432   if (VT.is64BitVector() || VT.is128BitVector())
10433     return PerformVMULCombine(N, DCI, Subtarget);
10434   if (VT != MVT::i32)
10435     return SDValue();
10436 
10437   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10438   if (!C)
10439     return SDValue();
10440 
10441   int64_t MulAmt = C->getSExtValue();
10442   unsigned ShiftAmt = countTrailingZeros<uint64_t>(MulAmt);
10443 
10444   ShiftAmt = ShiftAmt & (32 - 1);
10445   SDValue V = N->getOperand(0);
10446   SDLoc DL(N);
10447 
10448   SDValue Res;
10449   MulAmt >>= ShiftAmt;
10450 
10451   if (MulAmt >= 0) {
10452     if (isPowerOf2_32(MulAmt - 1)) {
10453       // (mul x, 2^N + 1) => (add (shl x, N), x)
10454       Res = DAG.getNode(ISD::ADD, DL, VT,
10455                         V,
10456                         DAG.getNode(ISD::SHL, DL, VT,
10457                                     V,
10458                                     DAG.getConstant(Log2_32(MulAmt - 1), DL,
10459                                                     MVT::i32)));
10460     } else if (isPowerOf2_32(MulAmt + 1)) {
10461       // (mul x, 2^N - 1) => (sub (shl x, N), x)
10462       Res = DAG.getNode(ISD::SUB, DL, VT,
10463                         DAG.getNode(ISD::SHL, DL, VT,
10464                                     V,
10465                                     DAG.getConstant(Log2_32(MulAmt + 1), DL,
10466                                                     MVT::i32)),
10467                         V);
10468     } else
10469       return SDValue();
10470   } else {
10471     uint64_t MulAmtAbs = -MulAmt;
10472     if (isPowerOf2_32(MulAmtAbs + 1)) {
10473       // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
10474       Res = DAG.getNode(ISD::SUB, DL, VT,
10475                         V,
10476                         DAG.getNode(ISD::SHL, DL, VT,
10477                                     V,
10478                                     DAG.getConstant(Log2_32(MulAmtAbs + 1), DL,
10479                                                     MVT::i32)));
10480     } else if (isPowerOf2_32(MulAmtAbs - 1)) {
10481       // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
10482       Res = DAG.getNode(ISD::ADD, DL, VT,
10483                         V,
10484                         DAG.getNode(ISD::SHL, DL, VT,
10485                                     V,
10486                                     DAG.getConstant(Log2_32(MulAmtAbs - 1), DL,
10487                                                     MVT::i32)));
10488       Res = DAG.getNode(ISD::SUB, DL, VT,
10489                         DAG.getConstant(0, DL, MVT::i32), Res);
10490     } else
10491       return SDValue();
10492   }
10493 
10494   if (ShiftAmt != 0)
10495     Res = DAG.getNode(ISD::SHL, DL, VT,
10496                       Res, DAG.getConstant(ShiftAmt, DL, MVT::i32));
10497 
10498   // Do not add new nodes to DAG combiner worklist.
10499   DCI.CombineTo(N, Res, false);
10500   return SDValue();
10501 }
10502 
10503 static SDValue PerformANDCombine(SDNode *N,
10504                                  TargetLowering::DAGCombinerInfo &DCI,
10505                                  const ARMSubtarget *Subtarget) {
10506   // Attempt to use immediate-form VBIC
10507   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10508   SDLoc dl(N);
10509   EVT VT = N->getValueType(0);
10510   SelectionDAG &DAG = DCI.DAG;
10511 
10512   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10513     return SDValue();
10514 
10515   APInt SplatBits, SplatUndef;
10516   unsigned SplatBitSize;
10517   bool HasAnyUndefs;
10518   if (BVN &&
10519       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10520     if (SplatBitSize <= 64) {
10521       EVT VbicVT;
10522       SDValue Val = isNEONModifiedImm((~SplatBits).getZExtValue(),
10523                                       SplatUndef.getZExtValue(), SplatBitSize,
10524                                       DAG, dl, VbicVT, VT.is128BitVector(),
10525                                       OtherModImm);
10526       if (Val.getNode()) {
10527         SDValue Input =
10528           DAG.getNode(ISD::BITCAST, dl, VbicVT, N->getOperand(0));
10529         SDValue Vbic = DAG.getNode(ARMISD::VBICIMM, dl, VbicVT, Input, Val);
10530         return DAG.getNode(ISD::BITCAST, dl, VT, Vbic);
10531       }
10532     }
10533   }
10534 
10535   if (!Subtarget->isThumb1Only()) {
10536     // fold (and (select cc, -1, c), x) -> (select cc, x, (and, x, c))
10537     if (SDValue Result = combineSelectAndUseCommutative(N, true, DCI))
10538       return Result;
10539 
10540     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10541       return Result;
10542   }
10543 
10544   return SDValue();
10545 }
10546 
10547 // Try combining OR nodes to SMULWB, SMULWT.
10548 static SDValue PerformORCombineToSMULWBT(SDNode *OR,
10549                                          TargetLowering::DAGCombinerInfo &DCI,
10550                                          const ARMSubtarget *Subtarget) {
10551   if (!Subtarget->hasV6Ops() ||
10552       (Subtarget->isThumb() &&
10553        (!Subtarget->hasThumb2() || !Subtarget->hasDSP())))
10554     return SDValue();
10555 
10556   SDValue SRL = OR->getOperand(0);
10557   SDValue SHL = OR->getOperand(1);
10558 
10559   if (SRL.getOpcode() != ISD::SRL || SHL.getOpcode() != ISD::SHL) {
10560     SRL = OR->getOperand(1);
10561     SHL = OR->getOperand(0);
10562   }
10563   if (!isSRL16(SRL) || !isSHL16(SHL))
10564     return SDValue();
10565 
10566   // The first operands to the shifts need to be the two results from the
10567   // same smul_lohi node.
10568   if ((SRL.getOperand(0).getNode() != SHL.getOperand(0).getNode()) ||
10569        SRL.getOperand(0).getOpcode() != ISD::SMUL_LOHI)
10570     return SDValue();
10571 
10572   SDNode *SMULLOHI = SRL.getOperand(0).getNode();
10573   if (SRL.getOperand(0) != SDValue(SMULLOHI, 0) ||
10574       SHL.getOperand(0) != SDValue(SMULLOHI, 1))
10575     return SDValue();
10576 
10577   // Now we have:
10578   // (or (srl (smul_lohi ?, ?), 16), (shl (smul_lohi ?, ?), 16)))
10579   // For SMUL[B|T] smul_lohi will take a 32-bit and a 16-bit arguments.
10580   // For SMUWB the 16-bit value will signed extended somehow.
10581   // For SMULWT only the SRA is required.
10582   // Check both sides of SMUL_LOHI
10583   SDValue OpS16 = SMULLOHI->getOperand(0);
10584   SDValue OpS32 = SMULLOHI->getOperand(1);
10585 
10586   SelectionDAG &DAG = DCI.DAG;
10587   if (!isS16(OpS16, DAG) && !isSRA16(OpS16)) {
10588     OpS16 = OpS32;
10589     OpS32 = SMULLOHI->getOperand(0);
10590   }
10591 
10592   SDLoc dl(OR);
10593   unsigned Opcode = 0;
10594   if (isS16(OpS16, DAG))
10595     Opcode = ARMISD::SMULWB;
10596   else if (isSRA16(OpS16)) {
10597     Opcode = ARMISD::SMULWT;
10598     OpS16 = OpS16->getOperand(0);
10599   }
10600   else
10601     return SDValue();
10602 
10603   SDValue Res = DAG.getNode(Opcode, dl, MVT::i32, OpS32, OpS16);
10604   DAG.ReplaceAllUsesOfValueWith(SDValue(OR, 0), Res);
10605   return SDValue(OR, 0);
10606 }
10607 
10608 static SDValue PerformORCombineToBFI(SDNode *N,
10609                                      TargetLowering::DAGCombinerInfo &DCI,
10610                                      const ARMSubtarget *Subtarget) {
10611   // BFI is only available on V6T2+
10612   if (Subtarget->isThumb1Only() || !Subtarget->hasV6T2Ops())
10613     return SDValue();
10614 
10615   EVT VT = N->getValueType(0);
10616   SDValue N0 = N->getOperand(0);
10617   SDValue N1 = N->getOperand(1);
10618   SelectionDAG &DAG = DCI.DAG;
10619   SDLoc DL(N);
10620   // 1) or (and A, mask), val => ARMbfi A, val, mask
10621   //      iff (val & mask) == val
10622   //
10623   // 2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10624   //  2a) iff isBitFieldInvertedMask(mask) && isBitFieldInvertedMask(~mask2)
10625   //          && mask == ~mask2
10626   //  2b) iff isBitFieldInvertedMask(~mask) && isBitFieldInvertedMask(mask2)
10627   //          && ~mask == mask2
10628   //  (i.e., copy a bitfield value into another bitfield of the same width)
10629 
10630   if (VT != MVT::i32)
10631     return SDValue();
10632 
10633   SDValue N00 = N0.getOperand(0);
10634 
10635   // The value and the mask need to be constants so we can verify this is
10636   // actually a bitfield set. If the mask is 0xffff, we can do better
10637   // via a movt instruction, so don't use BFI in that case.
10638   SDValue MaskOp = N0.getOperand(1);
10639   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(MaskOp);
10640   if (!MaskC)
10641     return SDValue();
10642   unsigned Mask = MaskC->getZExtValue();
10643   if (Mask == 0xffff)
10644     return SDValue();
10645   SDValue Res;
10646   // Case (1): or (and A, mask), val => ARMbfi A, val, mask
10647   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
10648   if (N1C) {
10649     unsigned Val = N1C->getZExtValue();
10650     if ((Val & ~Mask) != Val)
10651       return SDValue();
10652 
10653     if (ARM::isBitFieldInvertedMask(Mask)) {
10654       Val >>= countTrailingZeros(~Mask);
10655 
10656       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00,
10657                         DAG.getConstant(Val, DL, MVT::i32),
10658                         DAG.getConstant(Mask, DL, MVT::i32));
10659 
10660       DCI.CombineTo(N, Res, false);
10661       // Return value from the original node to inform the combiner than N is
10662       // now dead.
10663       return SDValue(N, 0);
10664     }
10665   } else if (N1.getOpcode() == ISD::AND) {
10666     // case (2) or (and A, mask), (and B, mask2) => ARMbfi A, (lsr B, amt), mask
10667     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10668     if (!N11C)
10669       return SDValue();
10670     unsigned Mask2 = N11C->getZExtValue();
10671 
10672     // Mask and ~Mask2 (or reverse) must be equivalent for the BFI pattern
10673     // as is to match.
10674     if (ARM::isBitFieldInvertedMask(Mask) &&
10675         (Mask == ~Mask2)) {
10676       // The pack halfword instruction works better for masks that fit it,
10677       // so use that when it's available.
10678       if (Subtarget->hasDSP() &&
10679           (Mask == 0xffff || Mask == 0xffff0000))
10680         return SDValue();
10681       // 2a
10682       unsigned amt = countTrailingZeros(Mask2);
10683       Res = DAG.getNode(ISD::SRL, DL, VT, N1.getOperand(0),
10684                         DAG.getConstant(amt, DL, MVT::i32));
10685       Res = DAG.getNode(ARMISD::BFI, DL, VT, N00, Res,
10686                         DAG.getConstant(Mask, DL, MVT::i32));
10687       DCI.CombineTo(N, Res, false);
10688       // Return value from the original node to inform the combiner than N is
10689       // now dead.
10690       return SDValue(N, 0);
10691     } else if (ARM::isBitFieldInvertedMask(~Mask) &&
10692                (~Mask == Mask2)) {
10693       // The pack halfword instruction works better for masks that fit it,
10694       // so use that when it's available.
10695       if (Subtarget->hasDSP() &&
10696           (Mask2 == 0xffff || Mask2 == 0xffff0000))
10697         return SDValue();
10698       // 2b
10699       unsigned lsb = countTrailingZeros(Mask);
10700       Res = DAG.getNode(ISD::SRL, DL, VT, N00,
10701                         DAG.getConstant(lsb, DL, MVT::i32));
10702       Res = DAG.getNode(ARMISD::BFI, DL, VT, N1.getOperand(0), Res,
10703                         DAG.getConstant(Mask2, DL, MVT::i32));
10704       DCI.CombineTo(N, Res, false);
10705       // Return value from the original node to inform the combiner than N is
10706       // now dead.
10707       return SDValue(N, 0);
10708     }
10709   }
10710 
10711   if (DAG.MaskedValueIsZero(N1, MaskC->getAPIntValue()) &&
10712       N00.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N00.getOperand(1)) &&
10713       ARM::isBitFieldInvertedMask(~Mask)) {
10714     // Case (3): or (and (shl A, #shamt), mask), B => ARMbfi B, A, ~mask
10715     // where lsb(mask) == #shamt and masked bits of B are known zero.
10716     SDValue ShAmt = N00.getOperand(1);
10717     unsigned ShAmtC = cast<ConstantSDNode>(ShAmt)->getZExtValue();
10718     unsigned LSB = countTrailingZeros(Mask);
10719     if (ShAmtC != LSB)
10720       return SDValue();
10721 
10722     Res = DAG.getNode(ARMISD::BFI, DL, VT, N1, N00.getOperand(0),
10723                       DAG.getConstant(~Mask, DL, MVT::i32));
10724 
10725     DCI.CombineTo(N, Res, false);
10726     // Return value from the original node to inform the combiner than N is
10727     // now dead.
10728     return SDValue(N, 0);
10729   }
10730 
10731   return SDValue();
10732 }
10733 
10734 /// PerformORCombine - Target-specific dag combine xforms for ISD::OR
10735 static SDValue PerformORCombine(SDNode *N,
10736                                 TargetLowering::DAGCombinerInfo &DCI,
10737                                 const ARMSubtarget *Subtarget) {
10738   // Attempt to use immediate-form VORR
10739   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(1));
10740   SDLoc dl(N);
10741   EVT VT = N->getValueType(0);
10742   SelectionDAG &DAG = DCI.DAG;
10743 
10744   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10745     return SDValue();
10746 
10747   APInt SplatBits, SplatUndef;
10748   unsigned SplatBitSize;
10749   bool HasAnyUndefs;
10750   if (BVN && Subtarget->hasNEON() &&
10751       BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
10752     if (SplatBitSize <= 64) {
10753       EVT VorrVT;
10754       SDValue Val = isNEONModifiedImm(SplatBits.getZExtValue(),
10755                                       SplatUndef.getZExtValue(), SplatBitSize,
10756                                       DAG, dl, VorrVT, VT.is128BitVector(),
10757                                       OtherModImm);
10758       if (Val.getNode()) {
10759         SDValue Input =
10760           DAG.getNode(ISD::BITCAST, dl, VorrVT, N->getOperand(0));
10761         SDValue Vorr = DAG.getNode(ARMISD::VORRIMM, dl, VorrVT, Input, Val);
10762         return DAG.getNode(ISD::BITCAST, dl, VT, Vorr);
10763       }
10764     }
10765   }
10766 
10767   if (!Subtarget->isThumb1Only()) {
10768     // fold (or (select cc, 0, c), x) -> (select cc, x, (or, x, c))
10769     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10770       return Result;
10771     if (SDValue Result = PerformORCombineToSMULWBT(N, DCI, Subtarget))
10772       return Result;
10773   }
10774 
10775   SDValue N0 = N->getOperand(0);
10776   SDValue N1 = N->getOperand(1);
10777 
10778   // (or (and B, A), (and C, ~A)) => (VBSL A, B, C) when A is a constant.
10779   if (Subtarget->hasNEON() && N1.getOpcode() == ISD::AND && VT.isVector() &&
10780       DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
10781 
10782     // The code below optimizes (or (and X, Y), Z).
10783     // The AND operand needs to have a single user to make these optimizations
10784     // profitable.
10785     if (N0.getOpcode() != ISD::AND || !N0.hasOneUse())
10786       return SDValue();
10787 
10788     APInt SplatUndef;
10789     unsigned SplatBitSize;
10790     bool HasAnyUndefs;
10791 
10792     APInt SplatBits0, SplatBits1;
10793     BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(1));
10794     BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(1));
10795     // Ensure that the second operand of both ands are constants
10796     if (BVN0 && BVN0->isConstantSplat(SplatBits0, SplatUndef, SplatBitSize,
10797                                       HasAnyUndefs) && !HasAnyUndefs) {
10798         if (BVN1 && BVN1->isConstantSplat(SplatBits1, SplatUndef, SplatBitSize,
10799                                           HasAnyUndefs) && !HasAnyUndefs) {
10800             // Ensure that the bit width of the constants are the same and that
10801             // the splat arguments are logical inverses as per the pattern we
10802             // are trying to simplify.
10803             if (SplatBits0.getBitWidth() == SplatBits1.getBitWidth() &&
10804                 SplatBits0 == ~SplatBits1) {
10805                 // Canonicalize the vector type to make instruction selection
10806                 // simpler.
10807                 EVT CanonicalVT = VT.is128BitVector() ? MVT::v4i32 : MVT::v2i32;
10808                 SDValue Result = DAG.getNode(ARMISD::VBSL, dl, CanonicalVT,
10809                                              N0->getOperand(1),
10810                                              N0->getOperand(0),
10811                                              N1->getOperand(0));
10812                 return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10813             }
10814         }
10815     }
10816   }
10817 
10818   // Try to use the ARM/Thumb2 BFI (bitfield insert) instruction when
10819   // reasonable.
10820   if (N0.getOpcode() == ISD::AND && N0.hasOneUse()) {
10821     if (SDValue Res = PerformORCombineToBFI(N, DCI, Subtarget))
10822       return Res;
10823   }
10824 
10825   if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10826     return Result;
10827 
10828   return SDValue();
10829 }
10830 
10831 static SDValue PerformXORCombine(SDNode *N,
10832                                  TargetLowering::DAGCombinerInfo &DCI,
10833                                  const ARMSubtarget *Subtarget) {
10834   EVT VT = N->getValueType(0);
10835   SelectionDAG &DAG = DCI.DAG;
10836 
10837   if(!DAG.getTargetLoweringInfo().isTypeLegal(VT))
10838     return SDValue();
10839 
10840   if (!Subtarget->isThumb1Only()) {
10841     // fold (xor (select cc, 0, c), x) -> (select cc, x, (xor, x, c))
10842     if (SDValue Result = combineSelectAndUseCommutative(N, false, DCI))
10843       return Result;
10844 
10845     if (SDValue Result = PerformSHLSimplify(N, DCI, Subtarget))
10846       return Result;
10847   }
10848 
10849   return SDValue();
10850 }
10851 
10852 // ParseBFI - given a BFI instruction in N, extract the "from" value (Rn) and return it,
10853 // and fill in FromMask and ToMask with (consecutive) bits in "from" to be extracted and
10854 // their position in "to" (Rd).
10855 static SDValue ParseBFI(SDNode *N, APInt &ToMask, APInt &FromMask) {
10856   assert(N->getOpcode() == ARMISD::BFI);
10857 
10858   SDValue From = N->getOperand(1);
10859   ToMask = ~cast<ConstantSDNode>(N->getOperand(2))->getAPIntValue();
10860   FromMask = APInt::getLowBitsSet(ToMask.getBitWidth(), ToMask.countPopulation());
10861 
10862   // If the Base came from a SHR #C, we can deduce that it is really testing bit
10863   // #C in the base of the SHR.
10864   if (From->getOpcode() == ISD::SRL &&
10865       isa<ConstantSDNode>(From->getOperand(1))) {
10866     APInt Shift = cast<ConstantSDNode>(From->getOperand(1))->getAPIntValue();
10867     assert(Shift.getLimitedValue() < 32 && "Shift too large!");
10868     FromMask <<= Shift.getLimitedValue(31);
10869     From = From->getOperand(0);
10870   }
10871 
10872   return From;
10873 }
10874 
10875 // If A and B contain one contiguous set of bits, does A | B == A . B?
10876 //
10877 // Neither A nor B must be zero.
10878 static bool BitsProperlyConcatenate(const APInt &A, const APInt &B) {
10879   unsigned LastActiveBitInA =  A.countTrailingZeros();
10880   unsigned FirstActiveBitInB = B.getBitWidth() - B.countLeadingZeros() - 1;
10881   return LastActiveBitInA - 1 == FirstActiveBitInB;
10882 }
10883 
10884 static SDValue FindBFIToCombineWith(SDNode *N) {
10885   // We have a BFI in N. Follow a possible chain of BFIs and find a BFI it can combine with,
10886   // if one exists.
10887   APInt ToMask, FromMask;
10888   SDValue From = ParseBFI(N, ToMask, FromMask);
10889   SDValue To = N->getOperand(0);
10890 
10891   // Now check for a compatible BFI to merge with. We can pass through BFIs that
10892   // aren't compatible, but not if they set the same bit in their destination as
10893   // we do (or that of any BFI we're going to combine with).
10894   SDValue V = To;
10895   APInt CombinedToMask = ToMask;
10896   while (V.getOpcode() == ARMISD::BFI) {
10897     APInt NewToMask, NewFromMask;
10898     SDValue NewFrom = ParseBFI(V.getNode(), NewToMask, NewFromMask);
10899     if (NewFrom != From) {
10900       // This BFI has a different base. Keep going.
10901       CombinedToMask |= NewToMask;
10902       V = V.getOperand(0);
10903       continue;
10904     }
10905 
10906     // Do the written bits conflict with any we've seen so far?
10907     if ((NewToMask & CombinedToMask).getBoolValue())
10908       // Conflicting bits - bail out because going further is unsafe.
10909       return SDValue();
10910 
10911     // Are the new bits contiguous when combined with the old bits?
10912     if (BitsProperlyConcatenate(ToMask, NewToMask) &&
10913         BitsProperlyConcatenate(FromMask, NewFromMask))
10914       return V;
10915     if (BitsProperlyConcatenate(NewToMask, ToMask) &&
10916         BitsProperlyConcatenate(NewFromMask, FromMask))
10917       return V;
10918 
10919     // We've seen a write to some bits, so track it.
10920     CombinedToMask |= NewToMask;
10921     // Keep going...
10922     V = V.getOperand(0);
10923   }
10924 
10925   return SDValue();
10926 }
10927 
10928 static SDValue PerformBFICombine(SDNode *N,
10929                                  TargetLowering::DAGCombinerInfo &DCI) {
10930   SDValue N1 = N->getOperand(1);
10931   if (N1.getOpcode() == ISD::AND) {
10932     // (bfi A, (and B, Mask1), Mask2) -> (bfi A, B, Mask2) iff
10933     // the bits being cleared by the AND are not demanded by the BFI.
10934     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
10935     if (!N11C)
10936       return SDValue();
10937     unsigned InvMask = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
10938     unsigned LSB = countTrailingZeros(~InvMask);
10939     unsigned Width = (32 - countLeadingZeros(~InvMask)) - LSB;
10940     assert(Width <
10941                static_cast<unsigned>(std::numeric_limits<unsigned>::digits) &&
10942            "undefined behavior");
10943     unsigned Mask = (1u << Width) - 1;
10944     unsigned Mask2 = N11C->getZExtValue();
10945     if ((Mask & (~Mask2)) == 0)
10946       return DCI.DAG.getNode(ARMISD::BFI, SDLoc(N), N->getValueType(0),
10947                              N->getOperand(0), N1.getOperand(0),
10948                              N->getOperand(2));
10949   } else if (N->getOperand(0).getOpcode() == ARMISD::BFI) {
10950     // We have a BFI of a BFI. Walk up the BFI chain to see how long it goes.
10951     // Keep track of any consecutive bits set that all come from the same base
10952     // value. We can combine these together into a single BFI.
10953     SDValue CombineBFI = FindBFIToCombineWith(N);
10954     if (CombineBFI == SDValue())
10955       return SDValue();
10956 
10957     // We've found a BFI.
10958     APInt ToMask1, FromMask1;
10959     SDValue From1 = ParseBFI(N, ToMask1, FromMask1);
10960 
10961     APInt ToMask2, FromMask2;
10962     SDValue From2 = ParseBFI(CombineBFI.getNode(), ToMask2, FromMask2);
10963     assert(From1 == From2);
10964     (void)From2;
10965 
10966     // First, unlink CombineBFI.
10967     DCI.DAG.ReplaceAllUsesWith(CombineBFI, CombineBFI.getOperand(0));
10968     // Then create a new BFI, combining the two together.
10969     APInt NewFromMask = FromMask1 | FromMask2;
10970     APInt NewToMask = ToMask1 | ToMask2;
10971 
10972     EVT VT = N->getValueType(0);
10973     SDLoc dl(N);
10974 
10975     if (NewFromMask[0] == 0)
10976       From1 = DCI.DAG.getNode(
10977         ISD::SRL, dl, VT, From1,
10978         DCI.DAG.getConstant(NewFromMask.countTrailingZeros(), dl, VT));
10979     return DCI.DAG.getNode(ARMISD::BFI, dl, VT, N->getOperand(0), From1,
10980                            DCI.DAG.getConstant(~NewToMask, dl, VT));
10981   }
10982   return SDValue();
10983 }
10984 
10985 /// PerformVMOVRRDCombine - Target-specific dag combine xforms for
10986 /// ARMISD::VMOVRRD.
10987 static SDValue PerformVMOVRRDCombine(SDNode *N,
10988                                      TargetLowering::DAGCombinerInfo &DCI,
10989                                      const ARMSubtarget *Subtarget) {
10990   // vmovrrd(vmovdrr x, y) -> x,y
10991   SDValue InDouble = N->getOperand(0);
10992   if (InDouble.getOpcode() == ARMISD::VMOVDRR && !Subtarget->isFPOnlySP())
10993     return DCI.CombineTo(N, InDouble.getOperand(0), InDouble.getOperand(1));
10994 
10995   // vmovrrd(load f64) -> (load i32), (load i32)
10996   SDNode *InNode = InDouble.getNode();
10997   if (ISD::isNormalLoad(InNode) && InNode->hasOneUse() &&
10998       InNode->getValueType(0) == MVT::f64 &&
10999       InNode->getOperand(1).getOpcode() == ISD::FrameIndex &&
11000       !cast<LoadSDNode>(InNode)->isVolatile()) {
11001     // TODO: Should this be done for non-FrameIndex operands?
11002     LoadSDNode *LD = cast<LoadSDNode>(InNode);
11003 
11004     SelectionDAG &DAG = DCI.DAG;
11005     SDLoc DL(LD);
11006     SDValue BasePtr = LD->getBasePtr();
11007     SDValue NewLD1 =
11008         DAG.getLoad(MVT::i32, DL, LD->getChain(), BasePtr, LD->getPointerInfo(),
11009                     LD->getAlignment(), LD->getMemOperand()->getFlags());
11010 
11011     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11012                                     DAG.getConstant(4, DL, MVT::i32));
11013     SDValue NewLD2 = DAG.getLoad(
11014         MVT::i32, DL, NewLD1.getValue(1), OffsetPtr, LD->getPointerInfo(),
11015         std::min(4U, LD->getAlignment() / 2), LD->getMemOperand()->getFlags());
11016 
11017     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), NewLD2.getValue(1));
11018     if (DCI.DAG.getDataLayout().isBigEndian())
11019       std::swap (NewLD1, NewLD2);
11020     SDValue Result = DCI.CombineTo(N, NewLD1, NewLD2);
11021     return Result;
11022   }
11023 
11024   return SDValue();
11025 }
11026 
11027 /// PerformVMOVDRRCombine - Target-specific dag combine xforms for
11028 /// ARMISD::VMOVDRR.  This is also used for BUILD_VECTORs with 2 operands.
11029 static SDValue PerformVMOVDRRCombine(SDNode *N, SelectionDAG &DAG) {
11030   // N=vmovrrd(X); vmovdrr(N:0, N:1) -> bit_convert(X)
11031   SDValue Op0 = N->getOperand(0);
11032   SDValue Op1 = N->getOperand(1);
11033   if (Op0.getOpcode() == ISD::BITCAST)
11034     Op0 = Op0.getOperand(0);
11035   if (Op1.getOpcode() == ISD::BITCAST)
11036     Op1 = Op1.getOperand(0);
11037   if (Op0.getOpcode() == ARMISD::VMOVRRD &&
11038       Op0.getNode() == Op1.getNode() &&
11039       Op0.getResNo() == 0 && Op1.getResNo() == 1)
11040     return DAG.getNode(ISD::BITCAST, SDLoc(N),
11041                        N->getValueType(0), Op0.getOperand(0));
11042   return SDValue();
11043 }
11044 
11045 /// hasNormalLoadOperand - Check if any of the operands of a BUILD_VECTOR node
11046 /// are normal, non-volatile loads.  If so, it is profitable to bitcast an
11047 /// i64 vector to have f64 elements, since the value can then be loaded
11048 /// directly into a VFP register.
11049 static bool hasNormalLoadOperand(SDNode *N) {
11050   unsigned NumElts = N->getValueType(0).getVectorNumElements();
11051   for (unsigned i = 0; i < NumElts; ++i) {
11052     SDNode *Elt = N->getOperand(i).getNode();
11053     if (ISD::isNormalLoad(Elt) && !cast<LoadSDNode>(Elt)->isVolatile())
11054       return true;
11055   }
11056   return false;
11057 }
11058 
11059 /// PerformBUILD_VECTORCombine - Target-specific dag combine xforms for
11060 /// ISD::BUILD_VECTOR.
11061 static SDValue PerformBUILD_VECTORCombine(SDNode *N,
11062                                           TargetLowering::DAGCombinerInfo &DCI,
11063                                           const ARMSubtarget *Subtarget) {
11064   // build_vector(N=ARMISD::VMOVRRD(X), N:1) -> bit_convert(X):
11065   // VMOVRRD is introduced when legalizing i64 types.  It forces the i64 value
11066   // into a pair of GPRs, which is fine when the value is used as a scalar,
11067   // but if the i64 value is converted to a vector, we need to undo the VMOVRRD.
11068   SelectionDAG &DAG = DCI.DAG;
11069   if (N->getNumOperands() == 2)
11070     if (SDValue RV = PerformVMOVDRRCombine(N, DAG))
11071       return RV;
11072 
11073   // Load i64 elements as f64 values so that type legalization does not split
11074   // them up into i32 values.
11075   EVT VT = N->getValueType(0);
11076   if (VT.getVectorElementType() != MVT::i64 || !hasNormalLoadOperand(N))
11077     return SDValue();
11078   SDLoc dl(N);
11079   SmallVector<SDValue, 8> Ops;
11080   unsigned NumElts = VT.getVectorNumElements();
11081   for (unsigned i = 0; i < NumElts; ++i) {
11082     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(i));
11083     Ops.push_back(V);
11084     // Make the DAGCombiner fold the bitcast.
11085     DCI.AddToWorklist(V.getNode());
11086   }
11087   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, NumElts);
11088   SDValue BV = DAG.getBuildVector(FloatVT, dl, Ops);
11089   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11090 }
11091 
11092 /// \brief Target-specific dag combine xforms for ARMISD::BUILD_VECTOR.
11093 static SDValue
11094 PerformARMBUILD_VECTORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11095   // ARMISD::BUILD_VECTOR is introduced when legalizing ISD::BUILD_VECTOR.
11096   // At that time, we may have inserted bitcasts from integer to float.
11097   // If these bitcasts have survived DAGCombine, change the lowering of this
11098   // BUILD_VECTOR in something more vector friendly, i.e., that does not
11099   // force to use floating point types.
11100 
11101   // Make sure we can change the type of the vector.
11102   // This is possible iff:
11103   // 1. The vector is only used in a bitcast to a integer type. I.e.,
11104   //    1.1. Vector is used only once.
11105   //    1.2. Use is a bit convert to an integer type.
11106   // 2. The size of its operands are 32-bits (64-bits are not legal).
11107   EVT VT = N->getValueType(0);
11108   EVT EltVT = VT.getVectorElementType();
11109 
11110   // Check 1.1. and 2.
11111   if (EltVT.getSizeInBits() != 32 || !N->hasOneUse())
11112     return SDValue();
11113 
11114   // By construction, the input type must be float.
11115   assert(EltVT == MVT::f32 && "Unexpected type!");
11116 
11117   // Check 1.2.
11118   SDNode *Use = *N->use_begin();
11119   if (Use->getOpcode() != ISD::BITCAST ||
11120       Use->getValueType(0).isFloatingPoint())
11121     return SDValue();
11122 
11123   // Check profitability.
11124   // Model is, if more than half of the relevant operands are bitcast from
11125   // i32, turn the build_vector into a sequence of insert_vector_elt.
11126   // Relevant operands are everything that is not statically
11127   // (i.e., at compile time) bitcasted.
11128   unsigned NumOfBitCastedElts = 0;
11129   unsigned NumElts = VT.getVectorNumElements();
11130   unsigned NumOfRelevantElts = NumElts;
11131   for (unsigned Idx = 0; Idx < NumElts; ++Idx) {
11132     SDValue Elt = N->getOperand(Idx);
11133     if (Elt->getOpcode() == ISD::BITCAST) {
11134       // Assume only bit cast to i32 will go away.
11135       if (Elt->getOperand(0).getValueType() == MVT::i32)
11136         ++NumOfBitCastedElts;
11137     } else if (Elt.isUndef() || isa<ConstantSDNode>(Elt))
11138       // Constants are statically casted, thus do not count them as
11139       // relevant operands.
11140       --NumOfRelevantElts;
11141   }
11142 
11143   // Check if more than half of the elements require a non-free bitcast.
11144   if (NumOfBitCastedElts <= NumOfRelevantElts / 2)
11145     return SDValue();
11146 
11147   SelectionDAG &DAG = DCI.DAG;
11148   // Create the new vector type.
11149   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElts);
11150   // Check if the type is legal.
11151   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11152   if (!TLI.isTypeLegal(VecVT))
11153     return SDValue();
11154 
11155   // Combine:
11156   // ARMISD::BUILD_VECTOR E1, E2, ..., EN.
11157   // => BITCAST INSERT_VECTOR_ELT
11158   //                      (INSERT_VECTOR_ELT (...), (BITCAST EN-1), N-1),
11159   //                      (BITCAST EN), N.
11160   SDValue Vec = DAG.getUNDEF(VecVT);
11161   SDLoc dl(N);
11162   for (unsigned Idx = 0 ; Idx < NumElts; ++Idx) {
11163     SDValue V = N->getOperand(Idx);
11164     if (V.isUndef())
11165       continue;
11166     if (V.getOpcode() == ISD::BITCAST &&
11167         V->getOperand(0).getValueType() == MVT::i32)
11168       // Fold obvious case.
11169       V = V.getOperand(0);
11170     else {
11171       V = DAG.getNode(ISD::BITCAST, SDLoc(V), MVT::i32, V);
11172       // Make the DAGCombiner fold the bitcasts.
11173       DCI.AddToWorklist(V.getNode());
11174     }
11175     SDValue LaneIdx = DAG.getConstant(Idx, dl, MVT::i32);
11176     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VecVT, Vec, V, LaneIdx);
11177   }
11178   Vec = DAG.getNode(ISD::BITCAST, dl, VT, Vec);
11179   // Make the DAGCombiner fold the bitcasts.
11180   DCI.AddToWorklist(Vec.getNode());
11181   return Vec;
11182 }
11183 
11184 /// PerformInsertEltCombine - Target-specific dag combine xforms for
11185 /// ISD::INSERT_VECTOR_ELT.
11186 static SDValue PerformInsertEltCombine(SDNode *N,
11187                                        TargetLowering::DAGCombinerInfo &DCI) {
11188   // Bitcast an i64 load inserted into a vector to f64.
11189   // Otherwise, the i64 value will be legalized to a pair of i32 values.
11190   EVT VT = N->getValueType(0);
11191   SDNode *Elt = N->getOperand(1).getNode();
11192   if (VT.getVectorElementType() != MVT::i64 ||
11193       !ISD::isNormalLoad(Elt) || cast<LoadSDNode>(Elt)->isVolatile())
11194     return SDValue();
11195 
11196   SelectionDAG &DAG = DCI.DAG;
11197   SDLoc dl(N);
11198   EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11199                                  VT.getVectorNumElements());
11200   SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, N->getOperand(0));
11201   SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::f64, N->getOperand(1));
11202   // Make the DAGCombiner fold the bitcasts.
11203   DCI.AddToWorklist(Vec.getNode());
11204   DCI.AddToWorklist(V.getNode());
11205   SDValue InsElt = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, FloatVT,
11206                                Vec, V, N->getOperand(2));
11207   return DAG.getNode(ISD::BITCAST, dl, VT, InsElt);
11208 }
11209 
11210 /// PerformVECTOR_SHUFFLECombine - Target-specific dag combine xforms for
11211 /// ISD::VECTOR_SHUFFLE.
11212 static SDValue PerformVECTOR_SHUFFLECombine(SDNode *N, SelectionDAG &DAG) {
11213   // The LLVM shufflevector instruction does not require the shuffle mask
11214   // length to match the operand vector length, but ISD::VECTOR_SHUFFLE does
11215   // have that requirement.  When translating to ISD::VECTOR_SHUFFLE, if the
11216   // operands do not match the mask length, they are extended by concatenating
11217   // them with undef vectors.  That is probably the right thing for other
11218   // targets, but for NEON it is better to concatenate two double-register
11219   // size vector operands into a single quad-register size vector.  Do that
11220   // transformation here:
11221   //   shuffle(concat(v1, undef), concat(v2, undef)) ->
11222   //   shuffle(concat(v1, v2), undef)
11223   SDValue Op0 = N->getOperand(0);
11224   SDValue Op1 = N->getOperand(1);
11225   if (Op0.getOpcode() != ISD::CONCAT_VECTORS ||
11226       Op1.getOpcode() != ISD::CONCAT_VECTORS ||
11227       Op0.getNumOperands() != 2 ||
11228       Op1.getNumOperands() != 2)
11229     return SDValue();
11230   SDValue Concat0Op1 = Op0.getOperand(1);
11231   SDValue Concat1Op1 = Op1.getOperand(1);
11232   if (!Concat0Op1.isUndef() || !Concat1Op1.isUndef())
11233     return SDValue();
11234   // Skip the transformation if any of the types are illegal.
11235   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11236   EVT VT = N->getValueType(0);
11237   if (!TLI.isTypeLegal(VT) ||
11238       !TLI.isTypeLegal(Concat0Op1.getValueType()) ||
11239       !TLI.isTypeLegal(Concat1Op1.getValueType()))
11240     return SDValue();
11241 
11242   SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11243                                   Op0.getOperand(0), Op1.getOperand(0));
11244   // Translate the shuffle mask.
11245   SmallVector<int, 16> NewMask;
11246   unsigned NumElts = VT.getVectorNumElements();
11247   unsigned HalfElts = NumElts/2;
11248   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11249   for (unsigned n = 0; n < NumElts; ++n) {
11250     int MaskElt = SVN->getMaskElt(n);
11251     int NewElt = -1;
11252     if (MaskElt < (int)HalfElts)
11253       NewElt = MaskElt;
11254     else if (MaskElt >= (int)NumElts && MaskElt < (int)(NumElts + HalfElts))
11255       NewElt = HalfElts + MaskElt - NumElts;
11256     NewMask.push_back(NewElt);
11257   }
11258   return DAG.getVectorShuffle(VT, SDLoc(N), NewConcat,
11259                               DAG.getUNDEF(VT), NewMask);
11260 }
11261 
11262 /// CombineBaseUpdate - Target-specific DAG combine function for VLDDUP,
11263 /// NEON load/store intrinsics, and generic vector load/stores, to merge
11264 /// base address updates.
11265 /// For generic load/stores, the memory type is assumed to be a vector.
11266 /// The caller is assumed to have checked legality.
11267 static SDValue CombineBaseUpdate(SDNode *N,
11268                                  TargetLowering::DAGCombinerInfo &DCI) {
11269   SelectionDAG &DAG = DCI.DAG;
11270   const bool isIntrinsic = (N->getOpcode() == ISD::INTRINSIC_VOID ||
11271                             N->getOpcode() == ISD::INTRINSIC_W_CHAIN);
11272   const bool isStore = N->getOpcode() == ISD::STORE;
11273   const unsigned AddrOpIdx = ((isIntrinsic || isStore) ? 2 : 1);
11274   SDValue Addr = N->getOperand(AddrOpIdx);
11275   MemSDNode *MemN = cast<MemSDNode>(N);
11276   SDLoc dl(N);
11277 
11278   // Search for a use of the address operand that is an increment.
11279   for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
11280          UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
11281     SDNode *User = *UI;
11282     if (User->getOpcode() != ISD::ADD ||
11283         UI.getUse().getResNo() != Addr.getResNo())
11284       continue;
11285 
11286     // Check that the add is independent of the load/store.  Otherwise, folding
11287     // it would create a cycle.
11288     if (User->isPredecessorOf(N) || N->isPredecessorOf(User))
11289       continue;
11290 
11291     // Find the new opcode for the updating load/store.
11292     bool isLoadOp = true;
11293     bool isLaneOp = false;
11294     unsigned NewOpc = 0;
11295     unsigned NumVecs = 0;
11296     if (isIntrinsic) {
11297       unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11298       switch (IntNo) {
11299       default: llvm_unreachable("unexpected intrinsic for Neon base update");
11300       case Intrinsic::arm_neon_vld1:     NewOpc = ARMISD::VLD1_UPD;
11301         NumVecs = 1; break;
11302       case Intrinsic::arm_neon_vld2:     NewOpc = ARMISD::VLD2_UPD;
11303         NumVecs = 2; break;
11304       case Intrinsic::arm_neon_vld3:     NewOpc = ARMISD::VLD3_UPD;
11305         NumVecs = 3; break;
11306       case Intrinsic::arm_neon_vld4:     NewOpc = ARMISD::VLD4_UPD;
11307         NumVecs = 4; break;
11308       case Intrinsic::arm_neon_vld2lane: NewOpc = ARMISD::VLD2LN_UPD;
11309         NumVecs = 2; isLaneOp = true; break;
11310       case Intrinsic::arm_neon_vld3lane: NewOpc = ARMISD::VLD3LN_UPD;
11311         NumVecs = 3; isLaneOp = true; break;
11312       case Intrinsic::arm_neon_vld4lane: NewOpc = ARMISD::VLD4LN_UPD;
11313         NumVecs = 4; isLaneOp = true; break;
11314       case Intrinsic::arm_neon_vst1:     NewOpc = ARMISD::VST1_UPD;
11315         NumVecs = 1; isLoadOp = false; break;
11316       case Intrinsic::arm_neon_vst2:     NewOpc = ARMISD::VST2_UPD;
11317         NumVecs = 2; isLoadOp = false; break;
11318       case Intrinsic::arm_neon_vst3:     NewOpc = ARMISD::VST3_UPD;
11319         NumVecs = 3; isLoadOp = false; break;
11320       case Intrinsic::arm_neon_vst4:     NewOpc = ARMISD::VST4_UPD;
11321         NumVecs = 4; isLoadOp = false; break;
11322       case Intrinsic::arm_neon_vst2lane: NewOpc = ARMISD::VST2LN_UPD;
11323         NumVecs = 2; isLoadOp = false; isLaneOp = true; break;
11324       case Intrinsic::arm_neon_vst3lane: NewOpc = ARMISD::VST3LN_UPD;
11325         NumVecs = 3; isLoadOp = false; isLaneOp = true; break;
11326       case Intrinsic::arm_neon_vst4lane: NewOpc = ARMISD::VST4LN_UPD;
11327         NumVecs = 4; isLoadOp = false; isLaneOp = true; break;
11328       }
11329     } else {
11330       isLaneOp = true;
11331       switch (N->getOpcode()) {
11332       default: llvm_unreachable("unexpected opcode for Neon base update");
11333       case ARMISD::VLD1DUP: NewOpc = ARMISD::VLD1DUP_UPD; NumVecs = 1; break;
11334       case ARMISD::VLD2DUP: NewOpc = ARMISD::VLD2DUP_UPD; NumVecs = 2; break;
11335       case ARMISD::VLD3DUP: NewOpc = ARMISD::VLD3DUP_UPD; NumVecs = 3; break;
11336       case ARMISD::VLD4DUP: NewOpc = ARMISD::VLD4DUP_UPD; NumVecs = 4; break;
11337       case ISD::LOAD:       NewOpc = ARMISD::VLD1_UPD;
11338         NumVecs = 1; isLaneOp = false; break;
11339       case ISD::STORE:      NewOpc = ARMISD::VST1_UPD;
11340         NumVecs = 1; isLaneOp = false; isLoadOp = false; break;
11341       }
11342     }
11343 
11344     // Find the size of memory referenced by the load/store.
11345     EVT VecTy;
11346     if (isLoadOp) {
11347       VecTy = N->getValueType(0);
11348     } else if (isIntrinsic) {
11349       VecTy = N->getOperand(AddrOpIdx+1).getValueType();
11350     } else {
11351       assert(isStore && "Node has to be a load, a store, or an intrinsic!");
11352       VecTy = N->getOperand(1).getValueType();
11353     }
11354 
11355     unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
11356     if (isLaneOp)
11357       NumBytes /= VecTy.getVectorNumElements();
11358 
11359     // If the increment is a constant, it must match the memory ref size.
11360     SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
11361     ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode());
11362     if (NumBytes >= 3 * 16 && (!CInc || CInc->getZExtValue() != NumBytes)) {
11363       // VLD3/4 and VST3/4 for 128-bit vectors are implemented with two
11364       // separate instructions that make it harder to use a non-constant update.
11365       continue;
11366     }
11367 
11368     // OK, we found an ADD we can fold into the base update.
11369     // Now, create a _UPD node, taking care of not breaking alignment.
11370 
11371     EVT AlignedVecTy = VecTy;
11372     unsigned Alignment = MemN->getAlignment();
11373 
11374     // If this is a less-than-standard-aligned load/store, change the type to
11375     // match the standard alignment.
11376     // The alignment is overlooked when selecting _UPD variants; and it's
11377     // easier to introduce bitcasts here than fix that.
11378     // There are 3 ways to get to this base-update combine:
11379     // - intrinsics: they are assumed to be properly aligned (to the standard
11380     //   alignment of the memory type), so we don't need to do anything.
11381     // - ARMISD::VLDx nodes: they are only generated from the aforementioned
11382     //   intrinsics, so, likewise, there's nothing to do.
11383     // - generic load/store instructions: the alignment is specified as an
11384     //   explicit operand, rather than implicitly as the standard alignment
11385     //   of the memory type (like the intrisics).  We need to change the
11386     //   memory type to match the explicit alignment.  That way, we don't
11387     //   generate non-standard-aligned ARMISD::VLDx nodes.
11388     if (isa<LSBaseSDNode>(N)) {
11389       if (Alignment == 0)
11390         Alignment = 1;
11391       if (Alignment < VecTy.getScalarSizeInBits() / 8) {
11392         MVT EltTy = MVT::getIntegerVT(Alignment * 8);
11393         assert(NumVecs == 1 && "Unexpected multi-element generic load/store.");
11394         assert(!isLaneOp && "Unexpected generic load/store lane.");
11395         unsigned NumElts = NumBytes / (EltTy.getSizeInBits() / 8);
11396         AlignedVecTy = MVT::getVectorVT(EltTy, NumElts);
11397       }
11398       // Don't set an explicit alignment on regular load/stores that we want
11399       // to transform to VLD/VST 1_UPD nodes.
11400       // This matches the behavior of regular load/stores, which only get an
11401       // explicit alignment if the MMO alignment is larger than the standard
11402       // alignment of the memory type.
11403       // Intrinsics, however, always get an explicit alignment, set to the
11404       // alignment of the MMO.
11405       Alignment = 1;
11406     }
11407 
11408     // Create the new updating load/store node.
11409     // First, create an SDVTList for the new updating node's results.
11410     EVT Tys[6];
11411     unsigned NumResultVecs = (isLoadOp ? NumVecs : 0);
11412     unsigned n;
11413     for (n = 0; n < NumResultVecs; ++n)
11414       Tys[n] = AlignedVecTy;
11415     Tys[n++] = MVT::i32;
11416     Tys[n] = MVT::Other;
11417     SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs+2));
11418 
11419     // Then, gather the new node's operands.
11420     SmallVector<SDValue, 8> Ops;
11421     Ops.push_back(N->getOperand(0)); // incoming chain
11422     Ops.push_back(N->getOperand(AddrOpIdx));
11423     Ops.push_back(Inc);
11424 
11425     if (StoreSDNode *StN = dyn_cast<StoreSDNode>(N)) {
11426       // Try to match the intrinsic's signature
11427       Ops.push_back(StN->getValue());
11428     } else {
11429       // Loads (and of course intrinsics) match the intrinsics' signature,
11430       // so just add all but the alignment operand.
11431       for (unsigned i = AddrOpIdx + 1; i < N->getNumOperands() - 1; ++i)
11432         Ops.push_back(N->getOperand(i));
11433     }
11434 
11435     // For all node types, the alignment operand is always the last one.
11436     Ops.push_back(DAG.getConstant(Alignment, dl, MVT::i32));
11437 
11438     // If this is a non-standard-aligned STORE, the penultimate operand is the
11439     // stored value.  Bitcast it to the aligned type.
11440     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::STORE) {
11441       SDValue &StVal = Ops[Ops.size()-2];
11442       StVal = DAG.getNode(ISD::BITCAST, dl, AlignedVecTy, StVal);
11443     }
11444 
11445     EVT LoadVT = isLaneOp ? VecTy.getVectorElementType() : AlignedVecTy;
11446     SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, dl, SDTys, Ops, LoadVT,
11447                                            MemN->getMemOperand());
11448 
11449     // Update the uses.
11450     SmallVector<SDValue, 5> NewResults;
11451     for (unsigned i = 0; i < NumResultVecs; ++i)
11452       NewResults.push_back(SDValue(UpdN.getNode(), i));
11453 
11454     // If this is an non-standard-aligned LOAD, the first result is the loaded
11455     // value.  Bitcast it to the expected result type.
11456     if (AlignedVecTy != VecTy && N->getOpcode() == ISD::LOAD) {
11457       SDValue &LdVal = NewResults[0];
11458       LdVal = DAG.getNode(ISD::BITCAST, dl, VecTy, LdVal);
11459     }
11460 
11461     NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs+1)); // chain
11462     DCI.CombineTo(N, NewResults);
11463     DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
11464 
11465     break;
11466   }
11467   return SDValue();
11468 }
11469 
11470 static SDValue PerformVLDCombine(SDNode *N,
11471                                  TargetLowering::DAGCombinerInfo &DCI) {
11472   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
11473     return SDValue();
11474 
11475   return CombineBaseUpdate(N, DCI);
11476 }
11477 
11478 /// CombineVLDDUP - For a VDUPLANE node N, check if its source operand is a
11479 /// vldN-lane (N > 1) intrinsic, and if all the other uses of that intrinsic
11480 /// are also VDUPLANEs.  If so, combine them to a vldN-dup operation and
11481 /// return true.
11482 static bool CombineVLDDUP(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
11483   SelectionDAG &DAG = DCI.DAG;
11484   EVT VT = N->getValueType(0);
11485   // vldN-dup instructions only support 64-bit vectors for N > 1.
11486   if (!VT.is64BitVector())
11487     return false;
11488 
11489   // Check if the VDUPLANE operand is a vldN-dup intrinsic.
11490   SDNode *VLD = N->getOperand(0).getNode();
11491   if (VLD->getOpcode() != ISD::INTRINSIC_W_CHAIN)
11492     return false;
11493   unsigned NumVecs = 0;
11494   unsigned NewOpc = 0;
11495   unsigned IntNo = cast<ConstantSDNode>(VLD->getOperand(1))->getZExtValue();
11496   if (IntNo == Intrinsic::arm_neon_vld2lane) {
11497     NumVecs = 2;
11498     NewOpc = ARMISD::VLD2DUP;
11499   } else if (IntNo == Intrinsic::arm_neon_vld3lane) {
11500     NumVecs = 3;
11501     NewOpc = ARMISD::VLD3DUP;
11502   } else if (IntNo == Intrinsic::arm_neon_vld4lane) {
11503     NumVecs = 4;
11504     NewOpc = ARMISD::VLD4DUP;
11505   } else {
11506     return false;
11507   }
11508 
11509   // First check that all the vldN-lane uses are VDUPLANEs and that the lane
11510   // numbers match the load.
11511   unsigned VLDLaneNo =
11512     cast<ConstantSDNode>(VLD->getOperand(NumVecs+3))->getZExtValue();
11513   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11514        UI != UE; ++UI) {
11515     // Ignore uses of the chain result.
11516     if (UI.getUse().getResNo() == NumVecs)
11517       continue;
11518     SDNode *User = *UI;
11519     if (User->getOpcode() != ARMISD::VDUPLANE ||
11520         VLDLaneNo != cast<ConstantSDNode>(User->getOperand(1))->getZExtValue())
11521       return false;
11522   }
11523 
11524   // Create the vldN-dup node.
11525   EVT Tys[5];
11526   unsigned n;
11527   for (n = 0; n < NumVecs; ++n)
11528     Tys[n] = VT;
11529   Tys[n] = MVT::Other;
11530   SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumVecs+1));
11531   SDValue Ops[] = { VLD->getOperand(0), VLD->getOperand(2) };
11532   MemIntrinsicSDNode *VLDMemInt = cast<MemIntrinsicSDNode>(VLD);
11533   SDValue VLDDup = DAG.getMemIntrinsicNode(NewOpc, SDLoc(VLD), SDTys,
11534                                            Ops, VLDMemInt->getMemoryVT(),
11535                                            VLDMemInt->getMemOperand());
11536 
11537   // Update the uses.
11538   for (SDNode::use_iterator UI = VLD->use_begin(), UE = VLD->use_end();
11539        UI != UE; ++UI) {
11540     unsigned ResNo = UI.getUse().getResNo();
11541     // Ignore uses of the chain result.
11542     if (ResNo == NumVecs)
11543       continue;
11544     SDNode *User = *UI;
11545     DCI.CombineTo(User, SDValue(VLDDup.getNode(), ResNo));
11546   }
11547 
11548   // Now the vldN-lane intrinsic is dead except for its chain result.
11549   // Update uses of the chain.
11550   std::vector<SDValue> VLDDupResults;
11551   for (unsigned n = 0; n < NumVecs; ++n)
11552     VLDDupResults.push_back(SDValue(VLDDup.getNode(), n));
11553   VLDDupResults.push_back(SDValue(VLDDup.getNode(), NumVecs));
11554   DCI.CombineTo(VLD, VLDDupResults);
11555 
11556   return true;
11557 }
11558 
11559 /// PerformVDUPLANECombine - Target-specific dag combine xforms for
11560 /// ARMISD::VDUPLANE.
11561 static SDValue PerformVDUPLANECombine(SDNode *N,
11562                                       TargetLowering::DAGCombinerInfo &DCI) {
11563   SDValue Op = N->getOperand(0);
11564 
11565   // If the source is a vldN-lane (N > 1) intrinsic, and all the other uses
11566   // of that intrinsic are also VDUPLANEs, combine them to a vldN-dup operation.
11567   if (CombineVLDDUP(N, DCI))
11568     return SDValue(N, 0);
11569 
11570   // If the source is already a VMOVIMM or VMVNIMM splat, the VDUPLANE is
11571   // redundant.  Ignore bit_converts for now; element sizes are checked below.
11572   while (Op.getOpcode() == ISD::BITCAST)
11573     Op = Op.getOperand(0);
11574   if (Op.getOpcode() != ARMISD::VMOVIMM && Op.getOpcode() != ARMISD::VMVNIMM)
11575     return SDValue();
11576 
11577   // Make sure the VMOV element size is not bigger than the VDUPLANE elements.
11578   unsigned EltSize = Op.getScalarValueSizeInBits();
11579   // The canonical VMOV for a zero vector uses a 32-bit element size.
11580   unsigned Imm = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11581   unsigned EltBits;
11582   if (ARM_AM::decodeNEONModImm(Imm, EltBits) == 0)
11583     EltSize = 8;
11584   EVT VT = N->getValueType(0);
11585   if (EltSize > VT.getScalarSizeInBits())
11586     return SDValue();
11587 
11588   return DCI.DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
11589 }
11590 
11591 /// PerformVDUPCombine - Target-specific dag combine xforms for ARMISD::VDUP.
11592 static SDValue PerformVDUPCombine(SDNode *N,
11593                                   TargetLowering::DAGCombinerInfo &DCI) {
11594   SelectionDAG &DAG = DCI.DAG;
11595   SDValue Op = N->getOperand(0);
11596 
11597   // Match VDUP(LOAD) -> VLD1DUP.
11598   // We match this pattern here rather than waiting for isel because the
11599   // transform is only legal for unindexed loads.
11600   LoadSDNode *LD = dyn_cast<LoadSDNode>(Op.getNode());
11601   if (LD && Op.hasOneUse() && LD->isUnindexed() &&
11602       LD->getMemoryVT() == N->getValueType(0).getVectorElementType()) {
11603     SDValue Ops[] = { LD->getOperand(0), LD->getOperand(1),
11604                       DAG.getConstant(LD->getAlignment(), SDLoc(N), MVT::i32) };
11605     SDVTList SDTys = DAG.getVTList(N->getValueType(0), MVT::Other);
11606     SDValue VLDDup = DAG.getMemIntrinsicNode(ARMISD::VLD1DUP, SDLoc(N), SDTys,
11607                                              Ops, LD->getMemoryVT(),
11608                                              LD->getMemOperand());
11609     DAG.ReplaceAllUsesOfValueWith(SDValue(LD, 1), VLDDup.getValue(1));
11610     return VLDDup;
11611   }
11612 
11613   return SDValue();
11614 }
11615 
11616 static SDValue PerformLOADCombine(SDNode *N,
11617                                   TargetLowering::DAGCombinerInfo &DCI) {
11618   EVT VT = N->getValueType(0);
11619 
11620   // If this is a legal vector load, try to combine it into a VLD1_UPD.
11621   if (ISD::isNormalLoad(N) && VT.isVector() &&
11622       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11623     return CombineBaseUpdate(N, DCI);
11624 
11625   return SDValue();
11626 }
11627 
11628 /// PerformSTORECombine - Target-specific dag combine xforms for
11629 /// ISD::STORE.
11630 static SDValue PerformSTORECombine(SDNode *N,
11631                                    TargetLowering::DAGCombinerInfo &DCI) {
11632   StoreSDNode *St = cast<StoreSDNode>(N);
11633   if (St->isVolatile())
11634     return SDValue();
11635 
11636   // Optimize trunc store (of multiple scalars) to shuffle and store.  First,
11637   // pack all of the elements in one place.  Next, store to memory in fewer
11638   // chunks.
11639   SDValue StVal = St->getValue();
11640   EVT VT = StVal.getValueType();
11641   if (St->isTruncatingStore() && VT.isVector()) {
11642     SelectionDAG &DAG = DCI.DAG;
11643     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11644     EVT StVT = St->getMemoryVT();
11645     unsigned NumElems = VT.getVectorNumElements();
11646     assert(StVT != VT && "Cannot truncate to the same type");
11647     unsigned FromEltSz = VT.getScalarSizeInBits();
11648     unsigned ToEltSz = StVT.getScalarSizeInBits();
11649 
11650     // From, To sizes and ElemCount must be pow of two
11651     if (!isPowerOf2_32(NumElems * FromEltSz * ToEltSz)) return SDValue();
11652 
11653     // We are going to use the original vector elt for storing.
11654     // Accumulated smaller vector elements must be a multiple of the store size.
11655     if (0 != (NumElems * FromEltSz) % ToEltSz) return SDValue();
11656 
11657     unsigned SizeRatio  = FromEltSz / ToEltSz;
11658     assert(SizeRatio * NumElems * ToEltSz == VT.getSizeInBits());
11659 
11660     // Create a type on which we perform the shuffle.
11661     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(), StVT.getScalarType(),
11662                                      NumElems*SizeRatio);
11663     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
11664 
11665     SDLoc DL(St);
11666     SDValue WideVec = DAG.getNode(ISD::BITCAST, DL, WideVecVT, StVal);
11667     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
11668     for (unsigned i = 0; i < NumElems; ++i)
11669       ShuffleVec[i] = DAG.getDataLayout().isBigEndian()
11670                           ? (i + 1) * SizeRatio - 1
11671                           : i * SizeRatio;
11672 
11673     // Can't shuffle using an illegal type.
11674     if (!TLI.isTypeLegal(WideVecVT)) return SDValue();
11675 
11676     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, DL, WideVec,
11677                                 DAG.getUNDEF(WideVec.getValueType()),
11678                                 ShuffleVec);
11679     // At this point all of the data is stored at the bottom of the
11680     // register. We now need to save it to mem.
11681 
11682     // Find the largest store unit
11683     MVT StoreType = MVT::i8;
11684     for (MVT Tp : MVT::integer_valuetypes()) {
11685       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToEltSz)
11686         StoreType = Tp;
11687     }
11688     // Didn't find a legal store type.
11689     if (!TLI.isTypeLegal(StoreType))
11690       return SDValue();
11691 
11692     // Bitcast the original vector into a vector of store-size units
11693     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
11694             StoreType, VT.getSizeInBits()/EVT(StoreType).getSizeInBits());
11695     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
11696     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, DL, StoreVecVT, Shuff);
11697     SmallVector<SDValue, 8> Chains;
11698     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, DL,
11699                                         TLI.getPointerTy(DAG.getDataLayout()));
11700     SDValue BasePtr = St->getBasePtr();
11701 
11702     // Perform one or more big stores into memory.
11703     unsigned E = (ToEltSz*NumElems)/StoreType.getSizeInBits();
11704     for (unsigned I = 0; I < E; I++) {
11705       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL,
11706                                    StoreType, ShuffWide,
11707                                    DAG.getIntPtrConstant(I, DL));
11708       SDValue Ch = DAG.getStore(St->getChain(), DL, SubVec, BasePtr,
11709                                 St->getPointerInfo(), St->getAlignment(),
11710                                 St->getMemOperand()->getFlags());
11711       BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
11712                             Increment);
11713       Chains.push_back(Ch);
11714     }
11715     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
11716   }
11717 
11718   if (!ISD::isNormalStore(St))
11719     return SDValue();
11720 
11721   // Split a store of a VMOVDRR into two integer stores to avoid mixing NEON and
11722   // ARM stores of arguments in the same cache line.
11723   if (StVal.getNode()->getOpcode() == ARMISD::VMOVDRR &&
11724       StVal.getNode()->hasOneUse()) {
11725     SelectionDAG  &DAG = DCI.DAG;
11726     bool isBigEndian = DAG.getDataLayout().isBigEndian();
11727     SDLoc DL(St);
11728     SDValue BasePtr = St->getBasePtr();
11729     SDValue NewST1 = DAG.getStore(
11730         St->getChain(), DL, StVal.getNode()->getOperand(isBigEndian ? 1 : 0),
11731         BasePtr, St->getPointerInfo(), St->getAlignment(),
11732         St->getMemOperand()->getFlags());
11733 
11734     SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i32, BasePtr,
11735                                     DAG.getConstant(4, DL, MVT::i32));
11736     return DAG.getStore(NewST1.getValue(0), DL,
11737                         StVal.getNode()->getOperand(isBigEndian ? 0 : 1),
11738                         OffsetPtr, St->getPointerInfo(),
11739                         std::min(4U, St->getAlignment() / 2),
11740                         St->getMemOperand()->getFlags());
11741   }
11742 
11743   if (StVal.getValueType() == MVT::i64 &&
11744       StVal.getNode()->getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
11745 
11746     // Bitcast an i64 store extracted from a vector to f64.
11747     // Otherwise, the i64 value will be legalized to a pair of i32 values.
11748     SelectionDAG &DAG = DCI.DAG;
11749     SDLoc dl(StVal);
11750     SDValue IntVec = StVal.getOperand(0);
11751     EVT FloatVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64,
11752                                    IntVec.getValueType().getVectorNumElements());
11753     SDValue Vec = DAG.getNode(ISD::BITCAST, dl, FloatVT, IntVec);
11754     SDValue ExtElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11755                                  Vec, StVal.getOperand(1));
11756     dl = SDLoc(N);
11757     SDValue V = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ExtElt);
11758     // Make the DAGCombiner fold the bitcasts.
11759     DCI.AddToWorklist(Vec.getNode());
11760     DCI.AddToWorklist(ExtElt.getNode());
11761     DCI.AddToWorklist(V.getNode());
11762     return DAG.getStore(St->getChain(), dl, V, St->getBasePtr(),
11763                         St->getPointerInfo(), St->getAlignment(),
11764                         St->getMemOperand()->getFlags(), St->getAAInfo());
11765   }
11766 
11767   // If this is a legal vector store, try to combine it into a VST1_UPD.
11768   if (ISD::isNormalStore(N) && VT.isVector() &&
11769       DCI.DAG.getTargetLoweringInfo().isTypeLegal(VT))
11770     return CombineBaseUpdate(N, DCI);
11771 
11772   return SDValue();
11773 }
11774 
11775 /// PerformVCVTCombine - VCVT (floating-point to fixed-point, Advanced SIMD)
11776 /// can replace combinations of VMUL and VCVT (floating-point to integer)
11777 /// when the VMUL has a constant operand that is a power of 2.
11778 ///
11779 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11780 ///  vmul.f32        d16, d17, d16
11781 ///  vcvt.s32.f32    d16, d16
11782 /// becomes:
11783 ///  vcvt.s32.f32    d16, d16, #3
11784 static SDValue PerformVCVTCombine(SDNode *N, SelectionDAG &DAG,
11785                                   const ARMSubtarget *Subtarget) {
11786   if (!Subtarget->hasNEON())
11787     return SDValue();
11788 
11789   SDValue Op = N->getOperand(0);
11790   if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
11791       Op.getOpcode() != ISD::FMUL)
11792     return SDValue();
11793 
11794   SDValue ConstVec = Op->getOperand(1);
11795   if (!isa<BuildVectorSDNode>(ConstVec))
11796     return SDValue();
11797 
11798   MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
11799   uint32_t FloatBits = FloatTy.getSizeInBits();
11800   MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
11801   uint32_t IntBits = IntTy.getSizeInBits();
11802   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11803   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11804     // These instructions only exist converting from f32 to i32. We can handle
11805     // smaller integers by generating an extra truncate, but larger ones would
11806     // be lossy. We also can't handle more then 4 lanes, since these intructions
11807     // only support v2i32/v4i32 types.
11808     return SDValue();
11809   }
11810 
11811   BitVector UndefElements;
11812   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11813   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11814   if (C == -1 || C == 0 || C > 32)
11815     return SDValue();
11816 
11817   SDLoc dl(N);
11818   bool isSigned = N->getOpcode() == ISD::FP_TO_SINT;
11819   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfp2fxs :
11820     Intrinsic::arm_neon_vcvtfp2fxu;
11821   SDValue FixConv = DAG.getNode(
11822       ISD::INTRINSIC_WO_CHAIN, dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11823       DAG.getConstant(IntrinsicOpcode, dl, MVT::i32), Op->getOperand(0),
11824       DAG.getConstant(C, dl, MVT::i32));
11825 
11826   if (IntBits < FloatBits)
11827     FixConv = DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), FixConv);
11828 
11829   return FixConv;
11830 }
11831 
11832 /// PerformVDIVCombine - VCVT (fixed-point to floating-point, Advanced SIMD)
11833 /// can replace combinations of VCVT (integer to floating-point) and VDIV
11834 /// when the VDIV has a constant operand that is a power of 2.
11835 ///
11836 /// Example (assume d17 = <float 8.000000e+00, float 8.000000e+00>):
11837 ///  vcvt.f32.s32    d16, d16
11838 ///  vdiv.f32        d16, d17, d16
11839 /// becomes:
11840 ///  vcvt.f32.s32    d16, d16, #3
11841 static SDValue PerformVDIVCombine(SDNode *N, SelectionDAG &DAG,
11842                                   const ARMSubtarget *Subtarget) {
11843   if (!Subtarget->hasNEON())
11844     return SDValue();
11845 
11846   SDValue Op = N->getOperand(0);
11847   unsigned OpOpcode = Op.getNode()->getOpcode();
11848   if (!N->getValueType(0).isVector() || !N->getValueType(0).isSimple() ||
11849       (OpOpcode != ISD::SINT_TO_FP && OpOpcode != ISD::UINT_TO_FP))
11850     return SDValue();
11851 
11852   SDValue ConstVec = N->getOperand(1);
11853   if (!isa<BuildVectorSDNode>(ConstVec))
11854     return SDValue();
11855 
11856   MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
11857   uint32_t FloatBits = FloatTy.getSizeInBits();
11858   MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
11859   uint32_t IntBits = IntTy.getSizeInBits();
11860   unsigned NumLanes = Op.getValueType().getVectorNumElements();
11861   if (FloatBits != 32 || IntBits > 32 || NumLanes > 4) {
11862     // These instructions only exist converting from i32 to f32. We can handle
11863     // smaller integers by generating an extra extend, but larger ones would
11864     // be lossy. We also can't handle more then 4 lanes, since these intructions
11865     // only support v2i32/v4i32 types.
11866     return SDValue();
11867   }
11868 
11869   BitVector UndefElements;
11870   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
11871   int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, 33);
11872   if (C == -1 || C == 0 || C > 32)
11873     return SDValue();
11874 
11875   SDLoc dl(N);
11876   bool isSigned = OpOpcode == ISD::SINT_TO_FP;
11877   SDValue ConvInput = Op.getOperand(0);
11878   if (IntBits < FloatBits)
11879     ConvInput = DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
11880                             dl, NumLanes == 2 ? MVT::v2i32 : MVT::v4i32,
11881                             ConvInput);
11882 
11883   unsigned IntrinsicOpcode = isSigned ? Intrinsic::arm_neon_vcvtfxs2fp :
11884     Intrinsic::arm_neon_vcvtfxu2fp;
11885   return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl,
11886                      Op.getValueType(),
11887                      DAG.getConstant(IntrinsicOpcode, dl, MVT::i32),
11888                      ConvInput, DAG.getConstant(C, dl, MVT::i32));
11889 }
11890 
11891 /// Getvshiftimm - Check if this is a valid build_vector for the immediate
11892 /// operand of a vector shift operation, where all the elements of the
11893 /// build_vector must have the same constant integer value.
11894 static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
11895   // Ignore bit_converts.
11896   while (Op.getOpcode() == ISD::BITCAST)
11897     Op = Op.getOperand(0);
11898   BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
11899   APInt SplatBits, SplatUndef;
11900   unsigned SplatBitSize;
11901   bool HasAnyUndefs;
11902   if (! BVN || ! BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
11903                                       HasAnyUndefs, ElementBits) ||
11904       SplatBitSize > ElementBits)
11905     return false;
11906   Cnt = SplatBits.getSExtValue();
11907   return true;
11908 }
11909 
11910 /// isVShiftLImm - Check if this is a valid build_vector for the immediate
11911 /// operand of a vector shift left operation.  That value must be in the range:
11912 ///   0 <= Value < ElementBits for a left shift; or
11913 ///   0 <= Value <= ElementBits for a long left shift.
11914 static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
11915   assert(VT.isVector() && "vector shift count is not a vector type");
11916   int64_t ElementBits = VT.getScalarSizeInBits();
11917   if (! getVShiftImm(Op, ElementBits, Cnt))
11918     return false;
11919   return (Cnt >= 0 && (isLong ? Cnt-1 : Cnt) < ElementBits);
11920 }
11921 
11922 /// isVShiftRImm - Check if this is a valid build_vector for the immediate
11923 /// operand of a vector shift right operation.  For a shift opcode, the value
11924 /// is positive, but for an intrinsic the value count must be negative. The
11925 /// absolute value must be in the range:
11926 ///   1 <= |Value| <= ElementBits for a right shift; or
11927 ///   1 <= |Value| <= ElementBits/2 for a narrow right shift.
11928 static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, bool isIntrinsic,
11929                          int64_t &Cnt) {
11930   assert(VT.isVector() && "vector shift count is not a vector type");
11931   int64_t ElementBits = VT.getScalarSizeInBits();
11932   if (! getVShiftImm(Op, ElementBits, Cnt))
11933     return false;
11934   if (!isIntrinsic)
11935     return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits/2 : ElementBits));
11936   if (Cnt >= -(isNarrow ? ElementBits/2 : ElementBits) && Cnt <= -1) {
11937     Cnt = -Cnt;
11938     return true;
11939   }
11940   return false;
11941 }
11942 
11943 /// PerformIntrinsicCombine - ARM-specific DAG combining for intrinsics.
11944 static SDValue PerformIntrinsicCombine(SDNode *N, SelectionDAG &DAG) {
11945   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
11946   switch (IntNo) {
11947   default:
11948     // Don't do anything for most intrinsics.
11949     break;
11950 
11951   // Vector shifts: check for immediate versions and lower them.
11952   // Note: This is done during DAG combining instead of DAG legalizing because
11953   // the build_vectors for 64-bit vector element shift counts are generally
11954   // not legal, and it is hard to see their values after they get legalized to
11955   // loads from a constant pool.
11956   case Intrinsic::arm_neon_vshifts:
11957   case Intrinsic::arm_neon_vshiftu:
11958   case Intrinsic::arm_neon_vrshifts:
11959   case Intrinsic::arm_neon_vrshiftu:
11960   case Intrinsic::arm_neon_vrshiftn:
11961   case Intrinsic::arm_neon_vqshifts:
11962   case Intrinsic::arm_neon_vqshiftu:
11963   case Intrinsic::arm_neon_vqshiftsu:
11964   case Intrinsic::arm_neon_vqshiftns:
11965   case Intrinsic::arm_neon_vqshiftnu:
11966   case Intrinsic::arm_neon_vqshiftnsu:
11967   case Intrinsic::arm_neon_vqrshiftns:
11968   case Intrinsic::arm_neon_vqrshiftnu:
11969   case Intrinsic::arm_neon_vqrshiftnsu: {
11970     EVT VT = N->getOperand(1).getValueType();
11971     int64_t Cnt;
11972     unsigned VShiftOpc = 0;
11973 
11974     switch (IntNo) {
11975     case Intrinsic::arm_neon_vshifts:
11976     case Intrinsic::arm_neon_vshiftu:
11977       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt)) {
11978         VShiftOpc = ARMISD::VSHL;
11979         break;
11980       }
11981       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt)) {
11982         VShiftOpc = (IntNo == Intrinsic::arm_neon_vshifts ?
11983                      ARMISD::VSHRs : ARMISD::VSHRu);
11984         break;
11985       }
11986       return SDValue();
11987 
11988     case Intrinsic::arm_neon_vrshifts:
11989     case Intrinsic::arm_neon_vrshiftu:
11990       if (isVShiftRImm(N->getOperand(2), VT, false, true, Cnt))
11991         break;
11992       return SDValue();
11993 
11994     case Intrinsic::arm_neon_vqshifts:
11995     case Intrinsic::arm_neon_vqshiftu:
11996       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
11997         break;
11998       return SDValue();
11999 
12000     case Intrinsic::arm_neon_vqshiftsu:
12001       if (isVShiftLImm(N->getOperand(2), VT, false, Cnt))
12002         break;
12003       llvm_unreachable("invalid shift count for vqshlu intrinsic");
12004 
12005     case Intrinsic::arm_neon_vrshiftn:
12006     case Intrinsic::arm_neon_vqshiftns:
12007     case Intrinsic::arm_neon_vqshiftnu:
12008     case Intrinsic::arm_neon_vqshiftnsu:
12009     case Intrinsic::arm_neon_vqrshiftns:
12010     case Intrinsic::arm_neon_vqrshiftnu:
12011     case Intrinsic::arm_neon_vqrshiftnsu:
12012       // Narrowing shifts require an immediate right shift.
12013       if (isVShiftRImm(N->getOperand(2), VT, true, true, Cnt))
12014         break;
12015       llvm_unreachable("invalid shift count for narrowing vector shift "
12016                        "intrinsic");
12017 
12018     default:
12019       llvm_unreachable("unhandled vector shift");
12020     }
12021 
12022     switch (IntNo) {
12023     case Intrinsic::arm_neon_vshifts:
12024     case Intrinsic::arm_neon_vshiftu:
12025       // Opcode already set above.
12026       break;
12027     case Intrinsic::arm_neon_vrshifts:
12028       VShiftOpc = ARMISD::VRSHRs; break;
12029     case Intrinsic::arm_neon_vrshiftu:
12030       VShiftOpc = ARMISD::VRSHRu; break;
12031     case Intrinsic::arm_neon_vrshiftn:
12032       VShiftOpc = ARMISD::VRSHRN; break;
12033     case Intrinsic::arm_neon_vqshifts:
12034       VShiftOpc = ARMISD::VQSHLs; break;
12035     case Intrinsic::arm_neon_vqshiftu:
12036       VShiftOpc = ARMISD::VQSHLu; break;
12037     case Intrinsic::arm_neon_vqshiftsu:
12038       VShiftOpc = ARMISD::VQSHLsu; break;
12039     case Intrinsic::arm_neon_vqshiftns:
12040       VShiftOpc = ARMISD::VQSHRNs; break;
12041     case Intrinsic::arm_neon_vqshiftnu:
12042       VShiftOpc = ARMISD::VQSHRNu; break;
12043     case Intrinsic::arm_neon_vqshiftnsu:
12044       VShiftOpc = ARMISD::VQSHRNsu; break;
12045     case Intrinsic::arm_neon_vqrshiftns:
12046       VShiftOpc = ARMISD::VQRSHRNs; break;
12047     case Intrinsic::arm_neon_vqrshiftnu:
12048       VShiftOpc = ARMISD::VQRSHRNu; break;
12049     case Intrinsic::arm_neon_vqrshiftnsu:
12050       VShiftOpc = ARMISD::VQRSHRNsu; break;
12051     }
12052 
12053     SDLoc dl(N);
12054     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12055                        N->getOperand(1), DAG.getConstant(Cnt, dl, MVT::i32));
12056   }
12057 
12058   case Intrinsic::arm_neon_vshiftins: {
12059     EVT VT = N->getOperand(1).getValueType();
12060     int64_t Cnt;
12061     unsigned VShiftOpc = 0;
12062 
12063     if (isVShiftLImm(N->getOperand(3), VT, false, Cnt))
12064       VShiftOpc = ARMISD::VSLI;
12065     else if (isVShiftRImm(N->getOperand(3), VT, false, true, Cnt))
12066       VShiftOpc = ARMISD::VSRI;
12067     else {
12068       llvm_unreachable("invalid shift count for vsli/vsri intrinsic");
12069     }
12070 
12071     SDLoc dl(N);
12072     return DAG.getNode(VShiftOpc, dl, N->getValueType(0),
12073                        N->getOperand(1), N->getOperand(2),
12074                        DAG.getConstant(Cnt, dl, MVT::i32));
12075   }
12076 
12077   case Intrinsic::arm_neon_vqrshifts:
12078   case Intrinsic::arm_neon_vqrshiftu:
12079     // No immediate versions of these to check for.
12080     break;
12081   }
12082 
12083   return SDValue();
12084 }
12085 
12086 /// PerformShiftCombine - Checks for immediate versions of vector shifts and
12087 /// lowers them.  As with the vector shift intrinsics, this is done during DAG
12088 /// combining instead of DAG legalizing because the build_vectors for 64-bit
12089 /// vector element shift counts are generally not legal, and it is hard to see
12090 /// their values after they get legalized to loads from a constant pool.
12091 static SDValue PerformShiftCombine(SDNode *N, SelectionDAG &DAG,
12092                                    const ARMSubtarget *ST) {
12093   EVT VT = N->getValueType(0);
12094   if (N->getOpcode() == ISD::SRL && VT == MVT::i32 && ST->hasV6Ops()) {
12095     // Canonicalize (srl (bswap x), 16) to (rotr (bswap x), 16) if the high
12096     // 16-bits of x is zero. This optimizes rev + lsr 16 to rev16.
12097     SDValue N1 = N->getOperand(1);
12098     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
12099       SDValue N0 = N->getOperand(0);
12100       if (C->getZExtValue() == 16 && N0.getOpcode() == ISD::BSWAP &&
12101           DAG.MaskedValueIsZero(N0.getOperand(0),
12102                                 APInt::getHighBitsSet(32, 16)))
12103         return DAG.getNode(ISD::ROTR, SDLoc(N), VT, N0, N1);
12104     }
12105   }
12106 
12107   // Nothing to be done for scalar shifts.
12108   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12109   if (!VT.isVector() || !TLI.isTypeLegal(VT))
12110     return SDValue();
12111 
12112   assert(ST->hasNEON() && "unexpected vector shift");
12113   int64_t Cnt;
12114 
12115   switch (N->getOpcode()) {
12116   default: llvm_unreachable("unexpected shift opcode");
12117 
12118   case ISD::SHL:
12119     if (isVShiftLImm(N->getOperand(1), VT, false, Cnt)) {
12120       SDLoc dl(N);
12121       return DAG.getNode(ARMISD::VSHL, dl, VT, N->getOperand(0),
12122                          DAG.getConstant(Cnt, dl, MVT::i32));
12123     }
12124     break;
12125 
12126   case ISD::SRA:
12127   case ISD::SRL:
12128     if (isVShiftRImm(N->getOperand(1), VT, false, false, Cnt)) {
12129       unsigned VShiftOpc = (N->getOpcode() == ISD::SRA ?
12130                             ARMISD::VSHRs : ARMISD::VSHRu);
12131       SDLoc dl(N);
12132       return DAG.getNode(VShiftOpc, dl, VT, N->getOperand(0),
12133                          DAG.getConstant(Cnt, dl, MVT::i32));
12134     }
12135   }
12136   return SDValue();
12137 }
12138 
12139 /// PerformExtendCombine - Target-specific DAG combining for ISD::SIGN_EXTEND,
12140 /// ISD::ZERO_EXTEND, and ISD::ANY_EXTEND.
12141 static SDValue PerformExtendCombine(SDNode *N, SelectionDAG &DAG,
12142                                     const ARMSubtarget *ST) {
12143   SDValue N0 = N->getOperand(0);
12144 
12145   // Check for sign- and zero-extensions of vector extract operations of 8-
12146   // and 16-bit vector elements.  NEON supports these directly.  They are
12147   // handled during DAG combining because type legalization will promote them
12148   // to 32-bit types and it is messy to recognize the operations after that.
12149   if (ST->hasNEON() && N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12150     SDValue Vec = N0.getOperand(0);
12151     SDValue Lane = N0.getOperand(1);
12152     EVT VT = N->getValueType(0);
12153     EVT EltVT = N0.getValueType();
12154     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12155 
12156     if (VT == MVT::i32 &&
12157         (EltVT == MVT::i8 || EltVT == MVT::i16) &&
12158         TLI.isTypeLegal(Vec.getValueType()) &&
12159         isa<ConstantSDNode>(Lane)) {
12160 
12161       unsigned Opc = 0;
12162       switch (N->getOpcode()) {
12163       default: llvm_unreachable("unexpected opcode");
12164       case ISD::SIGN_EXTEND:
12165         Opc = ARMISD::VGETLANEs;
12166         break;
12167       case ISD::ZERO_EXTEND:
12168       case ISD::ANY_EXTEND:
12169         Opc = ARMISD::VGETLANEu;
12170         break;
12171       }
12172       return DAG.getNode(Opc, SDLoc(N), VT, Vec, Lane);
12173     }
12174   }
12175 
12176   return SDValue();
12177 }
12178 
12179 static const APInt *isPowerOf2Constant(SDValue V) {
12180   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12181   if (!C)
12182     return nullptr;
12183   const APInt *CV = &C->getAPIntValue();
12184   return CV->isPowerOf2() ? CV : nullptr;
12185 }
12186 
12187 SDValue ARMTargetLowering::PerformCMOVToBFICombine(SDNode *CMOV, SelectionDAG &DAG) const {
12188   // If we have a CMOV, OR and AND combination such as:
12189   //   if (x & CN)
12190   //     y |= CM;
12191   //
12192   // And:
12193   //   * CN is a single bit;
12194   //   * All bits covered by CM are known zero in y
12195   //
12196   // Then we can convert this into a sequence of BFI instructions. This will
12197   // always be a win if CM is a single bit, will always be no worse than the
12198   // TST&OR sequence if CM is two bits, and for thumb will be no worse if CM is
12199   // three bits (due to the extra IT instruction).
12200 
12201   SDValue Op0 = CMOV->getOperand(0);
12202   SDValue Op1 = CMOV->getOperand(1);
12203   auto CCNode = cast<ConstantSDNode>(CMOV->getOperand(2));
12204   auto CC = CCNode->getAPIntValue().getLimitedValue();
12205   SDValue CmpZ = CMOV->getOperand(4);
12206 
12207   // The compare must be against zero.
12208   if (!isNullConstant(CmpZ->getOperand(1)))
12209     return SDValue();
12210 
12211   assert(CmpZ->getOpcode() == ARMISD::CMPZ);
12212   SDValue And = CmpZ->getOperand(0);
12213   if (And->getOpcode() != ISD::AND)
12214     return SDValue();
12215   const APInt *AndC = isPowerOf2Constant(And->getOperand(1));
12216   if (!AndC)
12217     return SDValue();
12218   SDValue X = And->getOperand(0);
12219 
12220   if (CC == ARMCC::EQ) {
12221     // We're performing an "equal to zero" compare. Swap the operands so we
12222     // canonicalize on a "not equal to zero" compare.
12223     std::swap(Op0, Op1);
12224   } else {
12225     assert(CC == ARMCC::NE && "How can a CMPZ node not be EQ or NE?");
12226   }
12227 
12228   if (Op1->getOpcode() != ISD::OR)
12229     return SDValue();
12230 
12231   ConstantSDNode *OrC = dyn_cast<ConstantSDNode>(Op1->getOperand(1));
12232   if (!OrC)
12233     return SDValue();
12234   SDValue Y = Op1->getOperand(0);
12235 
12236   if (Op0 != Y)
12237     return SDValue();
12238 
12239   // Now, is it profitable to continue?
12240   APInt OrCI = OrC->getAPIntValue();
12241   unsigned Heuristic = Subtarget->isThumb() ? 3 : 2;
12242   if (OrCI.countPopulation() > Heuristic)
12243     return SDValue();
12244 
12245   // Lastly, can we determine that the bits defined by OrCI
12246   // are zero in Y?
12247   KnownBits Known;
12248   DAG.computeKnownBits(Y, Known);
12249   if ((OrCI & Known.Zero) != OrCI)
12250     return SDValue();
12251 
12252   // OK, we can do the combine.
12253   SDValue V = Y;
12254   SDLoc dl(X);
12255   EVT VT = X.getValueType();
12256   unsigned BitInX = AndC->logBase2();
12257 
12258   if (BitInX != 0) {
12259     // We must shift X first.
12260     X = DAG.getNode(ISD::SRL, dl, VT, X,
12261                     DAG.getConstant(BitInX, dl, VT));
12262   }
12263 
12264   for (unsigned BitInY = 0, NumActiveBits = OrCI.getActiveBits();
12265        BitInY < NumActiveBits; ++BitInY) {
12266     if (OrCI[BitInY] == 0)
12267       continue;
12268     APInt Mask(VT.getSizeInBits(), 0);
12269     Mask.setBit(BitInY);
12270     V = DAG.getNode(ARMISD::BFI, dl, VT, V, X,
12271                     // Confusingly, the operand is an *inverted* mask.
12272                     DAG.getConstant(~Mask, dl, VT));
12273   }
12274 
12275   return V;
12276 }
12277 
12278 /// PerformBRCONDCombine - Target-specific DAG combining for ARMISD::BRCOND.
12279 SDValue
12280 ARMTargetLowering::PerformBRCONDCombine(SDNode *N, SelectionDAG &DAG) const {
12281   SDValue Cmp = N->getOperand(4);
12282   if (Cmp.getOpcode() != ARMISD::CMPZ)
12283     // Only looking at NE cases.
12284     return SDValue();
12285 
12286   EVT VT = N->getValueType(0);
12287   SDLoc dl(N);
12288   SDValue LHS = Cmp.getOperand(0);
12289   SDValue RHS = Cmp.getOperand(1);
12290   SDValue Chain = N->getOperand(0);
12291   SDValue BB = N->getOperand(1);
12292   SDValue ARMcc = N->getOperand(2);
12293   ARMCC::CondCodes CC =
12294     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12295 
12296   // (brcond Chain BB ne CPSR (cmpz (and (cmov 0 1 CC CPSR Cmp) 1) 0))
12297   // -> (brcond Chain BB CC CPSR Cmp)
12298   if (CC == ARMCC::NE && LHS.getOpcode() == ISD::AND && LHS->hasOneUse() &&
12299       LHS->getOperand(0)->getOpcode() == ARMISD::CMOV &&
12300       LHS->getOperand(0)->hasOneUse()) {
12301     auto *LHS00C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(0));
12302     auto *LHS01C = dyn_cast<ConstantSDNode>(LHS->getOperand(0)->getOperand(1));
12303     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12304     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12305     if ((LHS00C && LHS00C->getZExtValue() == 0) &&
12306         (LHS01C && LHS01C->getZExtValue() == 1) &&
12307         (LHS1C && LHS1C->getZExtValue() == 1) &&
12308         (RHSC && RHSC->getZExtValue() == 0)) {
12309       return DAG.getNode(
12310           ARMISD::BRCOND, dl, VT, Chain, BB, LHS->getOperand(0)->getOperand(2),
12311           LHS->getOperand(0)->getOperand(3), LHS->getOperand(0)->getOperand(4));
12312     }
12313   }
12314 
12315   return SDValue();
12316 }
12317 
12318 /// PerformCMOVCombine - Target-specific DAG combining for ARMISD::CMOV.
12319 SDValue
12320 ARMTargetLowering::PerformCMOVCombine(SDNode *N, SelectionDAG &DAG) const {
12321   SDValue Cmp = N->getOperand(4);
12322   if (Cmp.getOpcode() != ARMISD::CMPZ)
12323     // Only looking at EQ and NE cases.
12324     return SDValue();
12325 
12326   EVT VT = N->getValueType(0);
12327   SDLoc dl(N);
12328   SDValue LHS = Cmp.getOperand(0);
12329   SDValue RHS = Cmp.getOperand(1);
12330   SDValue FalseVal = N->getOperand(0);
12331   SDValue TrueVal = N->getOperand(1);
12332   SDValue ARMcc = N->getOperand(2);
12333   ARMCC::CondCodes CC =
12334     (ARMCC::CondCodes)cast<ConstantSDNode>(ARMcc)->getZExtValue();
12335 
12336   // BFI is only available on V6T2+.
12337   if (!Subtarget->isThumb1Only() && Subtarget->hasV6T2Ops()) {
12338     SDValue R = PerformCMOVToBFICombine(N, DAG);
12339     if (R)
12340       return R;
12341   }
12342 
12343   // Simplify
12344   //   mov     r1, r0
12345   //   cmp     r1, x
12346   //   mov     r0, y
12347   //   moveq   r0, x
12348   // to
12349   //   cmp     r0, x
12350   //   movne   r0, y
12351   //
12352   //   mov     r1, r0
12353   //   cmp     r1, x
12354   //   mov     r0, x
12355   //   movne   r0, y
12356   // to
12357   //   cmp     r0, x
12358   //   movne   r0, y
12359   /// FIXME: Turn this into a target neutral optimization?
12360   SDValue Res;
12361   if (CC == ARMCC::NE && FalseVal == RHS && FalseVal != LHS) {
12362     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, TrueVal, ARMcc,
12363                       N->getOperand(3), Cmp);
12364   } else if (CC == ARMCC::EQ && TrueVal == RHS) {
12365     SDValue ARMcc;
12366     SDValue NewCmp = getARMCmp(LHS, RHS, ISD::SETNE, ARMcc, DAG, dl);
12367     Res = DAG.getNode(ARMISD::CMOV, dl, VT, LHS, FalseVal, ARMcc,
12368                       N->getOperand(3), NewCmp);
12369   }
12370 
12371   // (cmov F T ne CPSR (cmpz (cmov 0 1 CC CPSR Cmp) 0))
12372   // -> (cmov F T CC CPSR Cmp)
12373   if (CC == ARMCC::NE && LHS.getOpcode() == ARMISD::CMOV && LHS->hasOneUse()) {
12374     auto *LHS0C = dyn_cast<ConstantSDNode>(LHS->getOperand(0));
12375     auto *LHS1C = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
12376     auto *RHSC = dyn_cast<ConstantSDNode>(RHS);
12377     if ((LHS0C && LHS0C->getZExtValue() == 0) &&
12378         (LHS1C && LHS1C->getZExtValue() == 1) &&
12379         (RHSC && RHSC->getZExtValue() == 0)) {
12380       return DAG.getNode(ARMISD::CMOV, dl, VT, FalseVal, TrueVal,
12381                          LHS->getOperand(2), LHS->getOperand(3),
12382                          LHS->getOperand(4));
12383     }
12384   }
12385 
12386   if (Res.getNode()) {
12387     KnownBits Known;
12388     DAG.computeKnownBits(SDValue(N,0), Known);
12389     // Capture demanded bits information that would be otherwise lost.
12390     if (Known.Zero == 0xfffffffe)
12391       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12392                         DAG.getValueType(MVT::i1));
12393     else if (Known.Zero == 0xffffff00)
12394       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12395                         DAG.getValueType(MVT::i8));
12396     else if (Known.Zero == 0xffff0000)
12397       Res = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Res,
12398                         DAG.getValueType(MVT::i16));
12399   }
12400 
12401   return Res;
12402 }
12403 
12404 SDValue ARMTargetLowering::PerformDAGCombine(SDNode *N,
12405                                              DAGCombinerInfo &DCI) const {
12406   switch (N->getOpcode()) {
12407   default: break;
12408   case ARMISD::ADDE:    return PerformADDECombine(N, DCI, Subtarget);
12409   case ARMISD::UMLAL:   return PerformUMLALCombine(N, DCI.DAG, Subtarget);
12410   case ISD::ADD:        return PerformADDCombine(N, DCI, Subtarget);
12411   case ISD::SUB:        return PerformSUBCombine(N, DCI);
12412   case ISD::MUL:        return PerformMULCombine(N, DCI, Subtarget);
12413   case ISD::OR:         return PerformORCombine(N, DCI, Subtarget);
12414   case ISD::XOR:        return PerformXORCombine(N, DCI, Subtarget);
12415   case ISD::AND:        return PerformANDCombine(N, DCI, Subtarget);
12416   case ARMISD::ADDC:
12417   case ARMISD::SUBC:    return PerformAddcSubcCombine(N, DCI, Subtarget);
12418   case ARMISD::SUBE:    return PerformAddeSubeCombine(N, DCI, Subtarget);
12419   case ARMISD::BFI:     return PerformBFICombine(N, DCI);
12420   case ARMISD::VMOVRRD: return PerformVMOVRRDCombine(N, DCI, Subtarget);
12421   case ARMISD::VMOVDRR: return PerformVMOVDRRCombine(N, DCI.DAG);
12422   case ISD::STORE:      return PerformSTORECombine(N, DCI);
12423   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DCI, Subtarget);
12424   case ISD::INSERT_VECTOR_ELT: return PerformInsertEltCombine(N, DCI);
12425   case ISD::VECTOR_SHUFFLE: return PerformVECTOR_SHUFFLECombine(N, DCI.DAG);
12426   case ARMISD::VDUPLANE: return PerformVDUPLANECombine(N, DCI);
12427   case ARMISD::VDUP: return PerformVDUPCombine(N, DCI);
12428   case ISD::FP_TO_SINT:
12429   case ISD::FP_TO_UINT:
12430     return PerformVCVTCombine(N, DCI.DAG, Subtarget);
12431   case ISD::FDIV:
12432     return PerformVDIVCombine(N, DCI.DAG, Subtarget);
12433   case ISD::INTRINSIC_WO_CHAIN: return PerformIntrinsicCombine(N, DCI.DAG);
12434   case ISD::SHL:
12435   case ISD::SRA:
12436   case ISD::SRL:        return PerformShiftCombine(N, DCI.DAG, Subtarget);
12437   case ISD::SIGN_EXTEND:
12438   case ISD::ZERO_EXTEND:
12439   case ISD::ANY_EXTEND: return PerformExtendCombine(N, DCI.DAG, Subtarget);
12440   case ARMISD::CMOV: return PerformCMOVCombine(N, DCI.DAG);
12441   case ARMISD::BRCOND: return PerformBRCONDCombine(N, DCI.DAG);
12442   case ISD::LOAD:       return PerformLOADCombine(N, DCI);
12443   case ARMISD::VLD1DUP:
12444   case ARMISD::VLD2DUP:
12445   case ARMISD::VLD3DUP:
12446   case ARMISD::VLD4DUP:
12447     return PerformVLDCombine(N, DCI);
12448   case ARMISD::BUILD_VECTOR:
12449     return PerformARMBUILD_VECTORCombine(N, DCI);
12450   case ARMISD::SMULWB: {
12451     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12452     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12453     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12454       return SDValue();
12455     break;
12456   }
12457   case ARMISD::SMULWT: {
12458     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12459     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12460     if (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI))
12461       return SDValue();
12462     break;
12463   }
12464   case ARMISD::SMLALBB: {
12465     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12466     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, 16);
12467     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12468         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12469       return SDValue();
12470     break;
12471   }
12472   case ARMISD::SMLALBT: {
12473     unsigned LowWidth = N->getOperand(0).getValueType().getSizeInBits();
12474     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12475     unsigned HighWidth = N->getOperand(1).getValueType().getSizeInBits();
12476     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12477     if ((SimplifyDemandedBits(N->getOperand(0), LowMask, DCI)) ||
12478         (SimplifyDemandedBits(N->getOperand(1), HighMask, DCI)))
12479       return SDValue();
12480     break;
12481   }
12482   case ARMISD::SMLALTB: {
12483     unsigned HighWidth = N->getOperand(0).getValueType().getSizeInBits();
12484     APInt HighMask = APInt::getHighBitsSet(HighWidth, 16);
12485     unsigned LowWidth = N->getOperand(1).getValueType().getSizeInBits();
12486     APInt LowMask = APInt::getLowBitsSet(LowWidth, 16);
12487     if ((SimplifyDemandedBits(N->getOperand(0), HighMask, DCI)) ||
12488         (SimplifyDemandedBits(N->getOperand(1), LowMask, DCI)))
12489       return SDValue();
12490     break;
12491   }
12492   case ARMISD::SMLALTT: {
12493     unsigned BitWidth = N->getValueType(0).getSizeInBits();
12494     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 16);
12495     if ((SimplifyDemandedBits(N->getOperand(0), DemandedMask, DCI)) ||
12496         (SimplifyDemandedBits(N->getOperand(1), DemandedMask, DCI)))
12497       return SDValue();
12498     break;
12499   }
12500   case ISD::INTRINSIC_VOID:
12501   case ISD::INTRINSIC_W_CHAIN:
12502     switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
12503     case Intrinsic::arm_neon_vld1:
12504     case Intrinsic::arm_neon_vld2:
12505     case Intrinsic::arm_neon_vld3:
12506     case Intrinsic::arm_neon_vld4:
12507     case Intrinsic::arm_neon_vld2lane:
12508     case Intrinsic::arm_neon_vld3lane:
12509     case Intrinsic::arm_neon_vld4lane:
12510     case Intrinsic::arm_neon_vst1:
12511     case Intrinsic::arm_neon_vst2:
12512     case Intrinsic::arm_neon_vst3:
12513     case Intrinsic::arm_neon_vst4:
12514     case Intrinsic::arm_neon_vst2lane:
12515     case Intrinsic::arm_neon_vst3lane:
12516     case Intrinsic::arm_neon_vst4lane:
12517       return PerformVLDCombine(N, DCI);
12518     default: break;
12519     }
12520     break;
12521   }
12522   return SDValue();
12523 }
12524 
12525 bool ARMTargetLowering::isDesirableToTransformToIntegerOp(unsigned Opc,
12526                                                           EVT VT) const {
12527   return (VT == MVT::f32) && (Opc == ISD::LOAD || Opc == ISD::STORE);
12528 }
12529 
12530 bool ARMTargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
12531                                                        unsigned,
12532                                                        unsigned,
12533                                                        bool *Fast) const {
12534   // The AllowsUnaliged flag models the SCTLR.A setting in ARM cpus
12535   bool AllowsUnaligned = Subtarget->allowsUnalignedMem();
12536 
12537   switch (VT.getSimpleVT().SimpleTy) {
12538   default:
12539     return false;
12540   case MVT::i8:
12541   case MVT::i16:
12542   case MVT::i32: {
12543     // Unaligned access can use (for example) LRDB, LRDH, LDR
12544     if (AllowsUnaligned) {
12545       if (Fast)
12546         *Fast = Subtarget->hasV7Ops();
12547       return true;
12548     }
12549     return false;
12550   }
12551   case MVT::f64:
12552   case MVT::v2f64: {
12553     // For any little-endian targets with neon, we can support unaligned ld/st
12554     // of D and Q (e.g. {D0,D1}) registers by using vld1.i8/vst1.i8.
12555     // A big-endian target may also explicitly support unaligned accesses
12556     if (Subtarget->hasNEON() && (AllowsUnaligned || Subtarget->isLittle())) {
12557       if (Fast)
12558         *Fast = true;
12559       return true;
12560     }
12561     return false;
12562   }
12563   }
12564 }
12565 
12566 static bool memOpAlign(unsigned DstAlign, unsigned SrcAlign,
12567                        unsigned AlignCheck) {
12568   return ((SrcAlign == 0 || SrcAlign % AlignCheck == 0) &&
12569           (DstAlign == 0 || DstAlign % AlignCheck == 0));
12570 }
12571 
12572 EVT ARMTargetLowering::getOptimalMemOpType(uint64_t Size,
12573                                            unsigned DstAlign, unsigned SrcAlign,
12574                                            bool IsMemset, bool ZeroMemset,
12575                                            bool MemcpyStrSrc,
12576                                            MachineFunction &MF) const {
12577   const Function &F = MF.getFunction();
12578 
12579   // See if we can use NEON instructions for this...
12580   if ((!IsMemset || ZeroMemset) && Subtarget->hasNEON() &&
12581       !F.hasFnAttribute(Attribute::NoImplicitFloat)) {
12582     bool Fast;
12583     if (Size >= 16 &&
12584         (memOpAlign(SrcAlign, DstAlign, 16) ||
12585          (allowsMisalignedMemoryAccesses(MVT::v2f64, 0, 1, &Fast) && Fast))) {
12586       return MVT::v2f64;
12587     } else if (Size >= 8 &&
12588                (memOpAlign(SrcAlign, DstAlign, 8) ||
12589                 (allowsMisalignedMemoryAccesses(MVT::f64, 0, 1, &Fast) &&
12590                  Fast))) {
12591       return MVT::f64;
12592     }
12593   }
12594 
12595   // Let the target-independent logic figure it out.
12596   return MVT::Other;
12597 }
12598 
12599 // 64-bit integers are split into their high and low parts and held in two
12600 // different registers, so the trunc is free since the low register can just
12601 // be used.
12602 bool ARMTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
12603   if (!SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
12604     return false;
12605   unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
12606   unsigned DestBits = DstTy->getPrimitiveSizeInBits();
12607   return (SrcBits == 64 && DestBits == 32);
12608 }
12609 
12610 bool ARMTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
12611   if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
12612       !DstVT.isInteger())
12613     return false;
12614   unsigned SrcBits = SrcVT.getSizeInBits();
12615   unsigned DestBits = DstVT.getSizeInBits();
12616   return (SrcBits == 64 && DestBits == 32);
12617 }
12618 
12619 bool ARMTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
12620   if (Val.getOpcode() != ISD::LOAD)
12621     return false;
12622 
12623   EVT VT1 = Val.getValueType();
12624   if (!VT1.isSimple() || !VT1.isInteger() ||
12625       !VT2.isSimple() || !VT2.isInteger())
12626     return false;
12627 
12628   switch (VT1.getSimpleVT().SimpleTy) {
12629   default: break;
12630   case MVT::i1:
12631   case MVT::i8:
12632   case MVT::i16:
12633     // 8-bit and 16-bit loads implicitly zero-extend to 32-bits.
12634     return true;
12635   }
12636 
12637   return false;
12638 }
12639 
12640 bool ARMTargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
12641   EVT VT = ExtVal.getValueType();
12642 
12643   if (!isTypeLegal(VT))
12644     return false;
12645 
12646   // Don't create a loadext if we can fold the extension into a wide/long
12647   // instruction.
12648   // If there's more than one user instruction, the loadext is desirable no
12649   // matter what.  There can be two uses by the same instruction.
12650   if (ExtVal->use_empty() ||
12651       !ExtVal->use_begin()->isOnlyUserOf(ExtVal.getNode()))
12652     return true;
12653 
12654   SDNode *U = *ExtVal->use_begin();
12655   if ((U->getOpcode() == ISD::ADD || U->getOpcode() == ISD::SUB ||
12656        U->getOpcode() == ISD::SHL || U->getOpcode() == ARMISD::VSHL))
12657     return false;
12658 
12659   return true;
12660 }
12661 
12662 bool ARMTargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
12663   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
12664     return false;
12665 
12666   if (!isTypeLegal(EVT::getEVT(Ty1)))
12667     return false;
12668 
12669   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
12670 
12671   // Assuming the caller doesn't have a zeroext or signext return parameter,
12672   // truncation all the way down to i1 is valid.
12673   return true;
12674 }
12675 
12676 int ARMTargetLowering::getScalingFactorCost(const DataLayout &DL,
12677                                                 const AddrMode &AM, Type *Ty,
12678                                                 unsigned AS) const {
12679   if (isLegalAddressingMode(DL, AM, Ty, AS)) {
12680     if (Subtarget->hasFPAO())
12681       return AM.Scale < 0 ? 1 : 0; // positive offsets execute faster
12682     return 0;
12683   }
12684   return -1;
12685 }
12686 
12687 static bool isLegalT1AddressImmediate(int64_t V, EVT VT) {
12688   if (V < 0)
12689     return false;
12690 
12691   unsigned Scale = 1;
12692   switch (VT.getSimpleVT().SimpleTy) {
12693   default: return false;
12694   case MVT::i1:
12695   case MVT::i8:
12696     // Scale == 1;
12697     break;
12698   case MVT::i16:
12699     // Scale == 2;
12700     Scale = 2;
12701     break;
12702   case MVT::i32:
12703     // Scale == 4;
12704     Scale = 4;
12705     break;
12706   }
12707 
12708   if ((V & (Scale - 1)) != 0)
12709     return false;
12710   V /= Scale;
12711   return V == (V & ((1LL << 5) - 1));
12712 }
12713 
12714 static bool isLegalT2AddressImmediate(int64_t V, EVT VT,
12715                                       const ARMSubtarget *Subtarget) {
12716   bool isNeg = false;
12717   if (V < 0) {
12718     isNeg = true;
12719     V = - V;
12720   }
12721 
12722   switch (VT.getSimpleVT().SimpleTy) {
12723   default: return false;
12724   case MVT::i1:
12725   case MVT::i8:
12726   case MVT::i16:
12727   case MVT::i32:
12728     // + imm12 or - imm8
12729     if (isNeg)
12730       return V == (V & ((1LL << 8) - 1));
12731     return V == (V & ((1LL << 12) - 1));
12732   case MVT::f32:
12733   case MVT::f64:
12734     // Same as ARM mode. FIXME: NEON?
12735     if (!Subtarget->hasVFP2())
12736       return false;
12737     if ((V & 3) != 0)
12738       return false;
12739     V >>= 2;
12740     return V == (V & ((1LL << 8) - 1));
12741   }
12742 }
12743 
12744 /// isLegalAddressImmediate - Return true if the integer value can be used
12745 /// as the offset of the target addressing mode for load / store of the
12746 /// given type.
12747 static bool isLegalAddressImmediate(int64_t V, EVT VT,
12748                                     const ARMSubtarget *Subtarget) {
12749   if (V == 0)
12750     return true;
12751 
12752   if (!VT.isSimple())
12753     return false;
12754 
12755   if (Subtarget->isThumb1Only())
12756     return isLegalT1AddressImmediate(V, VT);
12757   else if (Subtarget->isThumb2())
12758     return isLegalT2AddressImmediate(V, VT, Subtarget);
12759 
12760   // ARM mode.
12761   if (V < 0)
12762     V = - V;
12763   switch (VT.getSimpleVT().SimpleTy) {
12764   default: return false;
12765   case MVT::i1:
12766   case MVT::i8:
12767   case MVT::i32:
12768     // +- imm12
12769     return V == (V & ((1LL << 12) - 1));
12770   case MVT::i16:
12771     // +- imm8
12772     return V == (V & ((1LL << 8) - 1));
12773   case MVT::f32:
12774   case MVT::f64:
12775     if (!Subtarget->hasVFP2()) // FIXME: NEON?
12776       return false;
12777     if ((V & 3) != 0)
12778       return false;
12779     V >>= 2;
12780     return V == (V & ((1LL << 8) - 1));
12781   }
12782 }
12783 
12784 bool ARMTargetLowering::isLegalT2ScaledAddressingMode(const AddrMode &AM,
12785                                                       EVT VT) const {
12786   int Scale = AM.Scale;
12787   if (Scale < 0)
12788     return false;
12789 
12790   switch (VT.getSimpleVT().SimpleTy) {
12791   default: return false;
12792   case MVT::i1:
12793   case MVT::i8:
12794   case MVT::i16:
12795   case MVT::i32:
12796     if (Scale == 1)
12797       return true;
12798     // r + r << imm
12799     Scale = Scale & ~1;
12800     return Scale == 2 || Scale == 4 || Scale == 8;
12801   case MVT::i64:
12802     // FIXME: What are we trying to model here? ldrd doesn't have an r + r
12803     // version in Thumb mode.
12804     // r + r
12805     if (Scale == 1)
12806       return true;
12807     // r * 2 (this can be lowered to r + r).
12808     if (!AM.HasBaseReg && Scale == 2)
12809       return true;
12810     return false;
12811   case MVT::isVoid:
12812     // Note, we allow "void" uses (basically, uses that aren't loads or
12813     // stores), because arm allows folding a scale into many arithmetic
12814     // operations.  This should be made more precise and revisited later.
12815 
12816     // Allow r << imm, but the imm has to be a multiple of two.
12817     if (Scale & 1) return false;
12818     return isPowerOf2_32(Scale);
12819   }
12820 }
12821 
12822 bool ARMTargetLowering::isLegalT1ScaledAddressingMode(const AddrMode &AM,
12823                                                       EVT VT) const {
12824   const int Scale = AM.Scale;
12825 
12826   // Negative scales are not supported in Thumb1.
12827   if (Scale < 0)
12828     return false;
12829 
12830   // Thumb1 addressing modes do not support register scaling excepting the
12831   // following cases:
12832   // 1. Scale == 1 means no scaling.
12833   // 2. Scale == 2 this can be lowered to r + r if there is no base register.
12834   return (Scale == 1) || (!AM.HasBaseReg && Scale == 2);
12835 }
12836 
12837 /// isLegalAddressingMode - Return true if the addressing mode represented
12838 /// by AM is legal for this target, for a load/store of the specified type.
12839 bool ARMTargetLowering::isLegalAddressingMode(const DataLayout &DL,
12840                                               const AddrMode &AM, Type *Ty,
12841                                               unsigned AS, Instruction *I) const {
12842   EVT VT = getValueType(DL, Ty, true);
12843   if (!isLegalAddressImmediate(AM.BaseOffs, VT, Subtarget))
12844     return false;
12845 
12846   // Can never fold addr of global into load/store.
12847   if (AM.BaseGV)
12848     return false;
12849 
12850   switch (AM.Scale) {
12851   case 0:  // no scale reg, must be "r+i" or "r", or "i".
12852     break;
12853   default:
12854     // ARM doesn't support any R+R*scale+imm addr modes.
12855     if (AM.BaseOffs)
12856       return false;
12857 
12858     if (!VT.isSimple())
12859       return false;
12860 
12861     if (Subtarget->isThumb1Only())
12862       return isLegalT1ScaledAddressingMode(AM, VT);
12863 
12864     if (Subtarget->isThumb2())
12865       return isLegalT2ScaledAddressingMode(AM, VT);
12866 
12867     int Scale = AM.Scale;
12868     switch (VT.getSimpleVT().SimpleTy) {
12869     default: return false;
12870     case MVT::i1:
12871     case MVT::i8:
12872     case MVT::i32:
12873       if (Scale < 0) Scale = -Scale;
12874       if (Scale == 1)
12875         return true;
12876       // r + r << imm
12877       return isPowerOf2_32(Scale & ~1);
12878     case MVT::i16:
12879     case MVT::i64:
12880       // r +/- r
12881       if (Scale == 1 || (AM.HasBaseReg && Scale == -1))
12882         return true;
12883       // r * 2 (this can be lowered to r + r).
12884       if (!AM.HasBaseReg && Scale == 2)
12885         return true;
12886       return false;
12887 
12888     case MVT::isVoid:
12889       // Note, we allow "void" uses (basically, uses that aren't loads or
12890       // stores), because arm allows folding a scale into many arithmetic
12891       // operations.  This should be made more precise and revisited later.
12892 
12893       // Allow r << imm, but the imm has to be a multiple of two.
12894       if (Scale & 1) return false;
12895       return isPowerOf2_32(Scale);
12896     }
12897   }
12898   return true;
12899 }
12900 
12901 /// isLegalICmpImmediate - Return true if the specified immediate is legal
12902 /// icmp immediate, that is the target has icmp instructions which can compare
12903 /// a register against the immediate without having to materialize the
12904 /// immediate into a register.
12905 bool ARMTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
12906   // Thumb2 and ARM modes can use cmn for negative immediates.
12907   if (!Subtarget->isThumb())
12908     return ARM_AM::getSOImmVal(std::abs(Imm)) != -1;
12909   if (Subtarget->isThumb2())
12910     return ARM_AM::getT2SOImmVal(std::abs(Imm)) != -1;
12911   // Thumb1 doesn't have cmn, and only 8-bit immediates.
12912   return Imm >= 0 && Imm <= 255;
12913 }
12914 
12915 /// isLegalAddImmediate - Return true if the specified immediate is a legal add
12916 /// *or sub* immediate, that is the target has add or sub instructions which can
12917 /// add a register with the immediate without having to materialize the
12918 /// immediate into a register.
12919 bool ARMTargetLowering::isLegalAddImmediate(int64_t Imm) const {
12920   // Same encoding for add/sub, just flip the sign.
12921   int64_t AbsImm = std::abs(Imm);
12922   if (!Subtarget->isThumb())
12923     return ARM_AM::getSOImmVal(AbsImm) != -1;
12924   if (Subtarget->isThumb2())
12925     return ARM_AM::getT2SOImmVal(AbsImm) != -1;
12926   // Thumb1 only has 8-bit unsigned immediate.
12927   return AbsImm >= 0 && AbsImm <= 255;
12928 }
12929 
12930 static bool getARMIndexedAddressParts(SDNode *Ptr, EVT VT,
12931                                       bool isSEXTLoad, SDValue &Base,
12932                                       SDValue &Offset, bool &isInc,
12933                                       SelectionDAG &DAG) {
12934   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12935     return false;
12936 
12937   if (VT == MVT::i16 || ((VT == MVT::i8 || VT == MVT::i1) && isSEXTLoad)) {
12938     // AddressingMode 3
12939     Base = Ptr->getOperand(0);
12940     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12941       int RHSC = (int)RHS->getZExtValue();
12942       if (RHSC < 0 && RHSC > -256) {
12943         assert(Ptr->getOpcode() == ISD::ADD);
12944         isInc = false;
12945         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12946         return true;
12947       }
12948     }
12949     isInc = (Ptr->getOpcode() == ISD::ADD);
12950     Offset = Ptr->getOperand(1);
12951     return true;
12952   } else if (VT == MVT::i32 || VT == MVT::i8 || VT == MVT::i1) {
12953     // AddressingMode 2
12954     if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12955       int RHSC = (int)RHS->getZExtValue();
12956       if (RHSC < 0 && RHSC > -0x1000) {
12957         assert(Ptr->getOpcode() == ISD::ADD);
12958         isInc = false;
12959         Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
12960         Base = Ptr->getOperand(0);
12961         return true;
12962       }
12963     }
12964 
12965     if (Ptr->getOpcode() == ISD::ADD) {
12966       isInc = true;
12967       ARM_AM::ShiftOpc ShOpcVal=
12968         ARM_AM::getShiftOpcForNode(Ptr->getOperand(0).getOpcode());
12969       if (ShOpcVal != ARM_AM::no_shift) {
12970         Base = Ptr->getOperand(1);
12971         Offset = Ptr->getOperand(0);
12972       } else {
12973         Base = Ptr->getOperand(0);
12974         Offset = Ptr->getOperand(1);
12975       }
12976       return true;
12977     }
12978 
12979     isInc = (Ptr->getOpcode() == ISD::ADD);
12980     Base = Ptr->getOperand(0);
12981     Offset = Ptr->getOperand(1);
12982     return true;
12983   }
12984 
12985   // FIXME: Use VLDM / VSTM to emulate indexed FP load / store.
12986   return false;
12987 }
12988 
12989 static bool getT2IndexedAddressParts(SDNode *Ptr, EVT VT,
12990                                      bool isSEXTLoad, SDValue &Base,
12991                                      SDValue &Offset, bool &isInc,
12992                                      SelectionDAG &DAG) {
12993   if (Ptr->getOpcode() != ISD::ADD && Ptr->getOpcode() != ISD::SUB)
12994     return false;
12995 
12996   Base = Ptr->getOperand(0);
12997   if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Ptr->getOperand(1))) {
12998     int RHSC = (int)RHS->getZExtValue();
12999     if (RHSC < 0 && RHSC > -0x100) { // 8 bits.
13000       assert(Ptr->getOpcode() == ISD::ADD);
13001       isInc = false;
13002       Offset = DAG.getConstant(-RHSC, SDLoc(Ptr), RHS->getValueType(0));
13003       return true;
13004     } else if (RHSC > 0 && RHSC < 0x100) { // 8 bit, no zero.
13005       isInc = Ptr->getOpcode() == ISD::ADD;
13006       Offset = DAG.getConstant(RHSC, SDLoc(Ptr), RHS->getValueType(0));
13007       return true;
13008     }
13009   }
13010 
13011   return false;
13012 }
13013 
13014 /// getPreIndexedAddressParts - returns true by value, base pointer and
13015 /// offset pointer and addressing mode by reference if the node's address
13016 /// can be legally represented as pre-indexed load / store address.
13017 bool
13018 ARMTargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
13019                                              SDValue &Offset,
13020                                              ISD::MemIndexedMode &AM,
13021                                              SelectionDAG &DAG) const {
13022   if (Subtarget->isThumb1Only())
13023     return false;
13024 
13025   EVT VT;
13026   SDValue Ptr;
13027   bool isSEXTLoad = false;
13028   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13029     Ptr = LD->getBasePtr();
13030     VT  = LD->getMemoryVT();
13031     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13032   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13033     Ptr = ST->getBasePtr();
13034     VT  = ST->getMemoryVT();
13035   } else
13036     return false;
13037 
13038   bool isInc;
13039   bool isLegal = false;
13040   if (Subtarget->isThumb2())
13041     isLegal = getT2IndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13042                                        Offset, isInc, DAG);
13043   else
13044     isLegal = getARMIndexedAddressParts(Ptr.getNode(), VT, isSEXTLoad, Base,
13045                                         Offset, isInc, DAG);
13046   if (!isLegal)
13047     return false;
13048 
13049   AM = isInc ? ISD::PRE_INC : ISD::PRE_DEC;
13050   return true;
13051 }
13052 
13053 /// getPostIndexedAddressParts - returns true by value, base pointer and
13054 /// offset pointer and addressing mode by reference if this node can be
13055 /// combined with a load / store to form a post-indexed load / store.
13056 bool ARMTargetLowering::getPostIndexedAddressParts(SDNode *N, SDNode *Op,
13057                                                    SDValue &Base,
13058                                                    SDValue &Offset,
13059                                                    ISD::MemIndexedMode &AM,
13060                                                    SelectionDAG &DAG) const {
13061   EVT VT;
13062   SDValue Ptr;
13063   bool isSEXTLoad = false, isNonExt;
13064   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
13065     VT  = LD->getMemoryVT();
13066     Ptr = LD->getBasePtr();
13067     isSEXTLoad = LD->getExtensionType() == ISD::SEXTLOAD;
13068     isNonExt = LD->getExtensionType() == ISD::NON_EXTLOAD;
13069   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
13070     VT  = ST->getMemoryVT();
13071     Ptr = ST->getBasePtr();
13072     isNonExt = !ST->isTruncatingStore();
13073   } else
13074     return false;
13075 
13076   if (Subtarget->isThumb1Only()) {
13077     // Thumb-1 can do a limited post-inc load or store as an updating LDM. It
13078     // must be non-extending/truncating, i32, with an offset of 4.
13079     assert(Op->getValueType(0) == MVT::i32 && "Non-i32 post-inc op?!");
13080     if (Op->getOpcode() != ISD::ADD || !isNonExt)
13081       return false;
13082     auto *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1));
13083     if (!RHS || RHS->getZExtValue() != 4)
13084       return false;
13085 
13086     Offset = Op->getOperand(1);
13087     Base = Op->getOperand(0);
13088     AM = ISD::POST_INC;
13089     return true;
13090   }
13091 
13092   bool isInc;
13093   bool isLegal = false;
13094   if (Subtarget->isThumb2())
13095     isLegal = getT2IndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13096                                        isInc, DAG);
13097   else
13098     isLegal = getARMIndexedAddressParts(Op, VT, isSEXTLoad, Base, Offset,
13099                                         isInc, DAG);
13100   if (!isLegal)
13101     return false;
13102 
13103   if (Ptr != Base) {
13104     // Swap base ptr and offset to catch more post-index load / store when
13105     // it's legal. In Thumb2 mode, offset must be an immediate.
13106     if (Ptr == Offset && Op->getOpcode() == ISD::ADD &&
13107         !Subtarget->isThumb2())
13108       std::swap(Base, Offset);
13109 
13110     // Post-indexed load / store update the base pointer.
13111     if (Ptr != Base)
13112       return false;
13113   }
13114 
13115   AM = isInc ? ISD::POST_INC : ISD::POST_DEC;
13116   return true;
13117 }
13118 
13119 void ARMTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
13120                                                       KnownBits &Known,
13121                                                       const APInt &DemandedElts,
13122                                                       const SelectionDAG &DAG,
13123                                                       unsigned Depth) const {
13124   unsigned BitWidth = Known.getBitWidth();
13125   Known.resetAll();
13126   switch (Op.getOpcode()) {
13127   default: break;
13128   case ARMISD::ADDC:
13129   case ARMISD::ADDE:
13130   case ARMISD::SUBC:
13131   case ARMISD::SUBE:
13132     // Special cases when we convert a carry to a boolean.
13133     if (Op.getResNo() == 0) {
13134       SDValue LHS = Op.getOperand(0);
13135       SDValue RHS = Op.getOperand(1);
13136       // (ADDE 0, 0, C) will give us a single bit.
13137       if (Op->getOpcode() == ARMISD::ADDE && isNullConstant(LHS) &&
13138           isNullConstant(RHS)) {
13139         Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
13140         return;
13141       }
13142     }
13143     break;
13144   case ARMISD::CMOV: {
13145     // Bits are known zero/one if known on the LHS and RHS.
13146     DAG.computeKnownBits(Op.getOperand(0), Known, Depth+1);
13147     if (Known.isUnknown())
13148       return;
13149 
13150     KnownBits KnownRHS;
13151     DAG.computeKnownBits(Op.getOperand(1), KnownRHS, Depth+1);
13152     Known.Zero &= KnownRHS.Zero;
13153     Known.One  &= KnownRHS.One;
13154     return;
13155   }
13156   case ISD::INTRINSIC_W_CHAIN: {
13157     ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
13158     Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
13159     switch (IntID) {
13160     default: return;
13161     case Intrinsic::arm_ldaex:
13162     case Intrinsic::arm_ldrex: {
13163       EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
13164       unsigned MemBits = VT.getScalarSizeInBits();
13165       Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
13166       return;
13167     }
13168     }
13169   }
13170   case ARMISD::BFI: {
13171     // Conservatively, we can recurse down the first operand
13172     // and just mask out all affected bits.
13173     DAG.computeKnownBits(Op.getOperand(0), Known, Depth + 1);
13174 
13175     // The operand to BFI is already a mask suitable for removing the bits it
13176     // sets.
13177     ConstantSDNode *CI = cast<ConstantSDNode>(Op.getOperand(2));
13178     const APInt &Mask = CI->getAPIntValue();
13179     Known.Zero &= Mask;
13180     Known.One &= Mask;
13181     return;
13182   }
13183   }
13184 }
13185 
13186 //===----------------------------------------------------------------------===//
13187 //                           ARM Inline Assembly Support
13188 //===----------------------------------------------------------------------===//
13189 
13190 bool ARMTargetLowering::ExpandInlineAsm(CallInst *CI) const {
13191   // Looking for "rev" which is V6+.
13192   if (!Subtarget->hasV6Ops())
13193     return false;
13194 
13195   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
13196   std::string AsmStr = IA->getAsmString();
13197   SmallVector<StringRef, 4> AsmPieces;
13198   SplitString(AsmStr, AsmPieces, ";\n");
13199 
13200   switch (AsmPieces.size()) {
13201   default: return false;
13202   case 1:
13203     AsmStr = AsmPieces[0];
13204     AsmPieces.clear();
13205     SplitString(AsmStr, AsmPieces, " \t,");
13206 
13207     // rev $0, $1
13208     if (AsmPieces.size() == 3 &&
13209         AsmPieces[0] == "rev" && AsmPieces[1] == "$0" && AsmPieces[2] == "$1" &&
13210         IA->getConstraintString().compare(0, 4, "=l,l") == 0) {
13211       IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
13212       if (Ty && Ty->getBitWidth() == 32)
13213         return IntrinsicLowering::LowerToByteSwap(CI);
13214     }
13215     break;
13216   }
13217 
13218   return false;
13219 }
13220 
13221 const char *ARMTargetLowering::LowerXConstraint(EVT ConstraintVT) const {
13222   // At this point, we have to lower this constraint to something else, so we
13223   // lower it to an "r" or "w". However, by doing this we will force the result
13224   // to be in register, while the X constraint is much more permissive.
13225   //
13226   // Although we are correct (we are free to emit anything, without
13227   // constraints), we might break use cases that would expect us to be more
13228   // efficient and emit something else.
13229   if (!Subtarget->hasVFP2())
13230     return "r";
13231   if (ConstraintVT.isFloatingPoint())
13232     return "w";
13233   if (ConstraintVT.isVector() && Subtarget->hasNEON() &&
13234      (ConstraintVT.getSizeInBits() == 64 ||
13235       ConstraintVT.getSizeInBits() == 128))
13236     return "w";
13237 
13238   return "r";
13239 }
13240 
13241 /// getConstraintType - Given a constraint letter, return the type of
13242 /// constraint it is for this target.
13243 ARMTargetLowering::ConstraintType
13244 ARMTargetLowering::getConstraintType(StringRef Constraint) const {
13245   if (Constraint.size() == 1) {
13246     switch (Constraint[0]) {
13247     default:  break;
13248     case 'l': return C_RegisterClass;
13249     case 'w': return C_RegisterClass;
13250     case 'h': return C_RegisterClass;
13251     case 'x': return C_RegisterClass;
13252     case 't': return C_RegisterClass;
13253     case 'j': return C_Other; // Constant for movw.
13254       // An address with a single base register. Due to the way we
13255       // currently handle addresses it is the same as an 'r' memory constraint.
13256     case 'Q': return C_Memory;
13257     }
13258   } else if (Constraint.size() == 2) {
13259     switch (Constraint[0]) {
13260     default: break;
13261     // All 'U+' constraints are addresses.
13262     case 'U': return C_Memory;
13263     }
13264   }
13265   return TargetLowering::getConstraintType(Constraint);
13266 }
13267 
13268 /// Examine constraint type and operand type and determine a weight value.
13269 /// This object must already have been set up with the operand type
13270 /// and the current alternative constraint selected.
13271 TargetLowering::ConstraintWeight
13272 ARMTargetLowering::getSingleConstraintMatchWeight(
13273     AsmOperandInfo &info, const char *constraint) const {
13274   ConstraintWeight weight = CW_Invalid;
13275   Value *CallOperandVal = info.CallOperandVal;
13276     // If we don't have a value, we can't do a match,
13277     // but allow it at the lowest weight.
13278   if (!CallOperandVal)
13279     return CW_Default;
13280   Type *type = CallOperandVal->getType();
13281   // Look at the constraint type.
13282   switch (*constraint) {
13283   default:
13284     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
13285     break;
13286   case 'l':
13287     if (type->isIntegerTy()) {
13288       if (Subtarget->isThumb())
13289         weight = CW_SpecificReg;
13290       else
13291         weight = CW_Register;
13292     }
13293     break;
13294   case 'w':
13295     if (type->isFloatingPointTy())
13296       weight = CW_Register;
13297     break;
13298   }
13299   return weight;
13300 }
13301 
13302 using RCPair = std::pair<unsigned, const TargetRegisterClass *>;
13303 
13304 RCPair ARMTargetLowering::getRegForInlineAsmConstraint(
13305     const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
13306   if (Constraint.size() == 1) {
13307     // GCC ARM Constraint Letters
13308     switch (Constraint[0]) {
13309     case 'l': // Low regs or general regs.
13310       if (Subtarget->isThumb())
13311         return RCPair(0U, &ARM::tGPRRegClass);
13312       return RCPair(0U, &ARM::GPRRegClass);
13313     case 'h': // High regs or no regs.
13314       if (Subtarget->isThumb())
13315         return RCPair(0U, &ARM::hGPRRegClass);
13316       break;
13317     case 'r':
13318       if (Subtarget->isThumb1Only())
13319         return RCPair(0U, &ARM::tGPRRegClass);
13320       return RCPair(0U, &ARM::GPRRegClass);
13321     case 'w':
13322       if (VT == MVT::Other)
13323         break;
13324       if (VT == MVT::f32)
13325         return RCPair(0U, &ARM::SPRRegClass);
13326       if (VT.getSizeInBits() == 64)
13327         return RCPair(0U, &ARM::DPRRegClass);
13328       if (VT.getSizeInBits() == 128)
13329         return RCPair(0U, &ARM::QPRRegClass);
13330       break;
13331     case 'x':
13332       if (VT == MVT::Other)
13333         break;
13334       if (VT == MVT::f32)
13335         return RCPair(0U, &ARM::SPR_8RegClass);
13336       if (VT.getSizeInBits() == 64)
13337         return RCPair(0U, &ARM::DPR_8RegClass);
13338       if (VT.getSizeInBits() == 128)
13339         return RCPair(0U, &ARM::QPR_8RegClass);
13340       break;
13341     case 't':
13342       if (VT == MVT::f32 || VT == MVT::i32)
13343         return RCPair(0U, &ARM::SPRRegClass);
13344       break;
13345     }
13346   }
13347   if (StringRef("{cc}").equals_lower(Constraint))
13348     return std::make_pair(unsigned(ARM::CPSR), &ARM::CCRRegClass);
13349 
13350   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
13351 }
13352 
13353 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
13354 /// vector.  If it is invalid, don't add anything to Ops.
13355 void ARMTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
13356                                                      std::string &Constraint,
13357                                                      std::vector<SDValue>&Ops,
13358                                                      SelectionDAG &DAG) const {
13359   SDValue Result;
13360 
13361   // Currently only support length 1 constraints.
13362   if (Constraint.length() != 1) return;
13363 
13364   char ConstraintLetter = Constraint[0];
13365   switch (ConstraintLetter) {
13366   default: break;
13367   case 'j':
13368   case 'I': case 'J': case 'K': case 'L':
13369   case 'M': case 'N': case 'O':
13370     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
13371     if (!C)
13372       return;
13373 
13374     int64_t CVal64 = C->getSExtValue();
13375     int CVal = (int) CVal64;
13376     // None of these constraints allow values larger than 32 bits.  Check
13377     // that the value fits in an int.
13378     if (CVal != CVal64)
13379       return;
13380 
13381     switch (ConstraintLetter) {
13382       case 'j':
13383         // Constant suitable for movw, must be between 0 and
13384         // 65535.
13385         if (Subtarget->hasV6T2Ops())
13386           if (CVal >= 0 && CVal <= 65535)
13387             break;
13388         return;
13389       case 'I':
13390         if (Subtarget->isThumb1Only()) {
13391           // This must be a constant between 0 and 255, for ADD
13392           // immediates.
13393           if (CVal >= 0 && CVal <= 255)
13394             break;
13395         } else if (Subtarget->isThumb2()) {
13396           // A constant that can be used as an immediate value in a
13397           // data-processing instruction.
13398           if (ARM_AM::getT2SOImmVal(CVal) != -1)
13399             break;
13400         } else {
13401           // A constant that can be used as an immediate value in a
13402           // data-processing instruction.
13403           if (ARM_AM::getSOImmVal(CVal) != -1)
13404             break;
13405         }
13406         return;
13407 
13408       case 'J':
13409         if (Subtarget->isThumb1Only()) {
13410           // This must be a constant between -255 and -1, for negated ADD
13411           // immediates. This can be used in GCC with an "n" modifier that
13412           // prints the negated value, for use with SUB instructions. It is
13413           // not useful otherwise but is implemented for compatibility.
13414           if (CVal >= -255 && CVal <= -1)
13415             break;
13416         } else {
13417           // This must be a constant between -4095 and 4095. It is not clear
13418           // what this constraint is intended for. Implemented for
13419           // compatibility with GCC.
13420           if (CVal >= -4095 && CVal <= 4095)
13421             break;
13422         }
13423         return;
13424 
13425       case 'K':
13426         if (Subtarget->isThumb1Only()) {
13427           // A 32-bit value where only one byte has a nonzero value. Exclude
13428           // zero to match GCC. This constraint is used by GCC internally for
13429           // constants that can be loaded with a move/shift combination.
13430           // It is not useful otherwise but is implemented for compatibility.
13431           if (CVal != 0 && ARM_AM::isThumbImmShiftedVal(CVal))
13432             break;
13433         } else if (Subtarget->isThumb2()) {
13434           // A constant whose bitwise inverse can be used as an immediate
13435           // value in a data-processing instruction. This can be used in GCC
13436           // with a "B" modifier that prints the inverted value, for use with
13437           // BIC and MVN instructions. It is not useful otherwise but is
13438           // implemented for compatibility.
13439           if (ARM_AM::getT2SOImmVal(~CVal) != -1)
13440             break;
13441         } else {
13442           // A constant whose bitwise inverse can be used as an immediate
13443           // value in a data-processing instruction. This can be used in GCC
13444           // with a "B" modifier that prints the inverted value, for use with
13445           // BIC and MVN instructions. It is not useful otherwise but is
13446           // implemented for compatibility.
13447           if (ARM_AM::getSOImmVal(~CVal) != -1)
13448             break;
13449         }
13450         return;
13451 
13452       case 'L':
13453         if (Subtarget->isThumb1Only()) {
13454           // This must be a constant between -7 and 7,
13455           // for 3-operand ADD/SUB immediate instructions.
13456           if (CVal >= -7 && CVal < 7)
13457             break;
13458         } else if (Subtarget->isThumb2()) {
13459           // A constant whose negation can be used as an immediate value in a
13460           // data-processing instruction. This can be used in GCC with an "n"
13461           // modifier that prints the negated value, for use with SUB
13462           // instructions. It is not useful otherwise but is implemented for
13463           // compatibility.
13464           if (ARM_AM::getT2SOImmVal(-CVal) != -1)
13465             break;
13466         } else {
13467           // A constant whose negation can be used as an immediate value in a
13468           // data-processing instruction. This can be used in GCC with an "n"
13469           // modifier that prints the negated value, for use with SUB
13470           // instructions. It is not useful otherwise but is implemented for
13471           // compatibility.
13472           if (ARM_AM::getSOImmVal(-CVal) != -1)
13473             break;
13474         }
13475         return;
13476 
13477       case 'M':
13478         if (Subtarget->isThumb1Only()) {
13479           // This must be a multiple of 4 between 0 and 1020, for
13480           // ADD sp + immediate.
13481           if ((CVal >= 0 && CVal <= 1020) && ((CVal & 3) == 0))
13482             break;
13483         } else {
13484           // A power of two or a constant between 0 and 32.  This is used in
13485           // GCC for the shift amount on shifted register operands, but it is
13486           // useful in general for any shift amounts.
13487           if ((CVal >= 0 && CVal <= 32) || ((CVal & (CVal - 1)) == 0))
13488             break;
13489         }
13490         return;
13491 
13492       case 'N':
13493         if (Subtarget->isThumb()) {  // FIXME thumb2
13494           // This must be a constant between 0 and 31, for shift amounts.
13495           if (CVal >= 0 && CVal <= 31)
13496             break;
13497         }
13498         return;
13499 
13500       case 'O':
13501         if (Subtarget->isThumb()) {  // FIXME thumb2
13502           // This must be a multiple of 4 between -508 and 508, for
13503           // ADD/SUB sp = sp + immediate.
13504           if ((CVal >= -508 && CVal <= 508) && ((CVal & 3) == 0))
13505             break;
13506         }
13507         return;
13508     }
13509     Result = DAG.getTargetConstant(CVal, SDLoc(Op), Op.getValueType());
13510     break;
13511   }
13512 
13513   if (Result.getNode()) {
13514     Ops.push_back(Result);
13515     return;
13516   }
13517   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
13518 }
13519 
13520 static RTLIB::Libcall getDivRemLibcall(
13521     const SDNode *N, MVT::SimpleValueType SVT) {
13522   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13523           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13524          "Unhandled Opcode in getDivRemLibcall");
13525   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13526                   N->getOpcode() == ISD::SREM;
13527   RTLIB::Libcall LC;
13528   switch (SVT) {
13529   default: llvm_unreachable("Unexpected request for libcall!");
13530   case MVT::i8:  LC = isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
13531   case MVT::i16: LC = isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
13532   case MVT::i32: LC = isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
13533   case MVT::i64: LC = isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
13534   }
13535   return LC;
13536 }
13537 
13538 static TargetLowering::ArgListTy getDivRemArgList(
13539     const SDNode *N, LLVMContext *Context, const ARMSubtarget *Subtarget) {
13540   assert((N->getOpcode() == ISD::SDIVREM || N->getOpcode() == ISD::UDIVREM ||
13541           N->getOpcode() == ISD::SREM    || N->getOpcode() == ISD::UREM) &&
13542          "Unhandled Opcode in getDivRemArgList");
13543   bool isSigned = N->getOpcode() == ISD::SDIVREM ||
13544                   N->getOpcode() == ISD::SREM;
13545   TargetLowering::ArgListTy Args;
13546   TargetLowering::ArgListEntry Entry;
13547   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
13548     EVT ArgVT = N->getOperand(i).getValueType();
13549     Type *ArgTy = ArgVT.getTypeForEVT(*Context);
13550     Entry.Node = N->getOperand(i);
13551     Entry.Ty = ArgTy;
13552     Entry.IsSExt = isSigned;
13553     Entry.IsZExt = !isSigned;
13554     Args.push_back(Entry);
13555   }
13556   if (Subtarget->isTargetWindows() && Args.size() >= 2)
13557     std::swap(Args[0], Args[1]);
13558   return Args;
13559 }
13560 
13561 SDValue ARMTargetLowering::LowerDivRem(SDValue Op, SelectionDAG &DAG) const {
13562   assert((Subtarget->isTargetAEABI() || Subtarget->isTargetAndroid() ||
13563           Subtarget->isTargetGNUAEABI() || Subtarget->isTargetMuslAEABI() ||
13564           Subtarget->isTargetWindows()) &&
13565          "Register-based DivRem lowering only");
13566   unsigned Opcode = Op->getOpcode();
13567   assert((Opcode == ISD::SDIVREM || Opcode == ISD::UDIVREM) &&
13568          "Invalid opcode for Div/Rem lowering");
13569   bool isSigned = (Opcode == ISD::SDIVREM);
13570   EVT VT = Op->getValueType(0);
13571   Type *Ty = VT.getTypeForEVT(*DAG.getContext());
13572   SDLoc dl(Op);
13573 
13574   // If the target has hardware divide, use divide + multiply + subtract:
13575   //     div = a / b
13576   //     rem = a - b * div
13577   //     return {div, rem}
13578   // This should be lowered into UDIV/SDIV + MLS later on.
13579   bool hasDivide = Subtarget->isThumb() ? Subtarget->hasDivideInThumbMode()
13580                                         : Subtarget->hasDivideInARMMode();
13581   if (hasDivide && Op->getValueType(0).isSimple() &&
13582       Op->getSimpleValueType(0) == MVT::i32) {
13583     unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
13584     const SDValue Dividend = Op->getOperand(0);
13585     const SDValue Divisor = Op->getOperand(1);
13586     SDValue Div = DAG.getNode(DivOpcode, dl, VT, Dividend, Divisor);
13587     SDValue Mul = DAG.getNode(ISD::MUL, dl, VT, Div, Divisor);
13588     SDValue Rem = DAG.getNode(ISD::SUB, dl, VT, Dividend, Mul);
13589 
13590     SDValue Values[2] = {Div, Rem};
13591     return DAG.getNode(ISD::MERGE_VALUES, dl, DAG.getVTList(VT, VT), Values);
13592   }
13593 
13594   RTLIB::Libcall LC = getDivRemLibcall(Op.getNode(),
13595                                        VT.getSimpleVT().SimpleTy);
13596   SDValue InChain = DAG.getEntryNode();
13597 
13598   TargetLowering::ArgListTy Args = getDivRemArgList(Op.getNode(),
13599                                                     DAG.getContext(),
13600                                                     Subtarget);
13601 
13602   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13603                                          getPointerTy(DAG.getDataLayout()));
13604 
13605   Type *RetTy = StructType::get(Ty, Ty);
13606 
13607   if (Subtarget->isTargetWindows())
13608     InChain = WinDBZCheckDenominator(DAG, Op.getNode(), InChain);
13609 
13610   TargetLowering::CallLoweringInfo CLI(DAG);
13611   CLI.setDebugLoc(dl).setChain(InChain)
13612     .setCallee(getLibcallCallingConv(LC), RetTy, Callee, std::move(Args))
13613     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13614 
13615   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13616   return CallInfo.first;
13617 }
13618 
13619 // Lowers REM using divmod helpers
13620 // see RTABI section 4.2/4.3
13621 SDValue ARMTargetLowering::LowerREM(SDNode *N, SelectionDAG &DAG) const {
13622   // Build return types (div and rem)
13623   std::vector<Type*> RetTyParams;
13624   Type *RetTyElement;
13625 
13626   switch (N->getValueType(0).getSimpleVT().SimpleTy) {
13627   default: llvm_unreachable("Unexpected request for libcall!");
13628   case MVT::i8:   RetTyElement = Type::getInt8Ty(*DAG.getContext());  break;
13629   case MVT::i16:  RetTyElement = Type::getInt16Ty(*DAG.getContext()); break;
13630   case MVT::i32:  RetTyElement = Type::getInt32Ty(*DAG.getContext()); break;
13631   case MVT::i64:  RetTyElement = Type::getInt64Ty(*DAG.getContext()); break;
13632   }
13633 
13634   RetTyParams.push_back(RetTyElement);
13635   RetTyParams.push_back(RetTyElement);
13636   ArrayRef<Type*> ret = ArrayRef<Type*>(RetTyParams);
13637   Type *RetTy = StructType::get(*DAG.getContext(), ret);
13638 
13639   RTLIB::Libcall LC = getDivRemLibcall(N, N->getValueType(0).getSimpleVT().
13640                                                              SimpleTy);
13641   SDValue InChain = DAG.getEntryNode();
13642   TargetLowering::ArgListTy Args = getDivRemArgList(N, DAG.getContext(),
13643                                                     Subtarget);
13644   bool isSigned = N->getOpcode() == ISD::SREM;
13645   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13646                                          getPointerTy(DAG.getDataLayout()));
13647 
13648   if (Subtarget->isTargetWindows())
13649     InChain = WinDBZCheckDenominator(DAG, N, InChain);
13650 
13651   // Lower call
13652   CallLoweringInfo CLI(DAG);
13653   CLI.setChain(InChain)
13654      .setCallee(CallingConv::ARM_AAPCS, RetTy, Callee, std::move(Args))
13655      .setSExtResult(isSigned).setZExtResult(!isSigned).setDebugLoc(SDLoc(N));
13656   std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
13657 
13658   // Return second (rem) result operand (first contains div)
13659   SDNode *ResNode = CallResult.first.getNode();
13660   assert(ResNode->getNumOperands() == 2 && "divmod should return two operands");
13661   return ResNode->getOperand(1);
13662 }
13663 
13664 SDValue
13665 ARMTargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const {
13666   assert(Subtarget->isTargetWindows() && "unsupported target platform");
13667   SDLoc DL(Op);
13668 
13669   // Get the inputs.
13670   SDValue Chain = Op.getOperand(0);
13671   SDValue Size  = Op.getOperand(1);
13672 
13673   SDValue Words = DAG.getNode(ISD::SRL, DL, MVT::i32, Size,
13674                               DAG.getConstant(2, DL, MVT::i32));
13675 
13676   SDValue Flag;
13677   Chain = DAG.getCopyToReg(Chain, DL, ARM::R4, Words, Flag);
13678   Flag = Chain.getValue(1);
13679 
13680   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13681   Chain = DAG.getNode(ARMISD::WIN__CHKSTK, DL, NodeTys, Chain, Flag);
13682 
13683   SDValue NewSP = DAG.getCopyFromReg(Chain, DL, ARM::SP, MVT::i32);
13684   Chain = NewSP.getValue(1);
13685 
13686   SDValue Ops[2] = { NewSP, Chain };
13687   return DAG.getMergeValues(Ops, DL);
13688 }
13689 
13690 SDValue ARMTargetLowering::LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) const {
13691   assert(Op.getValueType() == MVT::f64 && Subtarget->isFPOnlySP() &&
13692          "Unexpected type for custom-lowering FP_EXTEND");
13693 
13694   RTLIB::Libcall LC;
13695   LC = RTLIB::getFPEXT(Op.getOperand(0).getValueType(), Op.getValueType());
13696 
13697   SDValue SrcVal = Op.getOperand(0);
13698   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13699                      SDLoc(Op)).first;
13700 }
13701 
13702 SDValue ARMTargetLowering::LowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
13703   assert(Op.getOperand(0).getValueType() == MVT::f64 &&
13704          Subtarget->isFPOnlySP() &&
13705          "Unexpected type for custom-lowering FP_ROUND");
13706 
13707   RTLIB::Libcall LC;
13708   LC = RTLIB::getFPROUND(Op.getOperand(0).getValueType(), Op.getValueType());
13709 
13710   SDValue SrcVal = Op.getOperand(0);
13711   return makeLibCall(DAG, LC, Op.getValueType(), SrcVal, /*isSigned*/ false,
13712                      SDLoc(Op)).first;
13713 }
13714 
13715 bool
13716 ARMTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
13717   // The ARM target isn't yet aware of offsets.
13718   return false;
13719 }
13720 
13721 bool ARM::isBitFieldInvertedMask(unsigned v) {
13722   if (v == 0xffffffff)
13723     return false;
13724 
13725   // there can be 1's on either or both "outsides", all the "inside"
13726   // bits must be 0's
13727   return isShiftedMask_32(~v);
13728 }
13729 
13730 /// isFPImmLegal - Returns true if the target can instruction select the
13731 /// specified FP immediate natively. If false, the legalizer will
13732 /// materialize the FP immediate as a load from a constant pool.
13733 bool ARMTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
13734   if (!Subtarget->hasVFP3())
13735     return false;
13736   if (VT == MVT::f32)
13737     return ARM_AM::getFP32Imm(Imm) != -1;
13738   if (VT == MVT::f64 && !Subtarget->isFPOnlySP())
13739     return ARM_AM::getFP64Imm(Imm) != -1;
13740   return false;
13741 }
13742 
13743 /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
13744 /// MemIntrinsicNodes.  The associated MachineMemOperands record the alignment
13745 /// specified in the intrinsic calls.
13746 bool ARMTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
13747                                            const CallInst &I,
13748                                            MachineFunction &MF,
13749                                            unsigned Intrinsic) const {
13750   switch (Intrinsic) {
13751   case Intrinsic::arm_neon_vld1:
13752   case Intrinsic::arm_neon_vld2:
13753   case Intrinsic::arm_neon_vld3:
13754   case Intrinsic::arm_neon_vld4:
13755   case Intrinsic::arm_neon_vld2lane:
13756   case Intrinsic::arm_neon_vld3lane:
13757   case Intrinsic::arm_neon_vld4lane: {
13758     Info.opc = ISD::INTRINSIC_W_CHAIN;
13759     // Conservatively set memVT to the entire set of vectors loaded.
13760     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13761     uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
13762     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13763     Info.ptrVal = I.getArgOperand(0);
13764     Info.offset = 0;
13765     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13766     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13767     // volatile loads with NEON intrinsics not supported
13768     Info.flags = MachineMemOperand::MOLoad;
13769     return true;
13770   }
13771   case Intrinsic::arm_neon_vst1:
13772   case Intrinsic::arm_neon_vst2:
13773   case Intrinsic::arm_neon_vst3:
13774   case Intrinsic::arm_neon_vst4:
13775   case Intrinsic::arm_neon_vst2lane:
13776   case Intrinsic::arm_neon_vst3lane:
13777   case Intrinsic::arm_neon_vst4lane: {
13778     Info.opc = ISD::INTRINSIC_VOID;
13779     // Conservatively set memVT to the entire set of vectors stored.
13780     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13781     unsigned NumElts = 0;
13782     for (unsigned ArgI = 1, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
13783       Type *ArgTy = I.getArgOperand(ArgI)->getType();
13784       if (!ArgTy->isVectorTy())
13785         break;
13786       NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
13787     }
13788     Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
13789     Info.ptrVal = I.getArgOperand(0);
13790     Info.offset = 0;
13791     Value *AlignArg = I.getArgOperand(I.getNumArgOperands() - 1);
13792     Info.align = cast<ConstantInt>(AlignArg)->getZExtValue();
13793     // volatile stores with NEON intrinsics not supported
13794     Info.flags = MachineMemOperand::MOStore;
13795     return true;
13796   }
13797   case Intrinsic::arm_ldaex:
13798   case Intrinsic::arm_ldrex: {
13799     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13800     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
13801     Info.opc = ISD::INTRINSIC_W_CHAIN;
13802     Info.memVT = MVT::getVT(PtrTy->getElementType());
13803     Info.ptrVal = I.getArgOperand(0);
13804     Info.offset = 0;
13805     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13806     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
13807     return true;
13808   }
13809   case Intrinsic::arm_stlex:
13810   case Intrinsic::arm_strex: {
13811     auto &DL = I.getCalledFunction()->getParent()->getDataLayout();
13812     PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
13813     Info.opc = ISD::INTRINSIC_W_CHAIN;
13814     Info.memVT = MVT::getVT(PtrTy->getElementType());
13815     Info.ptrVal = I.getArgOperand(1);
13816     Info.offset = 0;
13817     Info.align = DL.getABITypeAlignment(PtrTy->getElementType());
13818     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
13819     return true;
13820   }
13821   case Intrinsic::arm_stlexd:
13822   case Intrinsic::arm_strexd:
13823     Info.opc = ISD::INTRINSIC_W_CHAIN;
13824     Info.memVT = MVT::i64;
13825     Info.ptrVal = I.getArgOperand(2);
13826     Info.offset = 0;
13827     Info.align = 8;
13828     Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
13829     return true;
13830 
13831   case Intrinsic::arm_ldaexd:
13832   case Intrinsic::arm_ldrexd:
13833     Info.opc = ISD::INTRINSIC_W_CHAIN;
13834     Info.memVT = MVT::i64;
13835     Info.ptrVal = I.getArgOperand(0);
13836     Info.offset = 0;
13837     Info.align = 8;
13838     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
13839     return true;
13840 
13841   default:
13842     break;
13843   }
13844 
13845   return false;
13846 }
13847 
13848 /// \brief Returns true if it is beneficial to convert a load of a constant
13849 /// to just the constant itself.
13850 bool ARMTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
13851                                                           Type *Ty) const {
13852   assert(Ty->isIntegerTy());
13853 
13854   unsigned Bits = Ty->getPrimitiveSizeInBits();
13855   if (Bits == 0 || Bits > 32)
13856     return false;
13857   return true;
13858 }
13859 
13860 bool ARMTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
13861                                                 unsigned Index) const {
13862   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
13863     return false;
13864 
13865   return (Index == 0 || Index == ResVT.getVectorNumElements());
13866 }
13867 
13868 Instruction* ARMTargetLowering::makeDMB(IRBuilder<> &Builder,
13869                                         ARM_MB::MemBOpt Domain) const {
13870   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
13871 
13872   // First, if the target has no DMB, see what fallback we can use.
13873   if (!Subtarget->hasDataBarrier()) {
13874     // Some ARMv6 cpus can support data barriers with an mcr instruction.
13875     // Thumb1 and pre-v6 ARM mode use a libcall instead and should never get
13876     // here.
13877     if (Subtarget->hasV6Ops() && !Subtarget->isThumb()) {
13878       Function *MCR = Intrinsic::getDeclaration(M, Intrinsic::arm_mcr);
13879       Value* args[6] = {Builder.getInt32(15), Builder.getInt32(0),
13880                         Builder.getInt32(0), Builder.getInt32(7),
13881                         Builder.getInt32(10), Builder.getInt32(5)};
13882       return Builder.CreateCall(MCR, args);
13883     } else {
13884       // Instead of using barriers, atomic accesses on these subtargets use
13885       // libcalls.
13886       llvm_unreachable("makeDMB on a target so old that it has no barriers");
13887     }
13888   } else {
13889     Function *DMB = Intrinsic::getDeclaration(M, Intrinsic::arm_dmb);
13890     // Only a full system barrier exists in the M-class architectures.
13891     Domain = Subtarget->isMClass() ? ARM_MB::SY : Domain;
13892     Constant *CDomain = Builder.getInt32(Domain);
13893     return Builder.CreateCall(DMB, CDomain);
13894   }
13895 }
13896 
13897 // Based on http://www.cl.cam.ac.uk/~pes20/cpp/cpp0xmappings.html
13898 Instruction *ARMTargetLowering::emitLeadingFence(IRBuilder<> &Builder,
13899                                                  Instruction *Inst,
13900                                                  AtomicOrdering Ord) const {
13901   switch (Ord) {
13902   case AtomicOrdering::NotAtomic:
13903   case AtomicOrdering::Unordered:
13904     llvm_unreachable("Invalid fence: unordered/non-atomic");
13905   case AtomicOrdering::Monotonic:
13906   case AtomicOrdering::Acquire:
13907     return nullptr; // Nothing to do
13908   case AtomicOrdering::SequentiallyConsistent:
13909     if (!Inst->hasAtomicStore())
13910       return nullptr; // Nothing to do
13911     LLVM_FALLTHROUGH;
13912   case AtomicOrdering::Release:
13913   case AtomicOrdering::AcquireRelease:
13914     if (Subtarget->preferISHSTBarriers())
13915       return makeDMB(Builder, ARM_MB::ISHST);
13916     // FIXME: add a comment with a link to documentation justifying this.
13917     else
13918       return makeDMB(Builder, ARM_MB::ISH);
13919   }
13920   llvm_unreachable("Unknown fence ordering in emitLeadingFence");
13921 }
13922 
13923 Instruction *ARMTargetLowering::emitTrailingFence(IRBuilder<> &Builder,
13924                                                   Instruction *Inst,
13925                                                   AtomicOrdering Ord) const {
13926   switch (Ord) {
13927   case AtomicOrdering::NotAtomic:
13928   case AtomicOrdering::Unordered:
13929     llvm_unreachable("Invalid fence: unordered/not-atomic");
13930   case AtomicOrdering::Monotonic:
13931   case AtomicOrdering::Release:
13932     return nullptr; // Nothing to do
13933   case AtomicOrdering::Acquire:
13934   case AtomicOrdering::AcquireRelease:
13935   case AtomicOrdering::SequentiallyConsistent:
13936     return makeDMB(Builder, ARM_MB::ISH);
13937   }
13938   llvm_unreachable("Unknown fence ordering in emitTrailingFence");
13939 }
13940 
13941 // Loads and stores less than 64-bits are already atomic; ones above that
13942 // are doomed anyway, so defer to the default libcall and blame the OS when
13943 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13944 // anything for those.
13945 bool ARMTargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
13946   unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
13947   return (Size == 64) && !Subtarget->isMClass();
13948 }
13949 
13950 // Loads and stores less than 64-bits are already atomic; ones above that
13951 // are doomed anyway, so defer to the default libcall and blame the OS when
13952 // things go wrong. Cortex M doesn't have ldrexd/strexd though, so don't emit
13953 // anything for those.
13954 // FIXME: ldrd and strd are atomic if the CPU has LPAE (e.g. A15 has that
13955 // guarantee, see DDI0406C ARM architecture reference manual,
13956 // sections A8.8.72-74 LDRD)
13957 TargetLowering::AtomicExpansionKind
13958 ARMTargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
13959   unsigned Size = LI->getType()->getPrimitiveSizeInBits();
13960   return ((Size == 64) && !Subtarget->isMClass()) ? AtomicExpansionKind::LLOnly
13961                                                   : AtomicExpansionKind::None;
13962 }
13963 
13964 // For the real atomic operations, we have ldrex/strex up to 32 bits,
13965 // and up to 64 bits on the non-M profiles
13966 TargetLowering::AtomicExpansionKind
13967 ARMTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
13968   unsigned Size = AI->getType()->getPrimitiveSizeInBits();
13969   bool hasAtomicRMW = !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13970   return (Size <= (Subtarget->isMClass() ? 32U : 64U) && hasAtomicRMW)
13971              ? AtomicExpansionKind::LLSC
13972              : AtomicExpansionKind::None;
13973 }
13974 
13975 bool ARMTargetLowering::shouldExpandAtomicCmpXchgInIR(
13976     AtomicCmpXchgInst *AI) const {
13977   // At -O0, fast-regalloc cannot cope with the live vregs necessary to
13978   // implement cmpxchg without spilling. If the address being exchanged is also
13979   // on the stack and close enough to the spill slot, this can lead to a
13980   // situation where the monitor always gets cleared and the atomic operation
13981   // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
13982   bool hasAtomicCmpXchg =
13983       !Subtarget->isThumb() || Subtarget->hasV8MBaselineOps();
13984   return getTargetMachine().getOptLevel() != 0 && hasAtomicCmpXchg;
13985 }
13986 
13987 bool ARMTargetLowering::shouldInsertFencesForAtomic(
13988     const Instruction *I) const {
13989   return InsertFencesForAtomic;
13990 }
13991 
13992 // This has so far only been implemented for MachO.
13993 bool ARMTargetLowering::useLoadStackGuardNode() const {
13994   return Subtarget->isTargetMachO();
13995 }
13996 
13997 bool ARMTargetLowering::canCombineStoreAndExtract(Type *VectorTy, Value *Idx,
13998                                                   unsigned &Cost) const {
13999   // If we do not have NEON, vector types are not natively supported.
14000   if (!Subtarget->hasNEON())
14001     return false;
14002 
14003   // Floating point values and vector values map to the same register file.
14004   // Therefore, although we could do a store extract of a vector type, this is
14005   // better to leave at float as we have more freedom in the addressing mode for
14006   // those.
14007   if (VectorTy->isFPOrFPVectorTy())
14008     return false;
14009 
14010   // If the index is unknown at compile time, this is very expensive to lower
14011   // and it is not possible to combine the store with the extract.
14012   if (!isa<ConstantInt>(Idx))
14013     return false;
14014 
14015   assert(VectorTy->isVectorTy() && "VectorTy is not a vector type");
14016   unsigned BitWidth = cast<VectorType>(VectorTy)->getBitWidth();
14017   // We can do a store + vector extract on any vector that fits perfectly in a D
14018   // or Q register.
14019   if (BitWidth == 64 || BitWidth == 128) {
14020     Cost = 0;
14021     return true;
14022   }
14023   return false;
14024 }
14025 
14026 bool ARMTargetLowering::isCheapToSpeculateCttz() const {
14027   return Subtarget->hasV6T2Ops();
14028 }
14029 
14030 bool ARMTargetLowering::isCheapToSpeculateCtlz() const {
14031   return Subtarget->hasV6T2Ops();
14032 }
14033 
14034 Value *ARMTargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
14035                                          AtomicOrdering Ord) const {
14036   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14037   Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
14038   bool IsAcquire = isAcquireOrStronger(Ord);
14039 
14040   // Since i64 isn't legal and intrinsics don't get type-lowered, the ldrexd
14041   // intrinsic must return {i32, i32} and we have to recombine them into a
14042   // single i64 here.
14043   if (ValTy->getPrimitiveSizeInBits() == 64) {
14044     Intrinsic::ID Int =
14045         IsAcquire ? Intrinsic::arm_ldaexd : Intrinsic::arm_ldrexd;
14046     Function *Ldrex = Intrinsic::getDeclaration(M, Int);
14047 
14048     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14049     Value *LoHi = Builder.CreateCall(Ldrex, Addr, "lohi");
14050 
14051     Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
14052     Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
14053     if (!Subtarget->isLittle())
14054       std::swap (Lo, Hi);
14055     Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
14056     Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
14057     return Builder.CreateOr(
14058         Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 32)), "val64");
14059   }
14060 
14061   Type *Tys[] = { Addr->getType() };
14062   Intrinsic::ID Int = IsAcquire ? Intrinsic::arm_ldaex : Intrinsic::arm_ldrex;
14063   Function *Ldrex = Intrinsic::getDeclaration(M, Int, Tys);
14064 
14065   return Builder.CreateTruncOrBitCast(
14066       Builder.CreateCall(Ldrex, Addr),
14067       cast<PointerType>(Addr->getType())->getElementType());
14068 }
14069 
14070 void ARMTargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
14071     IRBuilder<> &Builder) const {
14072   if (!Subtarget->hasV7Ops())
14073     return;
14074   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14075   Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::arm_clrex));
14076 }
14077 
14078 Value *ARMTargetLowering::emitStoreConditional(IRBuilder<> &Builder, Value *Val,
14079                                                Value *Addr,
14080                                                AtomicOrdering Ord) const {
14081   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
14082   bool IsRelease = isReleaseOrStronger(Ord);
14083 
14084   // Since the intrinsics must have legal type, the i64 intrinsics take two
14085   // parameters: "i32, i32". We must marshal Val into the appropriate form
14086   // before the call.
14087   if (Val->getType()->getPrimitiveSizeInBits() == 64) {
14088     Intrinsic::ID Int =
14089         IsRelease ? Intrinsic::arm_stlexd : Intrinsic::arm_strexd;
14090     Function *Strex = Intrinsic::getDeclaration(M, Int);
14091     Type *Int32Ty = Type::getInt32Ty(M->getContext());
14092 
14093     Value *Lo = Builder.CreateTrunc(Val, Int32Ty, "lo");
14094     Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 32), Int32Ty, "hi");
14095     if (!Subtarget->isLittle())
14096       std::swap(Lo, Hi);
14097     Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
14098     return Builder.CreateCall(Strex, {Lo, Hi, Addr});
14099   }
14100 
14101   Intrinsic::ID Int = IsRelease ? Intrinsic::arm_stlex : Intrinsic::arm_strex;
14102   Type *Tys[] = { Addr->getType() };
14103   Function *Strex = Intrinsic::getDeclaration(M, Int, Tys);
14104 
14105   return Builder.CreateCall(
14106       Strex, {Builder.CreateZExtOrBitCast(
14107                   Val, Strex->getFunctionType()->getParamType(0)),
14108               Addr});
14109 }
14110 
14111 /// A helper function for determining the number of interleaved accesses we
14112 /// will generate when lowering accesses of the given type.
14113 unsigned
14114 ARMTargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
14115                                              const DataLayout &DL) const {
14116   return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
14117 }
14118 
14119 bool ARMTargetLowering::isLegalInterleavedAccessType(
14120     VectorType *VecTy, const DataLayout &DL) const {
14121 
14122   unsigned VecSize = DL.getTypeSizeInBits(VecTy);
14123   unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
14124 
14125   // Ensure the vector doesn't have f16 elements. Even though we could do an
14126   // i16 vldN, we can't hold the f16 vectors and will end up converting via
14127   // f32.
14128   if (VecTy->getElementType()->isHalfTy())
14129     return false;
14130 
14131   // Ensure the number of vector elements is greater than 1.
14132   if (VecTy->getNumElements() < 2)
14133     return false;
14134 
14135   // Ensure the element type is legal.
14136   if (ElSize != 8 && ElSize != 16 && ElSize != 32)
14137     return false;
14138 
14139   // Ensure the total vector size is 64 or a multiple of 128. Types larger than
14140   // 128 will be split into multiple interleaved accesses.
14141   return VecSize == 64 || VecSize % 128 == 0;
14142 }
14143 
14144 /// \brief Lower an interleaved load into a vldN intrinsic.
14145 ///
14146 /// E.g. Lower an interleaved load (Factor = 2):
14147 ///        %wide.vec = load <8 x i32>, <8 x i32>* %ptr, align 4
14148 ///        %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6>  ; Extract even elements
14149 ///        %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7>  ; Extract odd elements
14150 ///
14151 ///      Into:
14152 ///        %vld2 = { <4 x i32>, <4 x i32> } call llvm.arm.neon.vld2(%ptr, 4)
14153 ///        %vec0 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 0
14154 ///        %vec1 = extractelement { <4 x i32>, <4 x i32> } %vld2, i32 1
14155 bool ARMTargetLowering::lowerInterleavedLoad(
14156     LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
14157     ArrayRef<unsigned> Indices, unsigned Factor) const {
14158   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14159          "Invalid interleave factor");
14160   assert(!Shuffles.empty() && "Empty shufflevector input");
14161   assert(Shuffles.size() == Indices.size() &&
14162          "Unmatched number of shufflevectors and indices");
14163 
14164   VectorType *VecTy = Shuffles[0]->getType();
14165   Type *EltTy = VecTy->getVectorElementType();
14166 
14167   const DataLayout &DL = LI->getModule()->getDataLayout();
14168 
14169   // Skip if we do not have NEON and skip illegal vector types. We can
14170   // "legalize" wide vector types into multiple interleaved accesses as long as
14171   // the vector types are divisible by 128.
14172   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VecTy, DL))
14173     return false;
14174 
14175   unsigned NumLoads = getNumInterleavedAccesses(VecTy, DL);
14176 
14177   // A pointer vector can not be the return type of the ldN intrinsics. Need to
14178   // load integer vectors first and then convert to pointer vectors.
14179   if (EltTy->isPointerTy())
14180     VecTy =
14181         VectorType::get(DL.getIntPtrType(EltTy), VecTy->getVectorNumElements());
14182 
14183   IRBuilder<> Builder(LI);
14184 
14185   // The base address of the load.
14186   Value *BaseAddr = LI->getPointerOperand();
14187 
14188   if (NumLoads > 1) {
14189     // If we're going to generate more than one load, reset the sub-vector type
14190     // to something legal.
14191     VecTy = VectorType::get(VecTy->getVectorElementType(),
14192                             VecTy->getVectorNumElements() / NumLoads);
14193 
14194     // We will compute the pointer operand of each load from the original base
14195     // address using GEPs. Cast the base address to a pointer to the scalar
14196     // element type.
14197     BaseAddr = Builder.CreateBitCast(
14198         BaseAddr, VecTy->getVectorElementType()->getPointerTo(
14199                       LI->getPointerAddressSpace()));
14200   }
14201 
14202   assert(isTypeLegal(EVT::getEVT(VecTy)) && "Illegal vldN vector type!");
14203 
14204   Type *Int8Ptr = Builder.getInt8PtrTy(LI->getPointerAddressSpace());
14205   Type *Tys[] = {VecTy, Int8Ptr};
14206   static const Intrinsic::ID LoadInts[3] = {Intrinsic::arm_neon_vld2,
14207                                             Intrinsic::arm_neon_vld3,
14208                                             Intrinsic::arm_neon_vld4};
14209   Function *VldnFunc =
14210       Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
14211 
14212   // Holds sub-vectors extracted from the load intrinsic return values. The
14213   // sub-vectors are associated with the shufflevector instructions they will
14214   // replace.
14215   DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
14216 
14217   for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
14218     // If we're generating more than one load, compute the base address of
14219     // subsequent loads as an offset from the previous.
14220     if (LoadCount > 0)
14221       BaseAddr = Builder.CreateConstGEP1_32(
14222           BaseAddr, VecTy->getVectorNumElements() * Factor);
14223 
14224     SmallVector<Value *, 2> Ops;
14225     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14226     Ops.push_back(Builder.getInt32(LI->getAlignment()));
14227 
14228     CallInst *VldN = Builder.CreateCall(VldnFunc, Ops, "vldN");
14229 
14230     // Replace uses of each shufflevector with the corresponding vector loaded
14231     // by ldN.
14232     for (unsigned i = 0; i < Shuffles.size(); i++) {
14233       ShuffleVectorInst *SV = Shuffles[i];
14234       unsigned Index = Indices[i];
14235 
14236       Value *SubVec = Builder.CreateExtractValue(VldN, Index);
14237 
14238       // Convert the integer vector to pointer vector if the element is pointer.
14239       if (EltTy->isPointerTy())
14240         SubVec = Builder.CreateIntToPtr(
14241             SubVec, VectorType::get(SV->getType()->getVectorElementType(),
14242                                     VecTy->getVectorNumElements()));
14243 
14244       SubVecs[SV].push_back(SubVec);
14245     }
14246   }
14247 
14248   // Replace uses of the shufflevector instructions with the sub-vectors
14249   // returned by the load intrinsic. If a shufflevector instruction is
14250   // associated with more than one sub-vector, those sub-vectors will be
14251   // concatenated into a single wide vector.
14252   for (ShuffleVectorInst *SVI : Shuffles) {
14253     auto &SubVec = SubVecs[SVI];
14254     auto *WideVec =
14255         SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
14256     SVI->replaceAllUsesWith(WideVec);
14257   }
14258 
14259   return true;
14260 }
14261 
14262 /// \brief Lower an interleaved store into a vstN intrinsic.
14263 ///
14264 /// E.g. Lower an interleaved store (Factor = 3):
14265 ///        %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
14266 ///                                  <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
14267 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr, align 4
14268 ///
14269 ///      Into:
14270 ///        %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
14271 ///        %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
14272 ///        %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
14273 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14274 ///
14275 /// Note that the new shufflevectors will be removed and we'll only generate one
14276 /// vst3 instruction in CodeGen.
14277 ///
14278 /// Example for a more general valid mask (Factor 3). Lower:
14279 ///        %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
14280 ///                 <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
14281 ///        store <12 x i32> %i.vec, <12 x i32>* %ptr
14282 ///
14283 ///      Into:
14284 ///        %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
14285 ///        %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
14286 ///        %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
14287 ///        call void llvm.arm.neon.vst3(%ptr, %sub.v0, %sub.v1, %sub.v2, 4)
14288 bool ARMTargetLowering::lowerInterleavedStore(StoreInst *SI,
14289                                               ShuffleVectorInst *SVI,
14290                                               unsigned Factor) const {
14291   assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
14292          "Invalid interleave factor");
14293 
14294   VectorType *VecTy = SVI->getType();
14295   assert(VecTy->getVectorNumElements() % Factor == 0 &&
14296          "Invalid interleaved store");
14297 
14298   unsigned LaneLen = VecTy->getVectorNumElements() / Factor;
14299   Type *EltTy = VecTy->getVectorElementType();
14300   VectorType *SubVecTy = VectorType::get(EltTy, LaneLen);
14301 
14302   const DataLayout &DL = SI->getModule()->getDataLayout();
14303 
14304   // Skip if we do not have NEON and skip illegal vector types. We can
14305   // "legalize" wide vector types into multiple interleaved accesses as long as
14306   // the vector types are divisible by 128.
14307   if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
14308     return false;
14309 
14310   unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
14311 
14312   Value *Op0 = SVI->getOperand(0);
14313   Value *Op1 = SVI->getOperand(1);
14314   IRBuilder<> Builder(SI);
14315 
14316   // StN intrinsics don't support pointer vectors as arguments. Convert pointer
14317   // vectors to integer vectors.
14318   if (EltTy->isPointerTy()) {
14319     Type *IntTy = DL.getIntPtrType(EltTy);
14320 
14321     // Convert to the corresponding integer vector.
14322     Type *IntVecTy =
14323         VectorType::get(IntTy, Op0->getType()->getVectorNumElements());
14324     Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
14325     Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
14326 
14327     SubVecTy = VectorType::get(IntTy, LaneLen);
14328   }
14329 
14330   // The base address of the store.
14331   Value *BaseAddr = SI->getPointerOperand();
14332 
14333   if (NumStores > 1) {
14334     // If we're going to generate more than one store, reset the lane length
14335     // and sub-vector type to something legal.
14336     LaneLen /= NumStores;
14337     SubVecTy = VectorType::get(SubVecTy->getVectorElementType(), LaneLen);
14338 
14339     // We will compute the pointer operand of each store from the original base
14340     // address using GEPs. Cast the base address to a pointer to the scalar
14341     // element type.
14342     BaseAddr = Builder.CreateBitCast(
14343         BaseAddr, SubVecTy->getVectorElementType()->getPointerTo(
14344                       SI->getPointerAddressSpace()));
14345   }
14346 
14347   assert(isTypeLegal(EVT::getEVT(SubVecTy)) && "Illegal vstN vector type!");
14348 
14349   auto Mask = SVI->getShuffleMask();
14350 
14351   Type *Int8Ptr = Builder.getInt8PtrTy(SI->getPointerAddressSpace());
14352   Type *Tys[] = {Int8Ptr, SubVecTy};
14353   static const Intrinsic::ID StoreInts[3] = {Intrinsic::arm_neon_vst2,
14354                                              Intrinsic::arm_neon_vst3,
14355                                              Intrinsic::arm_neon_vst4};
14356 
14357   for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
14358     // If we generating more than one store, we compute the base address of
14359     // subsequent stores as an offset from the previous.
14360     if (StoreCount > 0)
14361       BaseAddr = Builder.CreateConstGEP1_32(BaseAddr, LaneLen * Factor);
14362 
14363     SmallVector<Value *, 6> Ops;
14364     Ops.push_back(Builder.CreateBitCast(BaseAddr, Int8Ptr));
14365 
14366     Function *VstNFunc =
14367         Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
14368 
14369     // Split the shufflevector operands into sub vectors for the new vstN call.
14370     for (unsigned i = 0; i < Factor; i++) {
14371       unsigned IdxI = StoreCount * LaneLen * Factor + i;
14372       if (Mask[IdxI] >= 0) {
14373         Ops.push_back(Builder.CreateShuffleVector(
14374             Op0, Op1, createSequentialMask(Builder, Mask[IdxI], LaneLen, 0)));
14375       } else {
14376         unsigned StartMask = 0;
14377         for (unsigned j = 1; j < LaneLen; j++) {
14378           unsigned IdxJ = StoreCount * LaneLen * Factor + j;
14379           if (Mask[IdxJ * Factor + IdxI] >= 0) {
14380             StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
14381             break;
14382           }
14383         }
14384         // Note: If all elements in a chunk are undefs, StartMask=0!
14385         // Note: Filling undef gaps with random elements is ok, since
14386         // those elements were being written anyway (with undefs).
14387         // In the case of all undefs we're defaulting to using elems from 0
14388         // Note: StartMask cannot be negative, it's checked in
14389         // isReInterleaveMask
14390         Ops.push_back(Builder.CreateShuffleVector(
14391             Op0, Op1, createSequentialMask(Builder, StartMask, LaneLen, 0)));
14392       }
14393     }
14394 
14395     Ops.push_back(Builder.getInt32(SI->getAlignment()));
14396     Builder.CreateCall(VstNFunc, Ops);
14397   }
14398   return true;
14399 }
14400 
14401 enum HABaseType {
14402   HA_UNKNOWN = 0,
14403   HA_FLOAT,
14404   HA_DOUBLE,
14405   HA_VECT64,
14406   HA_VECT128
14407 };
14408 
14409 static bool isHomogeneousAggregate(Type *Ty, HABaseType &Base,
14410                                    uint64_t &Members) {
14411   if (auto *ST = dyn_cast<StructType>(Ty)) {
14412     for (unsigned i = 0; i < ST->getNumElements(); ++i) {
14413       uint64_t SubMembers = 0;
14414       if (!isHomogeneousAggregate(ST->getElementType(i), Base, SubMembers))
14415         return false;
14416       Members += SubMembers;
14417     }
14418   } else if (auto *AT = dyn_cast<ArrayType>(Ty)) {
14419     uint64_t SubMembers = 0;
14420     if (!isHomogeneousAggregate(AT->getElementType(), Base, SubMembers))
14421       return false;
14422     Members += SubMembers * AT->getNumElements();
14423   } else if (Ty->isFloatTy()) {
14424     if (Base != HA_UNKNOWN && Base != HA_FLOAT)
14425       return false;
14426     Members = 1;
14427     Base = HA_FLOAT;
14428   } else if (Ty->isDoubleTy()) {
14429     if (Base != HA_UNKNOWN && Base != HA_DOUBLE)
14430       return false;
14431     Members = 1;
14432     Base = HA_DOUBLE;
14433   } else if (auto *VT = dyn_cast<VectorType>(Ty)) {
14434     Members = 1;
14435     switch (Base) {
14436     case HA_FLOAT:
14437     case HA_DOUBLE:
14438       return false;
14439     case HA_VECT64:
14440       return VT->getBitWidth() == 64;
14441     case HA_VECT128:
14442       return VT->getBitWidth() == 128;
14443     case HA_UNKNOWN:
14444       switch (VT->getBitWidth()) {
14445       case 64:
14446         Base = HA_VECT64;
14447         return true;
14448       case 128:
14449         Base = HA_VECT128;
14450         return true;
14451       default:
14452         return false;
14453       }
14454     }
14455   }
14456 
14457   return (Members > 0 && Members <= 4);
14458 }
14459 
14460 /// \brief Return true if a type is an AAPCS-VFP homogeneous aggregate or one of
14461 /// [N x i32] or [N x i64]. This allows front-ends to skip emitting padding when
14462 /// passing according to AAPCS rules.
14463 bool ARMTargetLowering::functionArgumentNeedsConsecutiveRegisters(
14464     Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
14465   if (getEffectiveCallingConv(CallConv, isVarArg) !=
14466       CallingConv::ARM_AAPCS_VFP)
14467     return false;
14468 
14469   HABaseType Base = HA_UNKNOWN;
14470   uint64_t Members = 0;
14471   bool IsHA = isHomogeneousAggregate(Ty, Base, Members);
14472   DEBUG(dbgs() << "isHA: " << IsHA << " "; Ty->dump());
14473 
14474   bool IsIntArray = Ty->isArrayTy() && Ty->getArrayElementType()->isIntegerTy();
14475   return IsHA || IsIntArray;
14476 }
14477 
14478 unsigned ARMTargetLowering::getExceptionPointerRegister(
14479     const Constant *PersonalityFn) const {
14480   // Platforms which do not use SjLj EH may return values in these registers
14481   // via the personality function.
14482   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R0;
14483 }
14484 
14485 unsigned ARMTargetLowering::getExceptionSelectorRegister(
14486     const Constant *PersonalityFn) const {
14487   // Platforms which do not use SjLj EH may return values in these registers
14488   // via the personality function.
14489   return Subtarget->useSjLjEH() ? ARM::NoRegister : ARM::R1;
14490 }
14491 
14492 void ARMTargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
14493   // Update IsSplitCSR in ARMFunctionInfo.
14494   ARMFunctionInfo *AFI = Entry->getParent()->getInfo<ARMFunctionInfo>();
14495   AFI->setIsSplitCSR(true);
14496 }
14497 
14498 void ARMTargetLowering::insertCopiesSplitCSR(
14499     MachineBasicBlock *Entry,
14500     const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
14501   const ARMBaseRegisterInfo *TRI = Subtarget->getRegisterInfo();
14502   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
14503   if (!IStart)
14504     return;
14505 
14506   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
14507   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
14508   MachineBasicBlock::iterator MBBI = Entry->begin();
14509   for (const MCPhysReg *I = IStart; *I; ++I) {
14510     const TargetRegisterClass *RC = nullptr;
14511     if (ARM::GPRRegClass.contains(*I))
14512       RC = &ARM::GPRRegClass;
14513     else if (ARM::DPRRegClass.contains(*I))
14514       RC = &ARM::DPRRegClass;
14515     else
14516       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
14517 
14518     unsigned NewVR = MRI->createVirtualRegister(RC);
14519     // Create copy from CSR to a virtual register.
14520     // FIXME: this currently does not emit CFI pseudo-instructions, it works
14521     // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
14522     // nounwind. If we want to generalize this later, we may need to emit
14523     // CFI pseudo-instructions.
14524     assert(Entry->getParent()->getFunction().hasFnAttribute(
14525                Attribute::NoUnwind) &&
14526            "Function should be nounwind in insertCopiesSplitCSR!");
14527     Entry->addLiveIn(*I);
14528     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
14529         .addReg(*I);
14530 
14531     // Insert the copy-back instructions right before the terminator.
14532     for (auto *Exit : Exits)
14533       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
14534               TII->get(TargetOpcode::COPY), *I)
14535           .addReg(NewVR);
14536   }
14537 }
14538 
14539 void ARMTargetLowering::finalizeLowering(MachineFunction &MF) const {
14540   MF.getFrameInfo().computeMaxCallFrameSize(MF);
14541   TargetLoweringBase::finalizeLowering(MF);
14542 }
14543